Table Access metamethods

  • __index is called for the [] operator
  • __newindex is called for [] used as an assignment (a[3] = value)

The __index and __newindex metamethods are only called when the table does not have a value defined for a given index. For example, given t = { ["a"] = 123, ["b"] = 456}, if t has a metatable with the __index method defined, the __index metamethod would not be called for t["a"] but it would be called for t["foo"].

Example

mt={}
mt["__newindex"] = function(t,index,value)
    if type(index) != "number" then
        error("Can only use numbers for table keys!",0)
    end
    rawset(t,index,value) -- use rawset to ignore metamethods
end
t={["foo"]=33}
setmetatable(t,mt)

t["foo"] = 99        --> ok (t["foo"] already defined)
t["bar"] = 11        --> error
t[123] = 456         --> ok