如何在C ++中调用package.preload内部的函数 [英] How to call functions inside package.preload in C++
问题描述
我正在尝试调用 A:update(x)
并在C ++中获得返回值 x + 3
.
I'm trying to call A:update(x)
and get a returned value x + 3
in C++.
这是我的代码:
#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);
}
我希望它打印出 RETURNED:8
,但是出现以下错误:
I expect it to print RETURNED : 8
but I get the following error:
Thread 1:EXC_BAD_ACCESS (code=1, address=0x0)
我应该如何纠正我的代码才能正常工作?
How should I correct my code to work?
已我将 A:update(x)
更改为 A.update(x)
后,它立即起作用.我以为它们的工作原理相同,只是我可以在使用:
的函数中使用 self
.有人可以向我解释为什么会发生这种情况吗?
EDITED: It worked as soon as I change A:update(x)
to A.update(x)
. I thought they work identically except I can use self
in a function that uses :
. Could someone please explain to me why this happens?
推荐答案
符号 A:update(x)
是 A.update(A,x)
.这意味着您必须使用两个参数调用函数 update
.您缺少两个参数中的第一个.
The notation A:update(x)
is syntactic sugar for A.update(A,x)
. That means you have to call the function update
with two parameters. You are lacking the first of the two parameters.
第一个参数 A
已经在堆栈上,但是位于 update
函数的下方".使用 lua_pushvalue
,我们可以将表的副本推入堆栈.
The first parameter A
is already on the stack but is located "below" the update
function. Using lua_pushvalue
we can push a copy of the table onto the stack.
因此,您必须像这样调用函数(省略错误处理位)
Thus you have to call the function like this (omitting the error handling bits)
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);
这篇关于如何在C ++中调用package.preload内部的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!