Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How could I use the metamethods of other metatables?

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
}

1 comment

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

1 answer

✓ Accepted answer

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

This discussion is preserved as it was. New answers, comments, and votes are closed.