提问人:Jepessen 提问时间:9/1/2023 更新时间:9/1/2023 访问量:40
在 C/C++ 中读取嵌套 lua 脚本的键和值
Read both key and values of a nested lua script in C/C++
问:
我有以下 lua 脚本,其中我使用一个 C++ 函数,该函数需要读取嵌套表的键和值:
local scenariolist = {
scenarios = {
'scenario1',
'scenario3',
'scenario2'
},
result = true,
message = 'test message'
}
my.sendfromscenariolist(scenariolist)
这是我的C++函数,在调用时执行:sendfromscenariolist
int ScenarioFunction(lua_State* L) {
int nargs = lua_gettop(L);
if (nargs != 1) {
return 0;
}
int type = lua_type(L, 1);
if (type != LUA_TTABLE) {
return 0;
}
ParseScenarioTable(L);
return 0;
}
void ParseScenarioTable(lua_State* L) {
lua_pushnil(L);
while (lua_next(L, -2) != 0) {
if (lua_istable(L, -1)) {
ParseScenarioTable(L);
std::cout << "Key: " << "key" << ", Value is table" << std::endl;
}
else if (lua_isstring(L, -1)) {
std::string x = lua_tostring(L, -1);
std::cout << "Key: " << "key" << ", Value: " << x << std::endl;
int i = 0;
}
else if (lua_isboolean(L, -1)) {
bool x = lua_toboolean(L, -1);
int i = 0;
std::cout << "Key: " << "key" << ", Value: " << x << std::endl;
}
lua_pop(L, 1);
}
}
这个函数只读值,它工作,当我在控制台中运行它时,我得到:
Key: key, Value: 1
Key: key, Value: scenario1
Key: key, Value: scenario3
Key: key, Value: scenario2
Key: key, Value is table
Key: key, Value: test message
问题是我无法读取嵌套表元素的键。我用这个更改了我的代码:
int ScenarioFunction(lua_State* L) {
int nargs = lua_gettop(L);
if (nargs != 1) {
return 0;
}
int type = lua_type(L, 1);
if (type != LUA_TTABLE) {
return 0;
}
ParseScenarioTable(L);
return 0;
}
void ParseScenarioTable(lua_State* L) {
lua_pushnil(L);
while (lua_next(L, -2) != 0) {
if (lua_istable(L, -1)) {
std::string key = lua_tostring(L, -2);
ParseScenarioTable(L);
std::cout << "Key: " << key << ", Value is table" << std::endl;
}
else if (lua_isstring(L, -1)) {
std::string key = lua_tostring(L, -2);
std::string x = lua_tostring(L, -1);
std::cout << "Key: " << key << ", Value: " << x << std::endl;
int i = 0;
}
else if (lua_isboolean(L, -1)) {
std::string key = lua_tostring(L, -2);
bool x = lua_toboolean(L, -1);
int i = 0;
std::cout << "Key: " << key << ", Value: " << x << std::endl;
}
lua_pop(L, 1);
}
}
但是如果我尝试读取密钥,程序将中断并收到错误: 这是我程序的输出:
Key: result, Value: 1
Key: 1, Value: scenario1
[2023-09-01 16:17:03.391093][error]: Error when running the script. Error is: invalid key to 'next'
其中 是 Lua 的错误字符串。invalid key to 'next'
我做错了什么?如何读取键和值?
答:
3赞
ESkri
9/1/2023
#1
问题出在这里:
std::string key = lua_tostring(L, -2);
修改了它的参数:它在 API 堆栈索引处将 number 替换为 string ,因此 following 无法继续遍历表,因为它接收的是不存在的密钥而不是现有的 。
此行为在手册中进行了描述。lua_tostring
1
"1"
-2
lua_next
"1"
1
解决方案:
为要修改的值创建额外的临时堆栈槽。
取代lua_tostring
std::string key = lua_tostring(L, -2);
跟
lua_pushvalue(L, -2);
std::string key = lua_tostring(L, -1);
lua_pop(L, 1);
评论