lua-users home
lua-l archive

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


On Wednesday 13 October 2004 12:32, Warren Merrifield wrote:
> I'm not sure how to go about this. I've created a userdata type based
> on the code in PiL, which has a metatable with '__gc', '__tostring',
> etc. metamethods and they all work fine. I can add  method functiosn
> to that table as well, i.e. 'move', 'setpos', etc. But I can't then
> use 'normal' table access. If I write an '__index' function which
> returns x, and y positions, etc. I can no longer use my 'move'
> methods, as my __index function catches it first.
>
> To make things clearer; I want to be able to do things like:
>
> spr = newsprite(); --> Creates new userdata
> spr:move(10, 10); --> Updates the internal x & y values.
> print(spr.x);       --> 10
> spr.y = spr.y + 10; --> the y value in the userdata is set to 20
> spr:paint();  --> Draw the sprite at its internal x,y position
>
> Could anybody show me how to do this? Or let me know it isn't possible :)

It works like this: if you set an __index or __newindex metamethod then the 
specified function will only be called if the value you're trying to 
read/write is currently nil. Otherwise it will be as if no metamethod has 
been specified.  Read the manual on metamethods for further info.

So in your case, you should first set the methods (move, setpos etc.) before 
the __index and __newindex metamethods have been installed so that the 
metamethods will be bypassed for move or setpos (where the table values will 
be the functions and not nil) but not for x, y (whose values will be nil).

Dimitris