Big List of Defold Pro Tips!

Dynamically loading and running Lua script with Defold.

Thanks to @sicher

References (1) (2)

If for some reason (such as NPC dialog and movement scripting - which I’ll talk about in another post) you need to load scripts dynamically (as in you don’t know what names they are beforehand, are loading their names from another arbitrary data file) then there are some special considerations requires due of the way Defold bundles files.

First put the lua scripts you want to be able to run into a special folder such as “main/extra_scripts”. Next open your game.project file in a text editor and add custom_resources with the path to your scripts. custom_resources can be a path to a folder or a single file, and you can have multiple paths separated by commas.

NOTE! It’s important to not have the leading slash on this one when you are selecting folders and not single files. At least for me on Windows if I have a leading slash Defold gives an access denied error.

script = (“/path/to/script.lua”)
local code = sys.load_resource(script)
local f = assert(loadstring(code))

See reference (2) for more info.

5 Likes