lua-users home
lua-l archive

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


trust.no.one wrote:
> I am trying to create an inheritance system.
> I think I can use __index event of metatable ,because I am new to lua
> and I don't understand how to do it.

A fairly straightforward way to do it is to define a prototype table for
each "class" that contains all common methods and data for that class.  Then
set this proto table as the __index of an instance's metatable.

Example:

-- duh... that silly account again...
local account_proto = {
    name = "an account",
}

-- define "methods"
function account_proto:deposit(amount)
    self.amount = self.amount + amount
end

function account_proto:rob()
    self.amount = 0
end

-- define metatable
local account_meta = {
    __index = account_proto,
}

-- a helper function to create an account "instance".
-- note that account_meta is reused for all instances.
function account()
    local a = {amount = 0}
    setmetatable(a, account_meta)
    return a
end

-- an example
local a = account()
print(a.name)  -- "an account"
a:deposit(100)
a:deposit(110)
print(a.amount)  -- 210
a:rob()
print(a.amount)  -- 0
a.name = "aap"
print(a.name)  -- "aap"
b = account()
print(b.name)  -- "an account"


You can define "inheritance chains" by setting another proto table on the
account_proto.

Instead of using a table for the __index field you can also use a function.
So there are many ways to build your own "class system".

Keep in mind that __index is only consulted if a field is not present in the
table itself.  The same holds for __newindex.

Bye,
Wim