在C++ LUA对象
问题描述:
我要让这样的工作:
1.创建对象在Lua
2.获取该对象到C++
3.此对象从C++
在C++ LUA对象
现在我有这个在Lua:
Account = {balance = 0}
function Account.Create(name)
local a = Account:new(nil, name);
return a;
end
function Account:new (o, name)
o = o or {name=name}
setmetatable(o, self)
self.__index = self
return o
end
function Account:Info()
return self.name;
end
代码在C++
//get Lua object
lua_getglobal (L, "Account");
lua_pushstring(L, "Create");
lua_gettable(L, -2);
lua_pushstring(L, "SomeName");
lua_pcall(L, 1, 1, 0);
const void* pointer = lua_topointer(L, -1);
lua_pop(L, 3);
//then I want to perform some method on object
lua_getglobal (L, "Account");
lua_pushstring(L, "Info");
lua_gettable(L, -2);
lua_pushlightuserdata(L,(void*) pointer);
lua_pcall(L, 0, 1, 0);
//NOW I GET "attempt to index local 'self' (a userdata value)'
const char* str = lua_tostring(L, -1);
...etc...
你我做错了什么?我怎样才能得到这个Lua对象到C++?
答
const void* pointer = lua_topointer(L, -1);
Lua表不是C对象。他们不是void*
s。 lua_topointer
documentation表示该函数主要用于调试目的。你没有调试任何东西。
只能通过Lua API访问Lua表。你不能只是得到一个指向一个Lua表或其他东西的指针。相反,你需要做的是将Lua表存储在一个地方,然后当你想要访问它时,从那个位置检索它。存储这类数据的典型地方是Lua注册表。从Lua代码无法访问;只有C-API可以与之通话。
通常,您将在注册表中存储一些表,其中包含您当前拥有的所有Lua值。这样,您使用注册表不会使别人使用它。