读取Lua表并使用c++将其放入JSON对象

Read Lua table and put into JSON object using C++

本文关键字:JSON 对象 c++ Lua 读取      更新时间:2023-10-16

在尝试将Lua脚本系统与用于输出的JSON库集成时,我遇到了困难。

我想得到我调用的任何Lua函数返回并将其转换为JSON(我试图使用这个库),但这个任务被证明是完全困难的。

这是我迄今为止最远的尝试:

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。第一个可以工作,所以我认为我对堆栈的操作有些错误。

我试着学习正确的方法,但是很难理解。进程终止,并显示以下消息:

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