lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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.