Lua Metatables Simulating OOP


local Class = {} -- objects and classes will be tables
local __meta = {__index = Class}
-- ^ if an instance doesn't have a field, try indexing the class
    -- return setmetatable({}, __meta) -- this is shorter and equivalent to:
    local new_instance = {}
    setmetatable(new_instance, __meta)
    return new_instance
function Class.print()
    print "I am an instance of 'class'"

local object =
object.print() --> will print "I am an instance of 'class'"

Instance methods can be written by passing the object as the first argument.

-- append to the above example
function Class.sayhello(self)
    print("hello, I am ", self)
object.sayhello(object) --> will print "hello, I am <table ID>"
object.sayhello() --> will print "hello, I am nil"

There is some syntactic sugar for this.

function Class:saybye(phrase)
    print("I am " .. self .. "\n" .. phrase)
object:saybye("c ya") --> will print "I am <table ID>
                      -->             c ya"

We can also add default fields to a class.

local Class = {health = 100}
local __meta = {__index = Class}

function return setmetatable({}, __meta) end
local object =
print( --> prints 100 = 50; print( --> prints 50
-- this should not be done, but it illustrates lua indexes "Class"
-- when "object" doesn't have a certain field = 200 -- This does NOT index Class
print( --> prints 200