读取Lua表并使用c++将其放入JSON对象
Read Lua table and put into JSON object using C++
在尝试将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
。
相关文章:
- 有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?
- 如何使用 picojson.h 在 c++ 中从头开始创建 json 对象
- .value( "key" , default) 不适用于空的 json 对象吗?
- Rapidjson 遍历并获取复杂 JSON 对象成员的值
- JSON对象到C++模型
- 使用 NLOHMANN JSON 在 C++ 中创建嵌套的 JSON 对象
- 如何在 c++ 中从两个向量创建 JSON 对象?
- 如何正确解析 Java+C++ TCP 连接中的 JSON 对象?
- 如何将矢量转换为 json 对象?C++
- 将C++具有 150+ 变量的类转换为 Json 对象
- Poco 迭代嵌套的 JSON 对象
- 如何提取由特定模式分开的JSON对象字符串
- 如何创建具有分层对象和值的 json 对象
- 将 JSON 对象作为参数在 JNI 中传递给 CPP,并在 CPP 中检索 JSON 对象的数据
- 无法区分 JSON 对象/数组/字符串
- 如何将 cpr 的获取响应转换为 json 对象?
- 我正在尝试打开一个 json 文件.并将其存储为 JSON 对象
- 如何在不更改 C++ 中的值的情况下更改 json 对象名称
- 如何将Nolhmann JSON对象分成字符串
- Cpp:Cpp中的JSON解析器,提供支持序列化/反序列化功能,将JSON对象转换为用户定义的类