c++ - 通过整数键从 C 获取 lua 表条目

标签 c++ lua lua-table

我目前正在使用以下代码从表中获取值 (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/

相关文章:

c++ - 派生类中的功能与基类中的功能完全相同,但默认参数不同

android - Lua 可以单独用于应用程序开发吗?

c - 从 c api 内部创建 lua 表时出错

c++ - 用 C (mbed) 将字符写入文件?

c++ - Valgrind 与 dirname 决裂?

eclipse - 防止 Lua 表中的函数重写

lua - 为什么不能使用Set:union()代替Set.union?

lua - 如何在初始化期间自引用表

serialization - Lua table.toString(tableName) 和 table.fromString(stringTable) 函数?

c++ - 为什么我不能使用 for 循环更新像素数组?