Forum

> > CS2D > Scripts > Function in table
ForenübersichtCS2D-Übersicht Scripts-ÜbersichtEinloggen, um zu antworten

Englisch Function in table

3 Antworten
Zum Anfang Vorherige 1 Nächste Zum Anfang

alt Function in table

The Dark Shadow
User Off Offline

Zitieren
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

alt Re: Function in table

TrialAndError
User Off Offline

Zitieren
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

alt Re: Function in table

VADemon
User Off Offline

Zitieren
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.
Zum Anfang Vorherige 1 Nächste Zum Anfang
Einloggen, um zu antworten Scripts-ÜbersichtCS2D-ÜbersichtForenübersicht