lua-users home
lua-l archive

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

On Sun, Mar 13, 2011 at 00:56, Dirk Laurie <> wrote:
> On Sun, Mar 13, 2011 at 07:15:20AM +0200, HyperHacker 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]: ?
>> While this makes perfect sense, it seems like something that's likely
>> to give a hard time to newbies who don't realize why the second
>> statement fails ('self' is actually 4). I was just thinking this
>> should be noted in the manual to avoid that potential confusion.
> This particular mistake has little to do with Lua.
> I suppose that you are looking for a vector space structure, otherwise
> you would have coded the possibility of multiplying two objects.  Now
> in a vector space, you are supposed always to write scalars on one
> pre-chosen side of vectors when you multiply.  Left is usual, but right
> is equally possible and in fact preferred by some authors.  Whatever,
> you would expect one of scalar*vector and vector*scalar to be valid
> and the other invalid.
> Which is exactly what you found.
> Dirk

...OK, substitute "vector" with "anything you might use with a binary
operator with a different type of object on the other side".

Sent from my toaster.