Tutorial by Examples

A metatable defines a set of operations which alter the behaviour of a lua object. A metatable is just an ordinary table, which is used in a special way. local meta = { } -- create a table for use as metatable -- a metatable can change the behaviour of many things -- here we modify the 'tostrin...
Some metamethods don't have to be functions. To most important example for this is the __index metamethod. It can also be a table, which is then used as lookup. This is quite commonly used in the creation of classes in lua. Here, a table (often the metatable itself) is used to hold all the operation...
5.2 Objects in lua are garbage collected. Sometimes, you need to free some resource, want to print a message or do something else when an object is destroyed (collected). For this, you can use the __gc metamethod, which gets called with the object as argument when the object is destroyed. You could...
There are many more metamethods, some of them are arithmetic (e.g. addition, subtraction, multiplication), there are bitwise operations (and, or, xor, shift), comparison (<, >) and also basic type operations like == and # (equality and length). Lets build a class which supports many of these o...
There is a metamethod called __call, which defines the bevahiour of the object upon being used as a function, e.g. object(). This can be used to create function objects: -- create the metatable with a __call metamethod local meta = { __call = function(self) self.i = self.i + 1 e...
Perhaps the most important use of metatables is the possibility to change the indexing of tables. For this, there are two actions to consider: reading the content and writing the content of the table. Note that both actions are only triggered if the corresponding key is not present in the table. Re...
Sometimes, you don't want to trigger metamethods, but really write or read exactly the given key, without some clever functions wrapped around the access. For this, lua provides you with raw table access methods: -- first, set up a metatable that allows no read/write access local meta = { __i...
local Class = {} -- objects and classes will be tables local __meta = {__index = Class} -- ^ if an instance doesn't have a field, try indexing the class function Class.new() -- return setmetatable({}, __meta) -- this is shorter and equivalent to: local new_instance = {} setmetatabl...

Page 1 of 1