String2Tiles
Posted: Thu Nov 11, 2010 2:21 pm
Using arrays for tile-based maps is kind of a pain.
The problems I see:
... but they are a pain to use! - you can't easily do str[x][y] or similar. You have to rely on regular expressions and other nonsense.
Here's an attempt at taking the best from both worlds: string2Tiles.
This function:
And here's the output:
I hope this helps. Feel free to comment / add things.
Code: Select all
local tiles = {
{ ' ', ' ', ' ', ' ', ' ' },
{ ' ', ' ', ' ', ' ', ' ' },
{ '1', '*', '*', '*', '2' },
{ '*', ' ', ' ', ' ', '*' },
{ '*', ' ', '0', ' ', '*' },
{ '*', ' ', ' ', ' ', '*' },
{ '3', '*', '*', '*', '4' },
{ ' ', ' ', ' ', ' ', ' ' },
{ ' ', ' ', ' ', ' ', ' ' }
}
- There are way too many commas and quotes/apostrophes and {s and }s
- x and y coordinates are switched: you have to choose between doing map[y][x] instead of map[x][y], or drawing the map 'sideways'
Code: Select all
local str = [[
1***2
* *
* 0 *
* *
3***4
]]
Here's an attempt at taking the best from both worlds: string2Tiles.
Code: Select all
function string2Tiles(str)
local tiles = {}
local row_length = #(str:match("[^\n]+"))
for x = 1,row_length,1 do
tiles[x] = {}
end
local x,y = 1,1
for row in str:gmatch("[^\n]+") do
assert(#row == row_length, 'Map is not squared: length of row ' .. tostring(y) .. ' should be ' .. tostring(row_length) .. ', but it is ' .. tostring(#row))
x = 1
for tile in row:gmatch(".") do
tiles[x][y] = tile
x = x + 1
end
y=y+1
end
setmetatable(tiles, { __call = function(self, x,y) return self[x][y] end })
return tiles
end
- Accepts an easy-to-draw string
- Transforms it onto a table. The table is 'flexed', so you can index it like this: table[x][y]
- For more ease of use, it can also be indexed as a function: table(x,y)
Code: Select all
-- prints the tiles on the console
local function printTiles(tiles)
local buffer = {}
for x,column in ipairs(tiles) do
table.insert(buffer, "\n { '" .. table.concat(column, "', '") .. "' }")
end
print( '{' .. table.concat(buffer, ',\n') .. '\n}' )
end
local str = [[
1***2
* *
* 0 *
* *
3***4
]]
local tiles = string2Tiles(str)
print('string:')
print(str)
print('tiles:')
printTiles(tiles)
print('tiles[5][3]:', tiles[5][3])
print('tiles(5,3):', tiles(5,3))
Code: Select all
string:
1***2
* *
* 0 *
* *
3***4
tiles:
{
{ ' ', ' ', ' ', ' ', ' ' },
{ ' ', ' ', ' ', ' ', ' ' },
{ '1', '*', '*', '*', '3' },
{ '*', ' ', ' ', ' ', '*' },
{ '*', ' ', '0', ' ', '*' },
{ '*', ' ', ' ', ' ', '*' },
{ '2', '*', '*', '*', '4' },
{ ' ', ' ', ' ', ' ', ' ' },
{ ' ', ' ', ' ', ' ', ' ' }
}
tiles[5][3]: 0
tiles(5,3): 0
]]