for example if there is 5000 Steel being requested but only 1000 available, multiple deliveries will be created against the same 1000 steel, leaving many trains trying to load up for a non existent resource.
One possible solution below.
--return name of station with highest count of item or nil
function GetStationItemMax(item, min_count )
local currentStation = nil
local currentMax = min_count
for stopID, storage in pairs (global.Dispatcher.Storage) do
for k, v in pairs (storage.provided) do
if k == item and v > currentMax then
local ltStop = global.LogisticTrainStops[stopID]
if ltStop then
local outstanding = GetExistingDeliveries(ltStop.entity.backer_name, item);
if v - outstanding > currentMax and v - outstanding > 0 then
if global.log_level >= 4 then printmsg("found ".. v .." ".. k.." at "..ltStop.entity.backer_name) end
currentMax = v - outstanding
currentStation = {entity=ltStop.entity, count=v - outstanding, maxTraincars=global.Dispatcher.Storage[stopID].maxTraincars}
else
if global.log_level >= 4 then printmsg("found ".. v .." ".. k.." at "..ltStop.entity.backer_name.. " But it was already claimed") end
end
else
if global.log_level >= 1 then printmsg("Error(GetStationItemMax): "..stopID.." no such unit_number") end
end
end
end --for k, v in pairs (storage.provided) do
end
return currentStation
end
function GetExistingDeliveries(station, item)
local count = 0
for _, value in pairs(global.Dispatcher.Deliveries) do
if value.from == station and value.item == item then
count = count + value.count
end
end
return count;
end