我目前正在使用以下代码从表中获取值 (cstring = const char*):
template<>
cstring luaTable::get(cstring name) {
prep_get(name); // puts table[name] at -1 in stack
cstring result;
if(!lua_isstring(L, -1)) {
report(name, "is not a string");
result = "";
}
else {
result = lua_tostring(L, -1);
}
lua_pop(L, 1);
return result;
}
void luaTable::prep_get(cstring name) {
lua_pushstring(L, name); // name at -1, table at -2
lua_gettable(L, -2);
// table[name] is now at position -1 in stack
}
这非常适用于 table = {a=10, b=2}
形式的表格。我如何修改它以从没有键的表中获取值,例如 table = {10, 2}
?
我确信我遗漏了一些简单但似乎无法找到答案的东西。
提前致谢, 本
编辑:添加了一些 pops
最佳答案
好吧,很抱歉这么快就回答我自己的问题 - 但灵感的快速闪现导致:
void luaTable::prep_get(cstring name) {
lua_pushstring(L, name); // name string at -1
if(lua_isnumber(L, -1)) { // call prep_get("i") for ith element etc
int key = lua_tonumber(L, -1);
lua_pop(L, 1); // remove the name string from -1
lua_pushnumber(L, key); // push name number to -1
}
lua_gettable(L, -2);
// result is now at position -1 in stack
}
按预期工作。
关于c++ - 通过整数键从 C 获取 lua 表条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15418444/