简体   繁体   中英

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

I'm having a hard time while trying to integrate a Lua scripted system with a JSON library for outputting.

I want to get whatever the Lua function I'm calling returns and convert it to JSON (I'm trying to use this lib ), but this task is proving utterly hard.

That's my farthest try so far:

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);
    }

    (...)
}

The Lua script running is:

function onRequest()
    return {
        ["bool"] = true,
        ["number"] = 50.0,
        ["string"] = "test",
    }
end

This is crashing at while (lua_next(L, -2) != 0) { , and I can't figure out why. It always happens when trying to get the second table value, in that case ["number"] = 50.0 . The first one works, so I think I'm manipulating the stack somewhat wrong.

I'm trying to learn the right way with this , but it's hard to understand. The process aborts with the following message:

PANIC: unprotected error in call to Lua API (invalid key to 'next')
terminate called without an active exception
Signal: SIGABRT (Aborted)

So I guess that message is wrong somehow. Easy to guess, it's 11 years old, and Lua API must have changed a lot since then. What am I doing wrong to get that abort signal when trying to access the next table value, and why does it happen only on the second key?

Remove

    lua_pop(L, 1);

in parseLuaValue .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM