**under construction**
This is targeted towards someone new to Lua (like me) with more experience in a language like Java (like me). I didn’t find a guide like this in my inter-web searching, so I hope it helps. I realize I’m using terms loosely and ignoring technicalities, but whatever dude.
Here is a basic example of how to OO…Lala (yes, I know, I’m amazingly creative):
This is all based on, and derived from this, but I ran mine.
main.lua
require 'account'
require 'specialaccount'
--instantiation example
Bank = {}
Bank.account1 = Account:new()
Bank.account2 = Account:new()
Bank.account1:deposit(1000)
Bank.account1:withdraw(500)
print(Bank.account1.balance)
Bank.account2:withdraw(1000)
print(Bank.account2.balance)
--inheritance example
Bank.account4 = SpecialAccount:new{limit=1000.00}
Bank.account4:withdraw(1000)
print(Bank.account4.balance)
The main file creates a table called Bank, instantiates a couple objects of type Account, plays with those objects before instantiating a SpecialAccount which inherits from Account.
account.lua
Account = {balance = 0}
function Account:new (\_p)
\_p = \_p or {}
setmetatable(\_p, self)
self.\_\_index = self
return \_p
end
function Account:deposit (value)
self.balance = self.balance + value
end
function Account:withdraw (value)
if value \> self.balance then
print("insufficient funds")
else
self.balance = self.balance - value
end
end
The Account is a basic example of a good way to make a Class. It’s new function (which is like a constructor) is the hardest part to understand, but you could cut and paste it. Basically, an Account is a table with one value, balance, and 3 methods, new, deposit & withdraw.
specialaccount.lua
require 'account'
SpecialAccount = Account:new()
function SpecialAccount:withdraw (value)
if value - self.balance \> self:getLimit() then
print("insufficient funds")
else
self.balance = self.balance - value
end
end
function SpecialAccount:getLimit ()
return self.limit or 0
end
This shows how you can override inherited methods and setup new ones.
FYI, I’m writing programs with Corona to help my autistic son and other’s like him. If you’re interested in collaborating, hit me up.
[import]uid: 28775 topic_id: 10766 reply_id: 310766[/import]