lua-users home
lua-l archive

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


On 25/06/2011 22:37, Wesley Smith wrote:
const char* lua_tohstring( lua_State *L, int index, unsigned int *hash );

When writing bindings I usually get the key string in __index/__newindex
metamethods and compute some hash with them which then I use in a switch. It
would be nice if I could save the time spent in computing this hash since
Lua already has one.


How could you use the hash in a switch statement if the hash result
isn't a compile-time calculation?
wes



I'd generate the hashes with a command-line tool ( lua_pushstring(...); lua_tohstring(...); ) and put them into the source code, just like I do now.

static int index( lua_State* L )
{
    unsigned int hash;
    const char* key = lua_tohstring( L, 1, &hash );

    if ( key == NULL )
    {
        return luaL_error( L, "key is not a string" );
    }

    switch ( hash )
    {
    case 0x12345678: /* pre-computed hash */
        ....
    case 0x87654321: /* pre-computed hash */
        ...
    }

    return luaL_error( L, "invalid key: %s", key );
}