You're probably best off going with an OOP library to handle this for you. I, as usual, suggest
MiddleClass, but you could use something like Slither, SECS, or one of the many others out there.
As for metatables, I think of them like tables which specify information about how a table should operate. Think of it like a program which tells a robot how to operate. Here's the two key functions:
* setmetatable(t, mt) sets the metatable of table 't' to be the table 'mt'.
* getmetatable(t) gets the metatable of 't'.
Metatables can contain a number of different functions. The two key ones are called __index and __newindex. __index is called when you try to access something in a table that doesn't exist. For example:
Code: Select all
t = { foo = 3 }
t.foo -- exists, so we get 3
t.bar -- doesn't exist, so Lua looks for __index in the metatable, it doesn't find it in this case, so nil is returned
If we had specified __index, we could do this:
Code: Select all
t = setmetatable({ foo = 3}, { __index = function(self, key) print('The key' .. key .. 'doesn't exist!') end }) -- yes, setmetatable returns the first parameter
t.foo -- exists, so we get 3
t.bar -- Lua fins __index, and so 'The key bar doesn't exist!' is printed
The self parameter is the table which got indexed. The key parameter is the non-existent key inside the table.
__newindex is called whenever you try to set the value of something in table which doesn't already exist. For example:
Code: Select all
t = { foo = 3 }
t.foo = 4 -- all well and good
t.bar = 5 -- Lua looks for __newindex, doesn't find it, so it just sets the value in t
If we had specified __newindex, we could do this:
Code: Select all
t = setmetatable({ foo = 3}, { __newindex = function(self, key, value) print('We're not setting anything!') end })
t.foo = 4 -- all good
t.bar = 5 -- "We're not setting anything!"
Hope that helps!