Meta tables

How do you make an object with something resembling methods in Lua?

Lua has a very minimal mechanism which involves taking a Table and associating it with what is called a metatable. The same technique can used with User data type.

This metatable has special keys like __index which can be used to define a table of functions with with the Colon Operator syntax can be used like methods. This code sample provides an example of this:

local MT = {} MT.__index = {} MT.__index.oneMethod = function(T) return "OneMethod on "..T.name; end MT.__index.anotherMethod = function(T) return "AnotherMethod on "..T.name; end function main(Data) local O = {} O.name = "Fred" setmetatable(O, MT) O:anotherMethod() O:oneMethod() end

The best way to see it in action is in the Developing in the Translator :

 

Related pages