[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: attempt to perform arithmetic on field '_income' (a table value)
- From: Choonster TheMage <choonster.2010@...>
- Date: Wed, 18 Sep 2013 23:24:47 +1000
On 18 September 2013 23:02, Jayanth Acharya <jayachar88@gmail.com> wrote:
> On Wed, Sep 18, 2013 at 6:05 PM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
>>
>> 2013/9/18 Chris Berardi <chris.berardi@pmcsystems.com>:
>> > Can someone kindly explain the reason why I see this error ?
>> > tax.init = function (pIncome, pRate)
>> > tax._income = pIncome
>> > tax._rate = pRate
>> > end
>> >
>> > tax:init(12200, 12)
>> >
>> >
>> >
>> > The way Lua handles OO, the call to tax:init(12200, 12) is syntactic
>> > sugar for
>> > tax.init(tax, 12200, 12). Therefore, tax._income is assigned tax and
>> > tax._rate
>> > is assigned what you think is pIncome and what you think is pRate is
>> > thrown
>> > away.
>> >
>> > Try changing the call to tax.init(12200, 12) or change the function
>> > definition
>> > to tax.init = function (self, pIncome, pRate).
>>
>> And change all the tax.xxx statements to self.xxx statements.
>>
> Thanks Dirk, but changing tax to self inside the functions, I get this
> error:
> attempt to index global 'self' (a nil value)
You need to add self as the first parameter to the functions or define
them with colon syntax (which gives them an implicit first parameter
self).
i.e. the tax:init method could be declared like this:
tax.init = function(self, pIncome, pRate)
-- Do stuff
end
Or like this:
function tax:init(pIncome, pRate)
-- Do stuff
end
That way, when it's called with the colon syntax like `tax:init(12200,
12)`, self is assigned to the `tax` table.
This is explained in more detail in the manual:
http://www.lua.org/manual/5.1/manual.html#2.5.8
http://www.lua.org/manual/5.2/manual.html#3.4.9