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