【发布时间】: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 无关) :)
【问题讨论】:
-
将其简化为仅复制您的问题的代码,那里的噪音太多,无法看到您要做什么。
-
我需要解释我做了什么来解决这个问题。可能是我初始化错了。