BNW does this in dropItems function - when it decides to spill something after trying to figure out what to spill:
if count > 0 then
-- now we're forced to spill items
entity = entity or global.forces[player.force.name].roboport
entity.surface.spill_item_stack(entity.position, {name = name, count = count}, false, entity.force, false)
end
I have changed to this since above will crash if you run with mods that introduce items that are unknown or you hover cursor over those unknown items when they are on the ground or when you open a gui - like in Oarc, and hover them over the unknown items on the ground, OR when you drop a building on top of a rock - which is then an entity of ghost OR a tank running over a stone .
if count > 0 then
-- now we're forced to spill items
entity = entity or global.forces[player.force.name].roboport
if entity and entity.valid then
if (global.enable_oe_debug) then
log("dropItems: Spilling items for: ".. entity.name .. ", type: " .. entity.type .. ", at " .. GetGPStext(entity.position) .. ", entity force: ".. entity.force.name)
end
if (entity.name == "oarc-gui") then
game.players[player.name].print("Close your menu when stealing ore from someone ;)")
elseif (entity.surface == nil) then
game.players[player.name].print("Send this log to JustGoFly - it shows something that WOULD have crashed, and provides good info to debug what caused it")
log("dropItems: would have crashed accessing entity.surface - on entity name: " .. entity.name .. " for item: " .. name .. " count: " .. count .. " for player: " .. player.name)
else
entity.surface.spill_item_stack(entity.position, {name = name, count = count}, false, entity.force, false)
end
end
end
The check for oarc-gui should be removed in your code, but the validation of the surface being nil is very important.