Why are messages not constants?

Why are messages like "acquire_input_focus" a string that I have to type in my program, while other things like go.EASING_INBACK a predefined constant?

If they all were constants, typos would be caught at compile time, which would be an improvement IMO.

Right now I’m defining the constants myself in a separate file, but I don’t like duplicating definitions that belong to Defold’s internals:

local M = {}

-- Built-in messages
M.EXIT                 = hash("exit")
M.REBOOT               = hash("reboot")
M.SET_UPDATE_FREQUENCY = hash("set_update_frequency")
M.START_RECORD         = hash("start_record")
M.STOP_RECORD          = hash("stop_record")
M.TOGGLE_PROFILE       = hash("toggle_profile")
...

return M
1 Like

You will not get a compile time error if you try to use go.EASING_FOOBAR since Lua isn’t a compiled language. Consequently it will not really help to move the message hashes to a separate Lua module either.

You can however use static code analysis (LuaCheck or LuaInspect for instance) or use some clever tricks to lock tables and generate a runtime error to detect the use of something like go.EASING_FOOBAR or any other table access to nil values. One example of such a technique can be seen here: https://gist.github.com/britzl/546d2a7e32a3d75bab45 and you can read more about this here http://lua-users.org/wiki/DetectingUndefinedVariables

2 Likes

Would I be breaking anything by calling superstrict.lock on all of Defold’s namespaces? e.g. sys, go, gui, etc.

1 Like

The reason it looks like this is simply that we have created Defold with limited resources, and never really had the time yet to unify and polish the APIs. We are aware of a number of inconsistencies that needs to be fixed, but there are still more pressing needs that we need to take care of first. A big thing with the new text editor in Editor2 is to automatically remove some of these problems by providing better auto-completion (to avoid typing mistakes), but it’s by no means a 100% solution. The APIs themselves need to be improved as well. During the years we have moved from msg.post calls to specific functions, e.g. particlefx.play(). The latter still posts a message under the hood, but is a much better fit for text editors and humans too. :slight_smile:

7 Likes

No, you would not break anything. It’s definitely a valid solution. Another would be to run a static code analysis from time to time (or even better automate it!).

I do run luacheck as part of my test suite, but it only catches globals not in my whitelist, not things like gui.EASING_FOO. Do you have suggestions on a static analysis setup that’d catch that kind of thing?