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"insufficient funds" end
self.balance = self.balance - v
end
SpecialAccount = Account:new()
SpecialAccount.deposit(8)
运行后出现出现错误,报attempt to index local 'self' (a number value)错误。其原因的是
In general you should call member functions by :
.
In Lua, colon :
represents call of a function, supplying self
as a first parameter.
Thus
A:foo()
Is roughly equal to
A.foo(A)
If you don't specify A as in A.foo()
, the body of the function will try to reference self
parameter, which hasn't been filled neither explicitly nor implicitly.
Note that if you call it from inside of the member function, self
will be already available:
-- inside foo()-- these two are analogousself:bar()self.bar(self)
All of this information you'll find in any good Lua book/tutorial.