解決attempt to index local 'self' (a number value)的錯

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)錯誤。其緣由的是ide

In general you should call member functions by :.this

In Lua, colon : represents call of a function, supplying self as a first parameter.lua

Thusspa

A:foo()

Is roughly equal tocode

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.orm

Note that if you call it from inside of the member function, self will be already available:ci

-- inside foo()-- these two are analogousself:bar()self.bar(self)

All of this information you'll find in any good Lua book/tutorial.it

相關文章
相關標籤/搜索