What are the functions of OOP and what are they useful for? (asked many times), what could the examples be used for when neccessary rather then being used all the time?
You could use something like this:
local Module = NewModule()
print(Module.something)
But I still don’t understand. You can use functions and use _index
for a new function. (i think)
local metatable = {
__index = function (object, key)
local num = mathProblem(key)
object[key] = num
return num
end
}
I had this before and could use it but not neccassary
local a = {1, __add = function(Table,val)
return val - Table[1]
end}
setmetatable(a,a)
print(a + 4) ----->>>> 3
1 Like
Lua on __index
The use of the __index
metamethod for inheritance is so common that Lua provides a shortcut. Despite the name, the __index
metamethod does not need to be a function: It can be a table, instead. When it is a function, Lua calls it with the table and the absent key as its arguments. When it is a table, Lua redoes the access in that table. We could declare __index
simply as
Window.mt.__index = Window.prototype
OOP (Object-Oriented Programming)
Metatables and Metamethods
Here is one example on how they are useful: https://mawesome4ever.com/2019/09/13/metatables-the-tool-you-need/
Basically, rather than having to save each service into a variable you can just index it when you need them.
Alright, so there’s an insightful thread about OOP in roblox. Check it out!
But if you just want the explanation of the metamethod, here’s some information.
Simply, when you do table[index]
, it fires __index
. If you do table[index] = value
, it fires __newindex
. table1 + table2
would fire __add
, etc.