Last active
May 23, 2019 06:00
-
-
Save ofhope/1a710cfe67aa6c47e8ce3894d2f1e5ad to your computer and use it in GitHub Desktop.
Example from the Lua docs on creating class like behaviour using metatables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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