开发者

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 lega开发者_JAVA技巧l 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])


"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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜