Page 2 of 2

Re: How to replace entities on tiles in a migration

Posted: Fri Jun 09, 2023 7:19 pm
by Pi-C
AlmightyCrumpet wrote: Fri Jun 09, 2023 6:51 pm YES!
Got it working!
Thank you so much!
Great that it works now -- it was just an untested idea. :-)
This is how it ended up after your last reply
Some small improvements:

Code: Select all


local function swap_entities(surface, tiles)
  -- widget is implicitly declared in the header of the for-loop, but you don't want Widgets to be global!
	--~ local position, newEntity, widget, force
	local position, newEntity, Widgets, force
	
	for t, tile in pairs(tiles) do
		position = tile.position
	  
		-- check the same x/y coordinates for the existing entity on the tile
		Widgets = surface.find_entities_filtered{name = "powered-floor-widget", position = position, radius = 1}
		-- if it is only a 'power-floor-widget' then remove it and add a 'circuit-floor-widget' in it's place

    -- Not necessary: If Widgets is empty, the for loop will do nothing!
		--~ if next(Widgets) then
			for w, widget in pairs(Widgets) do
        --Not necessary: If the table isn't empty, there is guaranteed to be a widget for each w!  
				--~ if widget then
					-- Store force and delete widget
					force = widget.force
					widget.destroy{raise_destroy = true}

					-- Add new widget
					newEntity = surface.create_entity{
						name = 'circuit-floor-widget',
						position = {position.x, position.y},
						force = force,
						raise_built = true,
					}

					IncludeControlWiresToNeighbors(newEntity, surface)
					if newEntity then
						newEntity.destructible = false
					end
				--~ end
			end
		--~ end
	end
end