Referencing values

Hi,

Will it make a difference if you use a variable instead of string for the receiver of msg.post()?

Example:

local hashes = require("lib.hashes")

--THIS
msg.post("/asteroid#asteroid_factory_script", hashes.MESSAGE_FACTORY_CREATE_ASTEROID)

-- OR THIS
msg.post(hashes.ASTEROID_FACTORY_SCRIPT, hashes.MESSAGE_FACTORY_CREATE_ASTEROID)

Hashes.lua:

local M = {}

M.ASTEROID_FACTORY_SCRIPT = "/asteroid#asteroid_factory_script"

end

The advantage I see is that you can use a linter (1) or a nil guard (2) to detect if you have a typo when writing hashes.ASTEROID_FACTORY_SCRIPT. You could also get code completion for this in an external editor.

1 = yes, we will integrate one in the Defold editor but for now you’ll have to use an external tool like LuaCheck
2 = You could add a metafunction to the hashes table that would throw an error if you try to access a nil value:

local M = {}

M.ASTEROID_FACTORY_SCRIPT = "/asteroid#asteroid_factory_script"

return setmetatable(M, {
   __index = function(t,k)
       if not t[k] then error(("There is no key %s"):format(k)) end
      return t[k]
   end
})

If I know that the value will definitely be there and is set already, is the metatable necessary and is it best to use a reference value for the receiver or rather a string value for the receiver?

The metatable is for the situation where you somewhere in your code write:

msg.post(hashes.ASTEROID_FACTORY_SCIPT, hashes.MESSAGE_FACTORY_CREATE_ASTEROID)

You’d catch this at runtime when you try to read a value that doesn’t exist. It would of course be preferable to catch this compile time using a Linter.