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

Can you help with Metatables?

Asked by 10 years ago

Um, I've never really understood them, I know they can be helpful, the only thing I know is:

getmetatable()
setmetatable()

And I dont' know how they work.

1 answer

Log in to vote
3
Answered by
Andalf 100
10 years ago

A metatable is an interesting thing, it's not as easy to explain as it is to use however I'll still try.

Example

local Table = []
Table.__index = Table
Table.Age = 20
Table.Name = "Banana"

local table = []
Table.Age = 17
setmetatable(table, Table)

print(table.Name, table.Age)

Output

Banana 17

Because table has the metatable Table, it 'inherits' the properties/children of that metatable, this print will print "Banana", however name can still be overwritten as is the case with age.

Metatables allow you to do some pretty interesting stuff, including emulating your own OOP style class system.

There are also several metamethods that can be attached to functions

.__add, .__sub, .__mul, .__concat,.__lt,.__gt,.__gc I don't know all of them but they're pretty self explanatory.

In the case where you add two metatables together, the will return whatever the.__add metamethod is, .__sub for subtraction and so on.

.__gc is a special case and fires when luas garbage collector kicks in, I have no idea if this can even be used in RBXLua.

There's also .__index and .__newindex which are again special case metamethods, the former fires any time an index is changed and the latter whenever a new index is added. I'm sure there are some I've missed out however.

0
I think ._mul means multiply marioman1932 48 — 4y
Ad

Answer this question