user1483596
user1483596

Reputation: 319

Get lua table entry from C via integer key

I am currently using the following code to get a value from a 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
}

This works perfectly for tables of form table = {a=10, b=2}. How can I modify it to get values from tables without keys such as table = {10, 2}?

I'm sure I'm missing something simple but can't seem to find the answer.

Thanks in advance, Ben

Edit: added some pops

Upvotes: 1

Views: 1180

Answers (2)

sergio
sergio

Reputation: 296

@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.

Upvotes: 0

user1483596
user1483596

Reputation: 319

Okay sorry to answer my own question so soon - but a quick flash of inspiration lead to:

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
}

which works as desired.

Upvotes: 1

Related Questions