Page 1 of 1

LuaSurface.set_tiles parameter to offset tile positions

Posted: Sat Sep 14, 2024 5:39 pm
by sparr
I have a block of tiles that I want to place copies of multiple places in the world. I'd like to initialize the definition of those tiles just once, then call set_tiles with a MapPosition that will get added to the positions of all of the tiles in my block.

Currently I am doing this which saves time creating the table but still requires me to loop through to set all the positions:

Code: Select all

local blank_tiles = {}
for count = 0, 32*32-1 do
  -- position will be updated before placement
  blank_tiles[count] = {name= "out-of-map", position= {0, 0}}
end

local function wipe_chunk(surface, pos)
  for dx = 0,31 do
    for dy = 0,31 do
      local blank_tile = blank_tiles[dy*32+dx]
      blank_tile.position.x, blank_tile.position.y = pos.x + dx, pos.y + dy
    end
  end
  local tile_correction = false -- causes problems with deep water
  surface.set_tiles(tiles, tile_correction)
  -- ...
I'd love to be able to just do this:

Code: Select all

surface.set_tiles(tiles, tile_correction, pos)

Re: LuaSurface.set_tiles parameter to offset tile positions

Posted: Sat Sep 14, 2024 7:07 pm
by curiosity
You can optimize this further by caching blank_tile.position, pos.x and pos.y reads and by having a dedicated index variable for blank tiles instead of calculating the index on the fly.

Re: LuaSurface.set_tiles parameter to offset tile positions

Posted: Sun Sep 15, 2024 12:52 pm
by sparr
Good call on caching. I need to do a pass of that across all my mods I'm updating.

I was dubious about the index variable, but I benchmarked it and it does seem about 25% faster to do index = index + 1 instead of dy*32+dx, so I guess that's something I need to do in a lot of places as well.

Thanks for the tips!