gpt4 book ai didi

c++ - 将 C 函数转换为 Lua 函数

转载 作者:行者123 更新时间:2023-11-28 07:39:58 25 4
gpt4 key购买 nike

假设我有一个在指定玩家死亡时执行的回调函数。

function OnPlayerDeath(playerid)

end

我想在 Lua C 模块中调用这个函数,而不是将它放在 lua 脚本中:

static int l_OnPlayerConnect (lua_State * L) {
enum { lc_nformalargs = 1 };
lua_settop(L,1);

// so here I can use playerid argument - 1 arg

return 0;
}

是否有可能在 C 语言中接收此回调参数?

#define LUA extern "C" __declspec(dllexport) int __cdecl

LUA luaopen_mymodule(lua_State *L)
{
/* function OnPlayerConnect( playerid )
*
* end */
lua_pushcfunction(L,l_OnPlayerConnect);
lua_setfield(L,LUA_GLOBALSINDEX,"OnPlayerConnect"); //there's already OnPlayerConnect I just want to also call it here but I don't know how.
assert(lua_gettop(L) - lc_nextra == 0);

return 1;
}

我不想将这个函数压入 lua 堆栈,因为这个函数已经存在。我只希望它是已经存在的 Lua 函数。

最佳答案

如果你想通过 C API 在 Lua 中运行它,你需要以一种或另一种方式将它压入堆栈。如果它已经存在于全局表的某个地方,你可以通过调用 lua_getglobal 来推送它。 lua_call (lua_pcall) 要求函数被调用并且它的参数在调用之前存在于栈顶。

如果你喜欢,你可以检查 LuaJIT ffi 回调特性,但它不是普通的 Lua。

关于c++ - 将 C 函数转换为 Lua 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16041946/

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