C ++& Lua,推Lua表作为论据

时间:2012-06-26 20:26:57

标签: c++ function lua lua-table

我正在用C ++集成Lua,现在我把这个表作为'类',对于某些函数,它需要一个'self'参数,实际上就是表。 Lua代码:

a = {
numb = 5,

create = function(a)
    print(a);
end,

increment = function(self)
                            --self.numb = 6;
                            print(self.numb);
end,

decrement = function(self,i)
                            self.numb = self.numb-i;
                            print(self.numb);
end
};
b = a;

调用函数的C ++位(我已经用C ++运行了Lua)

luaL_openlibs(L);

luaL_dofile (L,"main.lua");

lua_getglobal(L, "a");
lua_getfield(L, -1, "increment");

string arg = "a";

lua_pushliteral(L,"a");

lua_pcall(L ,1,0,0);

printf(" \nI am done with Lua in C++.\n");

lua_close(L);

那么,我怎样才能将self参数作为表传递给函数增量?

感谢任何帮助

1 个答案:

答案 0 :(得分:1)

在Lua 5.1中,您使用lua_getglobal来获取全局信息,例如您的表a - 您正在使用它来使您的桌子只有几行;您需要做的就是复制该值以将其传递给您的函数

 lua_getglobal(L, "a"); // the table a is now on the stack
 lua_getfield(L, -1, "increment"); // followed by the value of a.increment

 lua_pushvalue(L,-2); // get the table a as the argument

 lua_pcall(L,1,0,0);