调用ac函数时获取lua命令

Nic*_*nks 8 c c++ lua

假设我在Lua中将许多不同的函数名注册到C中的相同函数.现在,每次调用我的C函数时,有没有办法确定调用了哪个函数名?

例如:

int runCommand(lua_State *lua)
{
  const char *name = // getFunctionName(lua) ? how would I do this part
  for(int i = 0; i < functions.size; i++)
    if(functions[i].name == name)
      functions[i].Call()
}

int main()
{
  ...

  lua_register(lua, "delay", runCommand);
  lua_register(lua, "execute", runCommand);
  lua_register(lua, "loadPlugin", runCommand);
  lua_register(lua, "loadModule", runCommand);
  lua_register(lua, "delay", runCommand);
}
Run Code Online (Sandbox Code Playgroud)

那么,我如何获得所谓的函数的名称呢?

sbk*_*sbk 11

攻击你的问题的另一种方法是使用upvalues.基本上,您使用以下函数注册C函数,而不是lua_register:

void my_lua_register(lua_State *L, const char *name, lua_CFunction f)
{
      lua_pushstring(L, name);
      lua_pushcclosure(L, f, 1);
      lua_setglobal(L, name);
}
Run Code Online (Sandbox Code Playgroud)

然后,getFunctionName是直接的

const char* getFunctionName(lua_State* L)
{
    return lua_tostring(L, lua_upvalueindex(1));
}
Run Code Online (Sandbox Code Playgroud)

那就是说,你想要做的事似乎有点可疑 - 你想要达到什么目的?runCommand问题中发布的函数看起来像是一种非常低效的方式来做Lua为你做的事情.