Can / should hashes ever be used as table keys?

Hi folks!

I’m finding myself a bit confused about whether hashes as table keys are ever a good idea. Based on this thread I thought the answer was no, because they don’t work properly in Release builds. But I noticed in the API reference for collectionfactory.create the example code uses hashes as keys for setting properties, in the function’s returned table, and to look up a specific enemy ID.

Did I misunderstand the linked thread, and hashes are fine to use as keys? Or is that something only Defold’s own APIs can do?

Thanks!

Using hashes as table keys is totally fine. It’s often very useful. Just keep in mind two things:

  1. You can’t convert hashes back into strings in release builds (or at least, that won’t give you anything useful).
  2. You can’t use hash keys in a ‘message’ table you send with msg.post().

Using full URLs on the other hand, while technically possible, doesn’t work for most cases.

Ah, okay. I definitely interpreted the rules as being much stricter than that! So just don’t try to get the string value back out or serialize them and be happy? :slight_smile:

Yep! It’s possible that there’s another little caveat or two that I’m missing, but I haven’t run into any problems myself!

Great. Thanks for clearing things up for me!

1 Like

This is incorrect. Hashes are foundational in Defold and they are used throughout the engine. I recommend embracing them and using them where you can and where it makes sense.

What doesn’t work in a release build is to convert a hash back to the original unhashed value when printing a hash value or using the tostring() function

A good example of using hashes as keys is to quickly look up data associated with game object IDs for instance. Or quickly looking up data you want to associate with message IDs.

4 Likes

Oh, I probably worded my original question a bit vaguely. Sorry! I was only (apparently incorrectly) avoiding using hashes as table keys. I’ve definitely been using hashes elsewhere! Trying to use Defold without them would be interesting :sweat_smile: