Classes

  • Classes can be created using tables as described above

    • They will have name value pairs, name function pairs, and use self

An example of a class for a bank account

Account = {balance=0} function Account:new (theObject) theObject = theObject or {} setmetatable(theObject, self) self.__index = self return theObject end function Account:deposit (theDeposit) self.balance = self.balance + theDeposit end function Account:withdraw(withdrawal) if withdrawal > self.balance then error ("insufficient funds") end self.balance = self.balance - withdrawal end function Account:print() print ("Account Balance is " .. self.balance) end local newAccount = Account:new() newAccount:deposit(100.00) newAccount:print() local myAccount = {} Account:new(myAccount) myAccount:deposit(50.00) myAccount:withdraw(25.00) myAccount:print() -- using the : passes in self as a hidden parameter --myAccount.print() -- this will not work because self is not present