Function in table
3 replies



09.06.20 11:00:52 pm
I don't really understand how it works, Could anyone explain me it simplified, please?
An example:
Would be appreciated
An example:
Code:
1
2
2
t = { age = 42, height = 102 }
m = { __add = function (tbl, n) return t.age + n end }
m = { __add = function (tbl, n) return t.age + n end }
Would be appreciated
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
t = {
age = 42,
height = 102
}
m = {
--called when we use the '+' operator on the given 'tbl'
__add = function (tbl, n)
return tbl.age + n
end
}
--Make it so the table 't' gets the metatable 'm'
setmetatable(t, m)
print(t + 3) --would be t.age + 3, so we expect 42 +3 aka 45
age = 42,
height = 102
}
m = {
--called when we use the '+' operator on the given 'tbl'
__add = function (tbl, n)
return tbl.age + n
end
}
--Make it so the table 't' gets the metatable 'm'
setmetatable(t, m)
print(t + 3) --would be t.age + 3, so we expect 42 +3 aka 45
This is called Metatables and you can use this to control how Lua processes tables. There are many thing like + (sum) which @
TrialAndError explained, you can create your own __tostring to create a different text when someone does
On the surface: it's just functions with specific names inside a table (must apply with setmetatable) that Lua calls whenever something happens to your table.

tostring(yourTable)
with your table etc.On the surface: it's just functions with specific names inside a table (must apply with setmetatable) that Lua calls whenever something happens to your table.



