我正在将Lua集成到C++中,现在有了这个表,它的行为像一个“类”,对于某些功能,它需要一个“自我”自变量,实际上就是该表。 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参数作为表格传递给函数增量呢?
任何帮助表示赞赏
最佳答案
在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);
关于c++ - C++和Lua,将Lua表作为参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11215400/