【问题标题】:Get lua table entry from C via integer key通过整数键从 C 获取 lua 表条目
【发布时间】:2013-03-15 04:32:43
【问题描述】:

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

我确定我错过了一些简单的东西,但似乎找不到答案。

提前致谢, 本

编辑:添加了一些流行音乐

【问题讨论】:

    标签: c++ lua lua-table


    【解决方案1】:

    好吧,很抱歉这么快就回答我自己的问题 - 但是灵感的快速闪现导致:

    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
    }
    

    按需要工作。

    【讨论】:

      【解决方案2】:

      @user1483596 我认为该解决方案行不通。 lua_isnumber 只会在值是 number 类型时返回 true,并且你只是推送了一个字符串,所以它总是返回 false。

      请尝试以下方法:

      void luaTable::prep_get(cstring name) {
         int num = strtol(name, 0, 0);
         if (num > 0) {
            lua_pushnumber(L, num);
         } else {
            lua_pushstring(L, name);
         }
         lua_gettable(L, -2);
      }
      

      请记住,它不会处理特殊情况。在 Lua 中 a[1] 和 a["1"] 是不同的。如果您使用此函数,您将始终将数字视为数组索引,即使它们不是。

      如果你想区分这两种情况,那么你可以重载 prep_get 并取一个数字。

      【讨论】:

        猜你喜欢
        • 2010-12-18
        • 1970-01-01
        • 2011-02-11
        • 2015-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多