Let's say I have table which, when parsed into a String, will return the name property of the table.
local Table_mt = { __index = Table, __tostring = function(tab) return tab.name end }
How could I make another table (with a separate metatable) use the __tostring() metamethod of this metatable, and add a touch of it's own? For example, it would return what Table's tostring method plus a number
local otherTable_mt= { __index = otherTable, __tostring = function(tab) return MYSTERY..tab.number; --MYSTERY is the call on the __tostring() of Table_mt end }
Just index and call the __tostring
function of Table_mt
as usual. Metatables act like any other table.
local tab = {name = "hello!"} local Table_mt = { __index = Table, __tostring = function(tab) return tab.name end } local otherTable_mt = { __index = otherTable, __tostring = function(tab) return Table_mt.__tostring(tab)..69 -- appends 69 to the string end } setmetatable(tab, otherTable_mt) print(tab)
prints:
hello!69