将C函数转换为Lua函数

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

function OnPlayerDeath(playerid)

end

我希望在 Lua C 模块内调用此函数,而不是将其放在 Lua 脚本中:

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

  // 所以这里我可以使用 playerid 参数 - 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 函数。

点赞
用户2198692
用户2198692

如果你想要从 C API 在 Lua 中运行它,你需要以某种方式将它推到栈中。如果它已经存在于全局表中,你可以通过调用 lua_getglobal 来将其压入栈中。在调用 lua_call (lua_pcall) 之前,需要将要调用的函数及其参数存在于栈顶。

如果你想了解的话,可以查看 LuaJIT ffi 回调特性,但这不是纯 Lua。

2013-04-16 16:23:55
用户1857483
用户1857483

解决。 W.B. 可能行。

解决方案: 从 C 中调用 loadstring。

2013-04-16 16:58:32