Skip to content

Instantly share code, notes, and snippets.

@ofhope
Last active May 23, 2019 06:00
Show Gist options
  • Save ofhope/1a710cfe67aa6c47e8ce3894d2f1e5ad to your computer and use it in GitHub Desktop.
Save ofhope/1a710cfe67aa6c47e8ce3894d2f1e5ad to your computer and use it in GitHub Desktop.
Example from the Lua docs on creating class like behaviour using metatables
-- Basic lua class
-- http://www.lua.org/pil/16.html
-- http://www.lua.org/pil/16.1.html
Account = { balance=0 }
function Account:new (o)
o = o or {
balance = 0
}
setmetatable(o, self)
self.__index = self
return o
end
function Account:withdraw (v)
self.balance = self.balance - v
end
function Account:deposit (v)
self.balance = self.balance + v
end
x = Account:new()
x:deposit(200.00)
x:withdraw(100.00)
y = Account:new({ balance=50.00 })
y:withdraw(20.49)
print(x.balance) -- 100.0
print(y.balance) -- 29.51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment