在C++中使用Lua对象

我想做出这样的东西:

1. 在 Lua 中创建对象

2. 将该对象传递给 C++

3. 在 C++ 中对该对象执行某些方法


现在我有了 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++ 中的代码:

//获取 Lua 对象

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);

//接下来我想对该对象执行某些方法

lua_getglobal (L, "Account");
lua_pushstring(L, "Info");
lua_gettable(L, -2);
lua_pushlightuserdata(L,(void*) pointer );
lua_pcall(L, 0, 1, 0);
//现在我得到了 "attempt to index local 'self' (a userdata value)"
const char* str = lua_tostring(L, -1);
...等等...

我做错了什么?我如何将这个 Lua 对象传递给 C++?

点赞
用户734069
用户734069
const void* pointer = lua_topointer(L, -1);

Lua表不是C对象。它们不是void*lua_topointer文档指出该函数主要用于调试目的,你没有调试任何东西。

Lua表只能通过Lua API访问。你不能直接获得一个指向Lua表的指针。相反,你需要将Lua表存储在某个位置,当你想访问它时再从那个位置检索它。存储这种数据的典型位置是Lua注册表。它无法从Lua代码访问,只有C API才能与之通信。

通常,你会在注册表中存储一些表,这些表包含了你当前持有的所有Lua值。这样,你使用注册表时就不会影响到其他人的使用。

2012-05-29 21:11:41