将C函数转换为Lua函数

Converting C function to Lua function

本文关键字:函数 Lua 转换      更新时间:2023-10-16

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

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函数

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

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

解决。这是可能的W.B.

解决方案:从c调用loadstring