You can cause an error to occur when you try to retrieve the tile for a location in the world where a tile doesn’t exist, in the case that you are converting transform positions to correspond to the grid of your tilemap.
Also, storing tile indices to a lua object and retrieving them from there is faster than frequently calling tilemap.get_tile()
, given the tilemap doesn’t change or changes infrequently.
Using the __index
metamethod, we can construct the stored tilemap data to avoid throwing an error for trying to retrieve nonexistent tiles without needing to explicitly check whether the coordinates we are querying is within the bounds of our stored data.
local function get_tiles(url, layer)
local tiles = {}
setmetatable(tiles, {
__index = function(table,key)
return {}
end
})
local x, y, w, h = tilemap.get_bounds(url)
for m = x,w do
tiles[m] = {}
for n = y,h do
tiles[m][n] = tilemap.get_tile(url, layer, m, n)
end
end
return tiles
end
Assigning the result of this call as a value acts as 2D storage of that tilemap, represented as tables of tables. After constructing the data in this way, we can retrieve the tilesource index safely even outside the bounds of our tilemap after conversion.
-- store tilemap data
my_tiles = get_tiles('#','my_tile_layer')
-- retrieve tile
print(my_tiles[x][y]) --[[ --> the index of the tile,
or nil if out of bounds
]]