lua-users home
lua-l archive

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


On 26/06/2011 3.46, Andre Leiradella wrote:
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 );
}




Mmmmh, maybe mine it's weird thinking, but...:
since the hash algorithm is a Lua internal, and so unspecified, its calculations could depend on the specific platforms Lua is compiled on (if it relies on some standard C platform-dependent feature).

So if you embed in Lua source (which is cross-platform) an hash pre-computed on a platform and run the code on a different platform you could get a broken program!

More weirdness, I don't know if could be sane, but the hashing could even depend on the specific run on a specific machine. I don't know Lua internals very much, but the hashing algo could also take some address into account, so the hashes could change according to the current memory layout of the machine you the interpreter.

If my ramblings are completely wrong, someone please correct me!

-- Lorenzo