如何在C++; < >我试图调用:更新(x)< />代码,在C++中得到返回值 x+3 >
这是我的密码:如何在C++; < >我试图调用:更新(x)< />代码,在C++中得到返回值 x+3 >,c++,lua,C++,Lua,这是我的密码: #include <lua.hpp> void main() { lua_State *L = luaL_newstate(); luaL_openlibs(L); lua_settop(L, 0); luaL_dostring(L, "package.preload['A'] = function () local A = {}\n" "function A:update(x) return
#include <lua.hpp>
void main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_settop(L, 0);
luaL_dostring(L, "package.preload['A'] = function () local A = {}\n"
"function A:update(x) return x + 3 end \n"
"return A end");
//call function
lua_getglobal(L, "require");
lua_pushstring(L, "A");
if (lua_pcall(L, 1, LUA_MULTRET, 0) != 0) {
std::cerr << "lua:" << lua_tostring(L, 1) << '\n';
lua_pop(L, 1);
}
int top = lua_gettop(L);
lua_getfield(L, -1, "update");
if (!lua_isfunction(L, -1))
{
std::cerr << "lua:" << lua_tostring(L, 1) << '\n';
lua_pop(L, 1);
}
lua_pushnumber(L, 5); //pass the argument 5
if (lua_pcall(L, 1, LUA_MULTRET, 0))
{
std::cerr << "lua:" << lua_tostring(L, 1) << '\n';
lua_pop(L, 1);
}
if (lua_gettop(L) - top)
{
if (lua_isnumber(L, -1))
{
std::cout << "RETURNED : " << lua_tonumber(L, -1) << std::endl;
}
}
lua_pop(L, 1); // pop 'update'
lua_pop(L, 1); // pop 'A'
lua_close(L);
}
我应该如何更正代码才能工作
编辑:当我将
A:update(x)
更改为A.update(x)
时,它就工作了。我认为它们的工作原理相同,只是我可以在使用:
的函数中使用self
。有人能给我解释一下为什么会这样吗?符号A:update(x)是A.update(A,x)
的语法糖。这意味着您必须使用两个参数调用函数update
。您缺少两个参数中的第一个
第一个参数A
已在堆栈上,但位于update
函数的“下方”。使用lua\u pushvalue
我们可以将表的副本推送到堆栈上
因此,您必须像这样调用函数(省略错误处理位)
您还必须使用
self
作为第一个参数调用A:update
。当前您正在调用A:update
,第一个参数为5
(完全忽略第二个参数)。谢谢您的回答。现在调用A:update(x)
没有问题。但是,在C++中,不可能调用<代码> >更新> /COD>和<代码> >:更新< <代码> @ ZkLee,通过定义<代码>函数A:更新(x)< /> >在Lua中,您已经指定它只能被称为“代码>:AUPDATE(X)< /C> >(这相当于代码> AUPDATE(A,X))。self
参数的神奇传递只在具有:
语法的Lua解释器中起作用。在C-API中,必须显式传递self
参数。
Thread 1:EXC_BAD_ACCESS (code=1, address=0x0)
lua_getfield(L, -1, "update");
lua_pushvalue(L, -2); // push a copy of "A" onto the stack
lua_pushnumber(L, 5); //pass the argument 5
lua_pcall(L, 2, LUA_MULTRET, 0);