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

Can someone explain to me how metatables are suppose to work, how does this work with .__index?

Asked by 3 years ago

I am trying to learn Object Oriented Programming, but I am currently stuck on metatables and on what .__index does. The Roblox Dev Hub is a bit confusing for me to understand. Can someone please give me a simple explanation of what metatables are suppose to do?

1 answer

Log in to vote
1
Answered by 3 years ago
Edited 3 years ago

"Metatables allow tables to become more powerful than before. They are attached to data and contain values called metamethods. Metamethods are fired when a certain action is used with the datum that it is attached to."

Metatables are tables that give other tables "superpowers". Metatables tell Lua what to do during a specific situation.

What __index does?

Things start to get interesting with metatables! Let's say you wanted to create a new object.

local x = {}
function x.new()
    local self = {}
    return self --Returns table self.
end

local new = x.new()
print(new.ClassName) --Prints nil :(

ClassName does not exist. You have to specify a new property to make this work, which can be annoying. __index will save the day!

local x = {}
x.ClassName = "NewObject"
x.__index = x --Set __index metamethod to itself. Lua will be told to search here instead when it can't find anything.

function x.new()
    local self = setmetatable({}, x) --Create a new table and instantly give it superpowers.
    return self --Returns table self.
end

local new = x.new()
print(new.ClassName) --Prints "NewObject" :D

There is a situation where Lua can't find a property. You can see we tried to search ClassName, but Lua can't find anything. When we used metatables, Lua found ClassName.

__index metamethod guides Lua to the other way when that happens. When you set __index to a table, Lua will search for that table when it can't find something in the original table. When you set __index to a function, the function will fire when Lua did not found the specified index.

If you don't want __index to fire, you can use rawget, which exposes the true nature of the table.

There are more metamethods, but I don't want to go into further detail. If you have a clear understanding of metatables, you can try other metamethods such as __newindex, __tostring, __call, etc.

If you still don't understand, you can message me any time here on this website!

I recommend searching before you question since there are a lot of questions similar to yours. https://devforum.roblox.com/t/an-introduction-to-metatables/328611 https://scriptinghelpers.org/questions/75595/metatables-what-are-they-needed-for

Ad

Answer this question