lua-users home
lua-l archive

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


Hum...

So instead of feeding all my strings to gperf, I would insert them all in a Lua table as keys to integer values. In the metamethods, I just index that table with the key which already has its hash value computed (i.e. the hash will not be re-evaluated) and get back the unique integer I can use in a switch for example.

This is precisely what I suggested to Chris Gagnon, but done in the C side. How on Earth I didn't think of it?

Thanks!


Mark Hamburg wrote:
Your __index and __newindex functions can also store string to integer maps as upvalues and do the following:

    lua_pushvalue( L, 2 );    /* The key */
    lua_gettable( L, lua_upvalueindex( kKeyTableIndex ) );
    int keyIndex = lua_tointeger( L, -1 );

You could also use the environment index for the functions to do this.

Note that you don't want to have 0 be a valid result index (offset everything by 1 if need be) since undefined keys will come back as 1.

The actual lookup will probably be about as fast as your hash table so the overhead is in the other API calls.

You could become more clever for __index by having the translation table itself have an __index method that returns the key for any undefined items and you could then avoid the need to copy the key and instead could just translate it in place.

Mark