Still have questions? Join our Discord server and get real time help.
1

# Self and setmetatable how to use and whay is it?

Edited 11 days ago

Hey devs! I want to learn how to use "Self" and "setmetatable". So the robloxdev page isn't really precise, I dont really speak english im in learning. So if somebody can explain me how to use that and what is it? Thanks

local this = {}

this.func = (function()
local self = {}
setmetatable(self, this) -- What does it do?
end)()


2
incapaxx 2647
11 days ago

# Metatables

A table can be the metatable of another table. Multiple tables can have the same metatable. A table's metatable itself can have a metatable. A table can even be its own metatable.

setmetatable(x, m) allows you to set m to be x's metatable. Returns x back.

getmetatable(x) allows you to retrieve the metatable of x. Nil will be returned if x has no metatable.

Small example

lua local x = {}; --// remember how i said setmetatable returned x? you can do local x = setmetatable({}, m) to get the first table back. local m = {};

setmetatable(x, m); --// m is now the metatable of x



Metatables would contain metamethods. These can be thought of as "events for tables".

This is not strictly true. I am only using it as an abstraction to show you how it works more or less.

# Metamethods

When working with metatables you also need to understand metamethods.

Metatables would contain these metamethods. These can be thought of as "events for tables".

This is not strictly true. I am only using it as an abstraction to show you how it works more or less.

An example of a metamethod is __index. It is invoked when you index table x for a nonexistent field.

A tiny example of __index

lua local x, m = {}, {__index = {key = "value"}};

setmetatable(x, m); print(x.key); --> value

 Lua first checks if x has key. If it does, produce the value. If it does not, look for a metatable. If no metatable, produce nil. If there is a metatable that has the __index field produce the value in the __index table. If no __index field, produce nil.

__index can also be set to a function. When it is a function, produce its return.

lua local m = {__index = function(t, k) --// t is the table that m is the metatable of. k is the key that does not exist. return "Key: " .. k; end};

print(x.k); --> Key: k 

# What is self

First, remember that thing:method(x) is syntax sugar (a nicer way to write something) for thing.method(thing, x).

lua local thing = {};

function thing:method(x) print(self); end 

lua function thing.method(self, x) print(self); end

x is just some parameter; it is not needed. self is implicit parameter when you use the : notation when you define a function. It doesn't have to be called self when you explicitly pass it; it is just convention to name it self.

Let's try calling the method function.

lua thing.method(); --> nil thing:method(); --> table: 0x1a59e40