1

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

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

在此先感谢,本

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

4

2 回答 2

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
}

根据需要工作。

于 2013-03-14T19:40:44.110 回答
0

@user1483596 I don't think that solution would work. lua_isnumber will only return true if the value is of type number, and you just pushed a string, so it will always return false.

Instead, try something like this:

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);
}

Bear in mind though that it won't handle a special case. In Lua a[1] and a["1"] are different. If you use this function, you'll always treat numbers as array indices, even if they're not.

If you want to differentiate both cases, then you could overload prep_get and take a number.

于 2013-03-14T20:32:43.387 回答