lua-users home
lua-l archive

RE: Userdata with methods *and* table access.

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


> -----Original Message-----
> From: lua-bounces@bazar2.conectiva.com.br 
> [mailto:lua-bounces@bazar2.conectiva.com.br] On Behalf Of 
> Warren Merrifield
> Sent: Wednesday, October 13, 2004 4:33 AM
> To: Lua Mailing List
> Subject: Userdata with methods *and* table access.
> 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.
 This is how I write my __index method...
 static int point2_index( lua_State* L )
 {
 const char* key = lua_tostring( L, 2 );
 if ( key[0] == 'x' && key[1] == 0 ) { // faster than strcmp()
 lua_pushnumber( L, lclass_checkobject<point2>( L, 1 )->x );
 } else if ( key[0] == 'y' && key[1] == 0 ) {
 lua_pushnumber( L, lclass_checkobject<point2>( L, 1 )->y );
 } else {
 // Index into the metatable.
 lua_getmetatable( L, 1 );
 lua_pushvalue( L, 2 );
 lua_gettable( L, -2 );
 }
 return 1;
 }
 The template function lclass_checkobject<>() just returns the point2 class
from the userdata or calls lua_error() if it's nil or not a point2 type.
The else block is the trick which solves your problem.
 I'm trying to speed up the function by the way as it's still a bit slower
than a normal table index operation. I'm considering removing type checking
in lclass_checkobject<>(), but aside from that does anyone have any other
suggestions to speed this up?
 Tom Spilman
 Co-owner | Programmer
 www.sickheadgames.com

AltStyle によって変換されたページ (->オリジナル) /