Skip to content

Instantly share code, notes, and snippets.

@flbuddymooreiv
Last active June 8, 2021 21:36
Show Gist options
  • Save flbuddymooreiv/ad16e95e3efadf86083b37c5efbb76db to your computer and use it in GitHub Desktop.
Save flbuddymooreiv/ad16e95e3efadf86083b37c5efbb76db to your computer and use it in GitHub Desktop.
Modify factorio train schedule in lua script

This is a code dump of a script I wrote to change train schedules in factorio. The API states that the schedule must be deep-copied by value and then can be modified and set as one object rather than mutating the in-place runtime object/structure.

The deepcopy function from http://lua-users.org/wiki/CopyTable seems to work fine for this purpose.

/c
function deepcopy(orig, copies)
    copies = copies or {}
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        if copies[orig] then
            copy = copies[orig]
        else
            copy = {}
            copies[orig] = copy
            for orig_key, orig_value in next, orig, nil do
                copy[deepcopy(orig_key, copies)] = deepcopy(orig_value, copies)
            end
            setmetatable(copy, deepcopy(getmetatable(orig), copies))
        end
    else
        copy = orig
    end
    return copy
end

for trainind,train in pairs(game.player.force.get_trains()) do
    origsched = train.schedule
    if origsched then
        newsched = deepcopy(origsched)

        for recordkey, record in pairs(origsched.records) do
            if  record.station == '[L] [item=advanced-circuit]' and
                origsched.records[recordkey + 1].station ~= '#CLEAR' then
                table.insert(newsched.records,
                    recordkey + 1, { station = '#CLEAR' })
            end
        end
        train.schedule = newsched
    end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment