daven11
daven11

Reputation: 3035

can I index a lua array with other than an integer

Is it legal to use a metatable (or a string) as an index to an array. The bit of code below (which doesn't do much) seems to allow it. I've searched in the manual/internet etc but can't find if this is legal syntax, or it just happens to work. If anyone could confirm this is legal I'd appreciate it.

(btw, If it is legal it gives me the ability to index arrays with metatables which gives quite a bit of power. e.g. a multivalued key metatable to index a db table and so on)

x = { val = 3 }      -- our object

mt = {
    __index = function (table, key)
        print(key)
        return table.val
    end,
    __newindex = function (t,k,v)
        print(k)
        t.val = v
      end
    }

setmetatable(x, mt)


print(x[1])
print({1,2})
x["hello"] = 4
print(x[1])

Upvotes: 1

Views: 872

Answers (1)

lhf
lhf

Reputation: 72422

"The type table implements associative arrays, that is, arrays that can be indexed not only with numbers, but with any value (except nil)." http://www.lua.org/manual/5.1/manual.html#2.2

Upvotes: 9

Related Questions