[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Gotchas in math metamethods etc
- From: HyperHacker <hyperhacker@...>
- Date: Sun, 13 Mar 2011 18:11:18 -0600
On Sun, Mar 13, 2011 at 06:53, Leo Razoumov <email@example.com> wrote:
> On Sun, Mar 13, 2011 at 00:15, HyperHacker <firstname.lastname@example.org> wrote:
>> Something I stubbed my toe on the other day:
>>> function meta:__mul(num) return self.val * num end
>>> setmetatable(obj, meta)
>> stdin:1: attempt to index local 'self' (a number value)
>> stack traceback:
>> stdin:1: in function <stdin:1>
>> stdin:1: in main chunk
>> [C]: ?
> You expect that "__mul" is symmetric to its arguments which is not the
> case in Lua. You can achieve the desired behavior by slightly
> modifying your code.
> -- Untested:
> function meta:__mul(num)
> if type(self) == 'number' then self,num = num,self end
> return self.val * num
Right, I was just suggesting that this is an easy mistake to make and
it might help to have a note pointing this out. The behaviour is
correct, but not immediately obvious if you use this syntax.
Sent from my toaster.