我在尝试将 Lua 脚本系统与 JSON 库集成以进行输出时遇到了困难。
我想获取我正在调用的 Lua 函数返回的任何内容并将其转换为 JSON(我正在尝试使用 this lib ),但事实证明这项任务非常困难。
这是我迄今为止最远的尝试:
void parseTable(lua_State* L, json& result)
{
lua_pushnil(L);
while (lua_next(L, -2) != 0) {
auto key = lua_tostring(L, -2);
auto value = parseLuaValue(L);
result[key] = value;
lua_pop(L, 1);
}
}
json parseLuaValue(lua_State* L)
{
json result;
auto type = lua_type(L, -1);
if (type == LUA_TBOOLEAN) {
result = lua_toboolean(L, -1) != 0;
} else if (type == LUA_TNUMBER) {
result = lua_tonumber(L, -1);
} else if (type == LUA_TSTRING) {
result = lua_tostring(L, -1);
} else if (type == LUA_TTABLE) {
parseTable(L, result);
};
lua_pop(L, 1);
return result;
}
json JSONScriptInterface::callFunction(int params)
{
json result;
int size = lua_gettop(m_luaState);
if (protectedCall(m_luaState, params, 1) != 0) {
LuaScriptInterface::reportError(nullptr, LuaScriptInterface::getString(m_luaState, -1));
} else {
result = parseLuaValue(m_luaState);
}
(...)
}
运行的Lua脚本是:
function onRequest()
return {
["bool"] = true,
["number"] = 50.0,
["string"] = "test",
}
end
这在 while (lua_next(L, -2) != 0) {
时崩溃了,我不知道为什么。它总是在尝试获取第二个表值时发生,在这种情况下 ["number"] = 50.0
。第一个有效,所以我认为我对堆栈的操作有些错误。
我正在尝试通过 this 学习正确的方法,但很难理解。该过程中止并显示以下消息:
PANIC: unprotected error in call to Lua API (invalid key to 'next')
terminate called without an active exception
Signal: SIGABRT (Aborted)
所以我猜这个消息不知何故是错误的。很容易猜到,它已经 11 岁了,从那以后 Lua API 一定发生了很大变化。我在尝试访问下一个表值时获取该中止信号做错了什么,为什么它只发生在第二个键上?
最佳答案
移除
lua_pop(L, 1);
在 parseLuaValue
中。
关于c++ - 使用 C++ 读取 Lua 表并放入 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31889691/