Posted 24 August 2013 - 02:56 AM
Hello welcome to my basic metatable tutorial I only have explain some metatable functions
but it should be enough to get you started, and I should add some more later
what are metatables?
metatables are special assignments to tables that give metamethods which run a function ( or table, but focusing on function ) when called
so we want to start off with
__call is one of the metamethods metatables use, it runs function when called
example
set our table 't' to have the metatable 'mt' with the call metamethod, now how to use
now the __newindex metamethod is another metamethod metatables use and it runs when a new index is added to the table
setup a new metatable with __newindex instead if __call
set our table 't' to have the metatable 'mt' with the call metamethod, now how to use
to avoid setting this off you can use rawset(table, key, value)
Thats it so far fr the tutorial leave constructive feedback below and there will be more coming
but it should be enough to get you started, and I should add some more later
what are metatables?
metatables are special assignments to tables that give metamethods which run a function ( or table, but focusing on function ) when called
so we want to start off with
t = {} -- our table, it contains nothing now
mt = {} -- our metatable, it contains nothing now
setmetatable(t,mt) or t = setmetatable(t, mt) -- sets a metatable
getmetatable(t) -- returns mt, t's metatable
thats basiclly what you need to set and get a metatable now lets put in some metamethods__call is one of the metamethods metatables use, it runs function when called
example
set our table 't' to have the metatable 'mt' with the call metamethod, now how to use
t() -- this calls the table, meaning __call is called and it should print 'table called'
now the __newindex metamethod is another metamethod metatables use and it runs when a new index is added to the table
setup a new metatable with __newindex instead if __call
t = {}
mt = {__newindex = function() print("New Index Called") end} -- when __newindex function activated print 'new index called'
setmetatable(t,mt) -- set the metatable
set our table 't' to have the metatable 'mt' with the call metamethod, now how to use
t.v = "test" -- set 'v' in the table 't' to "test", this will activate __newindex which will print 'new index called'
to avoid setting this off you can use rawset(table, key, value)
Thats it so far fr the tutorial leave constructive feedback below and there will be more coming