【问题标题】:LuaJIT and C++ - call to Table.Method() does not work in loadstring/pcallLuaJIT 和 C++ - 调用 Table.Method() 在 loadstring/pcall 中不起作用
【发布时间】:2019-06-03 06:24:08
【问题描述】:

我有 2 个在 C++ 中注册 Lua 表和方法的函数:

void LuaScriptInterface::registerTable(const std::string& tableName)
{
    // _G[tableName] = {}
    lua_newtable(luaState);
    lua_setglobal(luaState, tableName.c_str());
}

void LuaScriptInterface::registerMethod(const std::string& globalName, const std::string& methodName, lua_CFunction func)
{
    // globalName.methodName = func
    lua_getglobal(luaState, globalName.c_str());
    lua_pushcfunction(luaState, func);
    lua_setfield(luaState, -2, methodName.c_str());

    // pop globalName
    lua_pop(luaState, 1);
}

它注册了一些方法:

registerTable("Game");
// Game.getHouses()
registerMethod("Game", "getHouses", LuaScriptInterface::luaGameGetHouses);

然后我调用 Lua:

local param = "print( Game.getHouses() )"
pcall(loadstring(param))

参数有问题。调用和结果:

1. print(Game.getHouses())
2. print(Game['getHouses']())
3. print( Game.getHouses() ) -- added spaces
4. print( Game['getHouses']() ) -- added spaces
5. local var = Game.getHouses() print(#var)
6. local var = Game['getHouses']() print(#var)
7. local var = #Game.getHouses() print(var)
8. local var = #Game['getHouses']() print(var)
9. local var = # Game.getHouses() print(var) -- added space

结果:

1. attempt to call a nil value
2. table: 0x4351fdd0
3. table: 0x42ce6b88
4. table: 0x426513c0
5. 1010
6. 1010 
7. attempt to call a nil value
8. 1010
9. 1010

谁能告诉我一个原因,为什么它在 loadstring/pcall 中不起作用?

我可以让它在 loadstring/pcall 中以某种方式工作吗?

编辑:

经过 2 小时的调试。我发现,我用来与服务器通信的客户端 - 执行 LUA - 对我发送的字符串执行了一些正则表达式(我仍然不知道为什么,但它与 LUA 无关) :)

【问题讨论】:

  • 将其简化为仅复制您的问题的代码,那里的噪音太多,无法看到您要做什么。
  • 我需要解释我做了什么来解决这个问题。可能是我初始化错了。

标签: c++ lua luajit


【解决方案1】:

您试图表示的问题是 someTable.key 给出的结果与 someTable["key"] 不同,但这不可能:

但是使用字符串常量作为键是很常见的,它有一个特殊的快捷语法:

> t = {}
> t.foo = 123 -- same as t["foo"] (but not t[foo], which would use the variable foo as the key)
> = t.foo
123
> = t["foo"]
123

仅当字符串由下划线、字母和数字组成时,快捷语法才有效,但不应以数字开头。 (http://lua-users.org/wiki/TablesTutorial)

由于它在loadstring 中不使用时有效,我怀疑您的问题与Player(cid) player:getId()"player:getPosition()" 有关。重要的是要注意您在两个不同的时间访问播放器。 1. 直接作为player:getId() 和 2. 虽然loadstring / pcall。最后一种可能性是Player(cid)。其中一个可能没有正确初始化/声明。

我认为由于测试条​​件不同,您的第二次尝试 local param = "print( #Game['getHouses']() )" 成功了。

【讨论】:

  • 你给你答复后,我又调试了一切。我发现我用来与服务器通信的客户端确实替换了我发送的文本中的一些字符组合。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多