Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How could I use the metamethods of other metatables?

Asked by 8 years ago

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
}
0
You could temporarily set the metatable of tab to the one of Table and then reset it, but I feel like that is a bit too far randomsmileyface 375 — 8y

1 answer

Log in to vote
0
Answered by
XAXA 1569 Moderation Voter
8 years ago

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
Ad

Answer this question