English Function in table

3 replies
Goto Page
To the start Previous 1 Next To the start
09.06.20 11:00:52 pm
Up
The Dark Shadow
User
Offline Off
I don't really understand how it works, Could anyone explain me it simplified, please?

An example:
Code:
1
2
t = { age = 42, height = 102 }
m = { __add = function (tbl, n) return t.age + n end }


Would be appreciated
09.06.20 11:16:26 pm
Up
TrialAndError
User
Offline Off
Code:
1
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
10.06.20 12:03:36 am
Up
VADemon
User
Offline Off
This is called Metatables and you can use this to control how Lua processes tables. There are many thing like + (sum) which @user TrialAndError explained, you can create your own __tostring to create a different text when someone does
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.
11.06.20 12:05:11 am
Up
The Dark Shadow
User
Offline Off
Useless post, But I just wanted to thank you as I promised. Thanks guys
To the start Previous 1 Next To the start