[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- 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 <slonik.az@gmail.com> wrote:
> On Sun, Mar 13, 2011 at 00:15, HyperHacker <hyperhacker@gmail.com> wrote:
>> Something I stubbed my toe on the other day:
>>> obj={val=2}
>>> meta={}
>>> function meta:__mul(num) return self.val * num end
>>> setmetatable(obj, meta)
>>> =obj*4
>> 8
>>> =4*obj
>> 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
> end
>
>
> --Leo--
>
>
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.