lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Version 2.01 of the multiple-inheritance class library for Lua has been released.

As the previous version, it offers a class framework along the lines of C++, including multiple stateful base classes (not just interfaces) plus shared (C++ virtual) derivation.

This version supports named classes and using the dot notation for scoping, and is backwards compatible with the previous 1.03 version which only supported unnamed classes and square-bracket scoping.

Example of the new style with global named classes and dot scoping:

require 'classlib'

class.Account()   -- declares global var 'Account', see doc.
function Account:__init(initial)
    self.balance = initial or 0
end
function Account:deposit(amount)
    self.balance = self.balance + amount
end
function Account:withdraw(amount)
    self.balance = self.balance - amount
end
function Account:balance()
    return self.balance
end

class.NamedAccount(shared(Account))    -- shared base
function NamedAccount:__init(name, initial)
    self.Account:__init(initial)
    self.name = name or 'anonymous'
end

class.LimitedAccount(shared(Account))  -- shared base
function LimitedAccount:__init(limit, initial)
    self.Account:__init(initial)
    self.limit = limit or 0
end
function LimitedAccount:withdraw(amount)
    if amount > self:balance() then
       error 'Limit exceeded'
    else
       self.Account:withdraw(amount)
    end
end

class.NamedLimitedAccount(NamedAccount, LimitedAccount)
function NamedLimitedAccount:__init(name, limit, initial)
    self.Account:__init(initial)
    self.NamedAccount:__init(name)
    self.LimitedAccount:__init(limit)
end
-- widthdraw() disambiguated to the limit-checking version
function NamedLimitedAccount:withdraw(amount)
    return self.LimitedAccount:withdraw(amount)
end

myNLAccount = NamedLimitedAccount('John', 0.00, 10.00)
myNLAccount:deposit(2.00)
print('balance now', myNLAccount:balance())   --> 12.00
myNLAccount:withdraw(1.00)
print('balance now', myNLAccount:balance())   --> 11.00
myNLAccount:withdraw(15.00)                   --> limit exceeded

For full documentation and source please look at the wiki:

http://lua-users.org/wiki/MultipleInheritanceClasses

or at LuaForge:

http://luaforge.net/projects/luamiclasses/

Any comments or bug reports will be appreciated, thanks.

Hugo Etchegoyen