Is calling hash() every time inefficient?

I am learning how to pass messages upon input triggers and in the on_input() function I am instructed to use the hash function to hash the action_id i am targeting:

if action_id == hash(“actionName”)

then do stuff…
I am wondering if the hash function actually hashes the string in place or performs a table lookup
If it is the former, then because the string is static I could just define the hashes as local constants and the hash function will only be called once.
If it is the later then is the hash table lookup performed using binary search or something?

Just trying to make my game as efficient as possible. :man_shrugging:

You can pre-hash to save some performance.

local hashes = {}
hashes.ACTION_NAME = hash(“ACTION_NAME”)


if action_id == hashes.ACTION_NAME

A typical thing to do in a big project is to put your hashes into a single Lua module.

4 Likes

I created for myself auto hash object:
instead of hash(“string”) I’m using hashed.string

local _hashed = {}
hashed = {};
local mt = {
	__index  = function(t, k)
		if _hashed[k] == nil then
			_hashed[k] = hash(k)
		end 
		return _hashed[k]
	end
}
setmetatable(hashed, mt)
2 Likes

I did the same thing.

local _M = {}

setmetatable(_M, {
	__index = function(t, key)
		local h = hash(key)
		rawset(t, key, h)
		return h
	end
})

return _M
1 Like

That’s a nice solution, but wouldn’t it break code completion?

What does it means? Not fully understand you
Yes, I have the global variable on the full project “hashed”, if you about this

Well, if you have something like this:

-- hashes.lua
local M = {}

M.TOUCH = hash("touch")

return M

-- foobar.script
local hashes = require "hashes"

function on_input(self, action_id, action)
    if action_id == hashes.     <--- WHEN I PRESS '.' I'D GET CODE COMPLETION 

With you’re solution there’s no way to get code completion for the hashes since they’re not declared in the hashes.lua module right?

1 Like

Oh, now I am understand
Sure this method without code completion (but I am using sublime, its help with it in some way)

PS. There is a way to show code completion window (hot-key) not only after press ‘.’ ?

1 Like

I think it’s ctrl+space right?

1 Like

Oh. I check this on windows, it’s work
On my mac I have change language binding on ctrl+space, so it’s not working (it’s really painfull :wink: )
Sorry for offtop

2 Likes