Skip to content

Instantly share code, notes, and snippets.

@morsk
Last active May 15, 2020 03:24
Show Gist options
  • Save morsk/bef1fa20946b5ecb3af070fc2d014a49 to your computer and use it in GitHub Desktop.
Save morsk/bef1fa20946b5ecb3af070fc2d014a49 to your computer and use it in GitHub Desktop.
Add Waypoints Before Stations [Factorio]
/c
--[[ a "station" is an existing station, of which you have many.
a "waypoint" is a single station to add before its stacker.
the table maps station names to the new waypoint name you're adding.
t[k] = v, where key is the station name, and v is the waypoint name. ]]
local station_waypoints = {
["[img=item/iron-ore] [U] @ [img=item/lab]"] = "[img=item/iron-ore] [W] @ [img=item/lab]",
["[img=item/copper-ore] [U] @ [img=item/lab]"] = "[img=item/copper-ore] [W] @ [img=item/lab]",
["[img=item/stone] [U] @ [img=item/lab]"] = "[img=item/stone] [W] @ [img=item/lab]",
["[img=item/coal] [U] @ [img=item/lab]"] = "[img=item/coal] [W] @ [img=item/lab]",
}
--[[ internal table to lookup waypoint names quickly ]]
local waypoints = {}
for _,v in pairs(station_waypoints) do
waypoints[v] = true
end
local n_changed = 0
local n_already_changed = 0
local trains = game.player.force.get_trains()
--[[ loop over trains, then over the "records" in a train's schedule. ]]
for i = 1,#trains do
local schedule = trains[i].schedule
if schedule then
local already_waypointed = false
local adding_waypoint = false
local n_records = #schedule.records
for j = 1,n_records do
local station = schedule.records[j].station
--[[ if any station is a waypoint, this train is already configured.
we don't try to redo a done train safely; we skip it. ]]
if waypoints[station] then
already_waypointed = true
break
end
--[[ if the station has a waypoint defined in our config table, add a new record to the
schedule for the waypoint, inserted before the current point (our loop index).
this change doesn't "commit" until assigning the train's schedule, so it's ok to do
it wrongly on a train that already has it, and check later before committing. ]]
if station_waypoints[station] then
adding_waypoint = true
local new_record = { station=station_waypoints[station] }
table.insert(schedule.records, j, new_record)
--[[ inserting a record means bumping our loop index, the total # we're looping to,
as well as the "current" station the train is using, if it's >= our index. ]]
if schedule.current >= j then
schedule.current = schedule.current + 1
end
j = j + 1
n_records = n_records + 1
end
end
--[[ commit changes, iff we should ]]
if already_waypointed then
n_already_changed = n_already_changed + 1
elseif adding_waypoint then
trains[i].schedule = schedule
n_changed = n_changed + 1
end
end
end
game.player.print("Changed "..n_changed.." trains. Skipped "..n_already_changed.." already changed.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment