luabind + hge + lua 使用方法总结

来源:互联网 发布:sql server 2005 32 编辑:程序博客网 时间:2024/05/17 09:34

转自: http://hi.baidu.com/xjxxjx1017/blog/item/8fdcbbfce75b1b89b801a037.html


网上关于这方面的资料真少啊... 我自己都不得不从google找资料.

google时, 有时候中国的IP会被屏蔽, 打不开的网页可以试一试在线代理, 比如酷摆.

下面是正题:

      在我仔细看了luabind的说明之后, 发现luabind对引用和指针都有很好的支持, 并不是没有办法.

下面这一段就专门说了, luabind对于引用和指针用了一个叫Pilicies的处理办法.
//--14   Policies
Sometimes it is necessary to control how luabind passes arguments and return value, to do this we have policies. All policies use an index to associate them with an argument in the function signature. These indices are result and _N (where N >= 1). When dealing with member functions _1 refers to the this pointer.
14.1   adopt 
14.2   dependency 
14.3   out_value 
14.4   pure_out_value 
14.5   return_reference_to 
14.6   copy 
14.7   discard_result 
14.8   return_stl_iterator 
14.9   raw 
14.10   yield

具体的就google吧, http://www.rasterbar.com/products/luabind/docs.html, 这个用在线代理就看得到, 是luabind的说明书.

然后呢...我自己总结了一些开发工作中常用的东西, 大致都写在了一个叫备注的文档里, 现在贴出来, 看不懂的也没关系, 觉得好用的就拿来用吧.


//--lua && stl (仅遍历适用)-------OK

#include <luabind/iterator_policy.hpp>
struct X
{
    std::vector<std::string> names;
};
module(L)
[
    class_<X>("X")

        .def (constructor<>())
        .def_readwrite("names", &X::names, return_stl_iterator)
];
> x = X()
> for name in x.names do
> print(name)
> end

//参照网上的, 自己添加了一个iterator_map_policy.hpp, 使得lua可对map进行遍历. 要的话留个邮箱.

//iterator做返回值. --注意下面那个的返回值是引用

vector<string>& getNames () {...}

.def("getNames", &getNames, return_stl_iterator)

> for name in getNames() do
>      print(name)
> end

//--返回指针-----OK

#include <luabind/adopt_policy.hpp>
X* create()
{
    return new X;
}
module(L)
[
    def("create", &create, adopt(result))
];


//--返回引用

#include <luabind/dependency_policy.hpp>
struct X
{
    B member;
    B& get() { return member; }
};
module(L)
[
    class_<X>("X")
.def("get", &X::get, dependency(result, _1)),
];

//--nil可以用作逻辑判断
both nil and the boolean value false represent false in a logical expression

//--在lua脚本中对以下语句的尝试------OK
a = 1
if (a ~= nil) then a = nil end
if (a == nil) then a = 1 end

//--多行注释
用"--[["和"]]"将多行的字符串

//全局变量的操作 lua→c++, c++→lua
int ggg = object_cast<int>(globals(L)["ggg"]); 
luabind::globals(myLuaState)["MyResourceManager"] = &MyResourceManager

//hge+lua的错误处理
try
{
//调用lua函数
}
catch(luabind::error& e)
{
string tmp = e.what () + string (":\n") + lua_tostring(lua, -1);
MessageBox(NULL, tmp.c_str (), "luaError", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
}

//成员变量
module(L)
[
class_<A>("A")
.def_readwrite("val", &A::val)
];

//文件之间共享全局变量
luaL_dofile(L, "selfadd.txt");

//传递参数的引用给lua函数
call_function<A<int>>(L, "selfadd", boost::ref(tmp));


原创粉丝点击