A central repository for shared strings?

When I code in Dart or Java I tend to define a class - typically I call it Statics - where I define the various constants ; integers, strings…; that are referenced from two or more locations within the project. This makes things a lot more bug proof and handles issues arising out of typos nicely. It is not immediately clear to me how I should do this in Defold. The case in point

  • I am using multiple factories to create a subset of sprites to populate a scene
  • Once all those sprites have been generated I configure their local attributes - initiated in their init functions - by passing a sequence of messages from the factory script
  • Needless to say in the script associated with the sprite in its prototype the relevant on_message function has to trap these messages and do the necessary

Now, I don’t like having to type in the message_id string twice - once in the factory script and then again in the sprite prototype script. What would be the standard way of avoiding this?

If I understand you correctly then you would do it pretty much the same way by putting your constants into a lua module.

local M = {}
-- Constants
M.LEVEL_AMOUNT_OF_ROWS = 3 
M.LEVEL_AMOUNT_OF_COLUMNS = 5

M.WEAPON_RIFLE_DAMAGE = 10

-- Messages
M.LEVEL_ON_HIT = "on_hit"
M.LEVEL_RESTART = "restart_level"
M.LEVEL_RECIVE_DAMAGE = "take_damage"

M.MENU_SHOW = "show_menu"

-- Sounds
M.SOUND_MAIN_MENU = "track_main_jingle"

return M

You would then of course simply require that in all files that needs it (if you don’t put it in the global scope, but that tends not to be a good idea imo)

--- bullet_factory.script
local constants = require "utils.constants"

function do_damage(self)
  msg.post(self.url, constant.LEVEL_RECIVE_DAMAGE, {damage=constants.WEAPON_RIFLE_DAMAGE})
end

Personally I prefer to have all my constant in one file split up with a comment string instead of in different files, but that’s personal preferense.

3 Likes

Thanks. All constants in one file is pretty much what I do when I create a Statics class in Dart and in Java.

1 Like

A minor correction to the example as given by @Jerakin. To have access to your defined constants you must do two things

  1. The constants file should have the extension .lua. In my case this file is called statics.lua and is stored in the scripts folder one level below the project root

  2. If it is in a top level folder called, say, scripts then your require statement should read

    local CONSTS = require “scripts.statics”

If you try local CONSTS = require “utils.constants” or anything of that ilk the Defold compiler will complain that it cannot find a file called constants.lua at the location /utils

1 Like