values for fibs[1] and fibs[2]. setmetatable(fibs, { __index = function(values, n) --[[__index is a function predefined by Lua, it is called if key "n" does not exist.]] values[n] = values[n - 1] + values[n - 2] -- Calculate and memoize fibs[n]. return values[n] end }) Object-oriented programming Although Lua does not have a built-in concept of classes, object-oriented programming can be emulated using functions and tables. An object is formed by putting methods and fields in a table. Inheritance (both single and multiple) can be implemented with metatables, delegating nonexistent methods and fields to a parent object. There is no such concept as "class" with these techniques; rather, prototypes are used, similar to Self or JavaScript. New objects are created either with a factory method (that constructs new objects from scratch) or by cloning an existing object. Creating a basic vector object: local Vector = {} local VectorMeta = { __index = Vector} function Vector.new(x, y, z) -- The constructor return setmetatable({x = x, y = y, z = z}, VectorMeta) end function Vector.magnitude(self) -- Another method return math.sqrt(self.x^2 + self.y^2 + self.z^2) end local vec = Vector.new(0, 1, 0) -- Create a vector print(vec.magnitude(vec)) -- Call a method (output: 1) print(vec.x) -- Access a member variable (output: 0) Here, tells Lua to look for an element in the table if it is not present in the table. , which is equivalent to , first looks in the table for the element. The table does not have a element, but its metatable delegates to the table for the element when it's not found in the table. Lua provides some syntactic sugar to facilitate object orientation. To declare member functions inside a prototype table, one can use , which is equivalent to . Calling class methods also makes use of the colon: is equivalent to . That in mind, here is a corresponding class with syntactic sugar: local Vector = {} Vector.__index = Vector function Vector:new(x, y, z) -- The constructor -- Since the function definition uses a colon, -- its first argument is "self" which refers -- to "Vector" return setmetatable({x = x, y = y, z = z}, self) end function Vector:magnitude() -- Another method -- Reference the implicit object using self return math.sqrt(self.x^2 + self.y^2 + self.z^2) end local vec = Vector:new(0, 1, 0) -- Create a vector print(vec:magnitude()) -- Call a method (output: 1) print(vec.x) -- Access