gpt4 book ai didi

c++ - 从 C++ 调用未知(按名称)lua 函数

转载 作者:太空狗 更新时间:2023-10-29 20:38:49 24 4
gpt4 key购买 nike

这是我想做的:

1) 有一个用户定义的lua函数,不知道名字。说是:

function f(x) return 2*x; end

2) 然后用户将从 Lua 中调用函数(在步骤 3 中设计),例如:

a=foo(f,3) --expecting a=6

3) foo 的 C++ 函数是:

int lua_foo(lua_State *L)
{
int nargs = lua_gettop(L);
if(nargs<2) throw "ERROR: At least two arguments i) Function ii) number must be supplied";


int type = lua_type(L, 1);
if(type!=LUA_TFUNCTION) throw "ERROR: First argument must be a function";

double arg2=lua_tonumber(L,2);
lua_pushnumber(L,arg2);

lua_pcall(L, 1, 1, 0) ; //trying to call the function f

double result=lua_tonumber(L,-1); //expecting the result to be 6
lua_pushnumber(L,result);

lua_pop(L,nargs);

return 1;
}

在 C++ 代码中,我知道第一个参数是一个函数,第二个参数是一个数字。我正在尝试使用第二个参数(数字)作为其参数来调用第一个参数(函数)。

最佳答案

如果函数设计如下:

/* avoid `lua_` (or `luaL_`) prefix for your own functions */
static int l_foo(lua_State *L)
{
/* `lauxlib.h` contains a lot of useful helper functions, e.g. for
* argument type checking: */
luaL_checktype(L, 1, LUA_TFUNCTION);
luaL_checknumber(L, 2);
/* discard any extra arguments to `foo`; ignoring extra arguments
* is customary for Lua functions */
lua_settop(L, 2);
/* the `lua_settop()` above ensures that the two topmost elements
* of the stack are the function `f` and its argument, so
* everything is set for the `lua_call()` */
lua_call(L, 1, 1);
/* return the topmost value on the Lua stack (the result); all
* other stack values are removed by Lua automatically (but in
* this case the result is the only value on the stack as the
* `lua_call()` popped the function and the argument, and pushed
* one result) */
return 1;
}

它按预期工作。

关于c++ - 从 C++ 调用未知(按名称)lua 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30475204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com