How to refund a building
Posted: Thu May 16, 2019 8:42 am
My mod needs to prevent placing buildings with complex conditions, and I don't want to use "layer-11" collision mask. So I wrote this function to refund a building when my mod determines it was illegally placed.
Has any other mod implemented this feature so I can compare?
Does anyone see any bugs or edge cases I missed?
Has any other mod implemented this feature so I can compare?
Does anyone see any bugs or edge cases I missed?
Code: Select all
function refund_entity(entity, build_event)
if entity.prototype.items_to_place_this then
-- Find the item used to place the entity
local item_count = 0
local item_name = nil
if build_event and build_event.stack and build_event.stack.valid_for_read then
item_name = build_event.stack.name
end
for _, item in pairs(entity.prototype.items_to_place_this) do
if item_name == item.name then
item_count = item.count
break
end
end
if item_count == 0 then
local item = entity.prototype.items_to_place_this[1]
if item then
item_name = item.name
item_count = item.count
end
end
local health = entity.health / entity.prototype.max_health
-- Return item to player inventory
local player = nil
if build_event and build_event.player_index then
player = game.players[build_event.player_index]
end
if item_count > 0 and player then
local result = player.insert{name=item_name, count=item_count, health=health}
item_count = item_count - result
end
-- Return item to ground
if item_count > 0 then
entity.surface.spill_item_stack(entity.position, {name=item_name, count=item_count, health=health}, false, entity.force, false)
end
end
-- Destroy entity
entity.destroy{raise_destroy = true}
end