解决attempt to index local 'self' (a number value)的错

本文深入探讨了在Lua编程中使用self参数的方法,解释了如何通过self调用成员函数并解决常见错误,提供了关于self参数在成员函数内部和外部的详细说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


转载于:https://my.oschina.net/u/1053706/blog/269759

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值