分享

返回C++类给LUA脚本 ? LuaIE

 quasiceo 2014-01-17
返回C++类给LUA脚本
        2013/07/10

这里演示了如何返回一个C++指针类给LUA脚本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class MyClass
{
public:
  void say()
  {
    print("Hello\r\n");
  }
};
int test(lua_State* l)
{
  MyClass** c = (MyClass**)lua_newuserdata(l, sizeof(MyClass*));
  *c = new MyClass();       // we manage this
  luaL_setmetatable(l, "MyClass");  //assign MyClass metatable
  return 1;
}
void l_registerClass()
{
  lua_newtable(l);
  int methods = lua_gettop(l);
  luaL_newmetatable(l, "MyClass");
  int metatable = lua_gettop(l);
  lua_pushvalue(l, methods);
  lua_setglobal(l, "MyClass");
  lua_pushvalue(l, methods); 
  l_set(l, metatable, "__metatable");
  //set metatable __index
  lua_pushvalue(l, methods);
  l_set(l, metatable, "__index");
  //set metatable __gc
  lua_pushcfunction(l, l_destructor); 
  l_set(l, metatable, "__gc");
  //set method table
  lua_newtable(l);                // mt for method table 
  lua_pushcfunction(l, l_constructor); 
  lua_pushvalue(l, -1);           // dup new_T function 
  l_set(l, methods, "new");         // add new_T to method table 
  l_set(l, -3, "__call");           // mt.__call = new_T 
  lua_setmetatable(l, methods); 
  // set methods metatable  
  lua_pushstring(l, "say");
  lua_pushcclosure(l, l_proxy, 1); 
  lua_settable(l, methods);
  lua_pop(l, 2);
}
int l_proxy(lua_State* l)
{
  int i = (int)lua_tonumber(l, lua_upvalueindex(1));
  lua_remove(l, 1);  // remove self so member function args start at index 1
  //call real function
  MyClass* obj = getInstance();
  obj->say();
  return 1;
}

//lua script

 

1
2
3
4
local a = MyClass:new()
a:say()  <--- OK, beacause I set metatable!!
local b = test()
b:say()
文本为LuaIE原创文章返回C++类给LUA脚本

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多