Difference Between Tables and Metatables in Lua
snippet in lua

Difference Between Tables and Metatables in Lua

user4865

t={1,2,3}  -- basetable
mt={} -- metatable
mt.__index=function(t,k)
    print("__index event from "..tostring(t).." key "..k)
    return "currently unavailable"
end
mt.__newindex=function(t,k,v)
    print("__newindex event from "..tostring(t).." key: "..k.." value: "..v)
    if type(k)=="string" then
        rawset(t,k,v:reverse())
    else
        rawset(t,k,v)
    end
end
mt.__call=function(t,...)
    print("call to table "..tostring(t).." with arguments: ".. table.concat({...},','))
    print("All elements of the table:")
    for k,v in pairs(t) do print(k,v) end
end
setmetatable(t,mt)

t[4]="foo" -- this will run the __newindex method
print(t[5]) -- this will run the __index method
t("foo","bar")
-- Multiple fall through example:
t={}
mt={}
mt2={}
setmetatable(t,mt)  -- metatable on base table
setmetatable(mt,mt2) -- second layer of metatable
mt.__index=function(t,k) print('key '..k..' not found in '..namelookup[t]) return getmetatable(t)[k] end -- tries looking nonexistant indexes up in mt.
mt2.__index=mt.__index -- function was written portably, reuse it.

t[1]='A'
mt[2]='B'
mt2[3]='C'
namelookup={[t]="t",[mt]="mt",[mt2]="mt2"}
print(t[1],t[2],t[3],t[4])