Forum

> > CS2D > Scripts > Function in table
Forums overviewCS2D overview Scripts overviewLog in to reply

English Function in table

3 replies
To the start Previous 1 Next To the start

old Function in table

The Dark Shadow
User Off Offline

Quote
I don't really understand how it works, Could anyone explain me it simplified, please?

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

Would be appreciated

old Re: Function in table

TrialAndError
User Off Offline

Quote
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

old Re: Function in table

VADemon
User Off Offline

Quote
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.
To the start Previous 1 Next To the start
Log in to reply Scripts overviewCS2D overviewForums overview