Tilemap.get_bounds seems to be returning too high values for x and y (SOLVED)

This may or may not be by design and/or luas’ fault due to 1-indexing, but I keep finding myself doing this:

local x,y,w,h = tilemap.get_bounds("#tilemap") x = x-1 y = y-1

In order to get proper bounds values

Yes, it is by design. (If you use ipairs() to iterate 1-indexed arrays usually becomes transparent.)

I’m trying to get round this same problem but can’t work out the syntax for iterating through a tilemap using ipairs().

Please can anyone enlighten me?

I believe the files in the zip have a working example.

You can’t use ipairs() to iterate a tilemap. The get_bounds() function will return the bounds as a starting x,y pair and a width and height. This implies iteration using a numeric for loop:

local x, y, w, h = tilemap.get_bounds("#mytilemap")
for xi = x, x + w - 1 do
	for yi = y, y + h - 1 do
		local tile = tilemap.get_tile("#mytilemap", "mylayer", xi, yi)
	end
end

Thanks @britzl - that’s basically what I’m doing. It works perfectly well but throws up a bunch of errors reading:

ERROR:GAMESYS: Could not get the tile since the supplied tile was out of range.

It seems that accessing a layer that doesn’t cover the whole tilemap will go out of range once you go past the outermost tile on that layer - even if it’s short of the width or height of the tilemap as a whole.

Hmm, I see. I’m not able to do any experiments with this currently, but I’d try to do a protected call to get_tile to catch the error:

local x, y, w, h = tilemap.get_bounds("#mytilemap")
for xi = x,x+w do
	for yi = y,y+h do
		local ok, tile = pcall(tilemap.get_tile, "#mytilemap", "mylayer", xi, yi))
		if ok then
			-- do stuff with tile
		end
	end
end

No dice, I’m afraid :disappointed:

Doing a protected call on tilemap_get.tile also generates the same error.

It’s not a huge issue right now as the code still works but it would be nice to get it fixed at some point.

This was my mistake in the end - was going 1 over the bounds of the tilemap.

Excellent. I’m happy to hear that you found the cause of the problem!