1

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])

1 Answer 1

9

"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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, that is incredibly powerful, the more I use lua the more I think wow!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.