【问题标题】:Converting C function to Lua function将 C 函数转换为 Lua 函数
【发布时间】:2013-04-17 00:58:32
【问题描述】:

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

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++ lua


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      解决了。有可能是 W.B.

      解决方案:从 C 调用 loadstring。

      【讨论】:

        猜你喜欢
        • 2020-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-22
        • 2011-12-24
        • 1970-01-01
        • 2020-03-18
        相关资源
        最近更新 更多