Dynamic Script Reloading

From Age of Empires 4 Modding

Here's a very simple version of a custom Import function which can dynamically load scar files from your mod directory.

local absoluteDir = "C:/mymod/assets/scar/"

g_Import_UseAbsoluteDir = false

function Import(file)
    if g_Import_UseAbsoluteDir then
        local success, resultOrError = pcall(function()
            return assert(loadfile(absoluteDir..file))()
        end)
        if not success then
            fatal("Error importing file '"..file.."':\n" .. tostring(resultOrError))
        end
    else
        import(file)
    end
end
  1. Set the absoluteDir appropriately.
  2. Make sure this code executes. If you put this code in a separate file then you have to import it as you would import scripts before, using the normal import function.
  3. Replace normal import calls in your scripts that come after with Import.
  4. While you're developing your scripts, set g_Import_UseAbsoluteDir = true and rebuild your mod.

You will now be able to restart your match to completely reload your scripts from disk without the need to restart the game or build the mod's sga. Set the value g_Import_UseAbsoluteDir back to false when you're done with development and are ready for release.