Account = { balance = 0 }
function Account:new (o) --「:」に注意
o = o or { }
setmetatable(o, self)
self.__index = self
return o
end
function Account:deposit (v)
self.balance = self.balance + v
end
a = Account:new{ balance = 0 }
a:deposit(100)
Account = { balance = 0 }
function Account:new (o)
o = o or { }
setmetatable(o, self)
self.__index = self
return o
end
function Account:deposit(v)
self.balance = self.balance + v
end
function Account:withdraw(v)
if v > self.balance then error ("んな金ねーぉ") end
self.balance = self.balance - v
end
ここで、このAccountを継承するSpecialAccountクラスを作成する
SpecialAccount = Account:new() -- この段階ではまだインスタンス
s = SpecialAccount:new{limit = 1000.00} -- new を実行した時、selfのパラメータがSpecialAccountとなり、self.__indexもSpecialAccountとなった。
function SpecialAccount:withdraw (v) --オーバライド
if v - self.blance >= self:getLimit() then
error("引き出しすぎ")
end
self.balance = self.balance - v
end
function SpecialAccount:getLimit()
return self.limit or 0
end
Account = { balance = 0 }
function Account:new (o)
o = o or { }
setmetatable(o, self)
self.__index = self
return o
end
function Account:deposit(v)
self.balance = self.balance + v
end
----
Name = {}
function Named:getname()
return self.name
end
function Named:setname(n)
self.name = n
end
---
local function search (k ,plist)
for i=1, #plist do
local v = plist[i][k]
if v then return v end
end
end
function MultiInheritance (...) -- 複数のクラスから
local c = {} -- 新しいクラス
local parents = {...}
setmetatable(c, {__index = function(t, k)
local v = search(k, parents) -- 該当プロパティを持つ親クラスを特定する
t[k] = v -- パフォーマンス改善のためコピーしておく
return v
end})
c.__index = c
-- 新しいクラスのnewコンストラクタを定義
function c:new (o)
o = o or { }
setmetatable(o, c)
return o
end
return c
end
NamedAccount = MultiInheritance(Account, Named)
account = NamedAccount:new{name="Paul"}
function newAccount ( initialBalance)
local self = {balance = initialbalance}
local deposit = function (v )
self.balance = self.balance -v
end
local getBalance = function () return self.balance end
return {
deposit = deposit
getBalance = getBalance
}
end
acc = newAccount(100)
print(acc.getBalance())
function newObject(value)
return function(action, v)
if action == "get" then return value
elseif action == "set" then value = v
else error "invalid action"
end
end
end
d = newObject(0)
print(d("get")) --> 0
d("set", 10)
print(d("get")) --> 10