Lua - Implement a class

By xngo on February 22, 2019

There are multiple ways to implement a class in lua. Here is an example.

--[[
Description 
  * 1 of many ways to write object oriented code with Lua.
 
Reference:
  * http://www.lua.org/pil/16.1.html
 
]]--
 
 
Account = {     -- Class declaration.
  id      = 0,  -- Variables.
  balance = 0 
}
-- IMPORTANT:
-- new() method is needed so that you can
--  create multiple independent object of 
--  this class. It acts as a constructor.
--  Ref: http://www.lua.org/pil/16.1.html
function Account:new(o)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
 
  self.id = math.random(1000)         -- Initialize variables.
  return o
end
 
-- Functions implementations
function Account:deposit(value)
  self.balance = self.balance + value
  self:print_balance()                -- Call method within class.
end
 
function Account:withdraw(value)
  self.balance = self.balance - value
  self:print_balance()
end
 
function Account:print_balance()
  print("\tBalance = " .. self.balance)
end
 
 
-- Usage
 
-- 1 Account object.
local my_account = Account:new(nil)  -- Instantiate an Account object.
print("Account " .. my_account.id)-- Call a variable of an object.
my_account:deposit(55)            -- Call a method of an object.
my_account:deposit(5)             -- Call a method of an object.
 
print()
 
-- Another Account object.
local your_account = Account:new(nil)  -- Instantiate an Account object.
print("Account " .. your_account.id)-- Call a variable of an object.
your_account:withdraw(55)           -- Call a function of an object.
your_account:withdraw(5)            -- Call a function of an object.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.