Skip to content

Instantly share code, notes, and snippets.

@kikito
Created November 11, 2010 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kikito/671804 to your computer and use it in GitHub Desktop.
Save kikito/671804 to your computer and use it in GitHub Desktop.
-- transforms a pretty-but-difficult string into an ugly-but-easy array for tilemaps
local 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
local function printMap(map)
local buffer = {}
for x,column in ipairs(map) 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:')
printMap(tiles)
print('tiles[5][3]:', tiles[5][3])
print('tiles(5,3):', tiles(5,3))
--[[ Output:
string:
1***2
* *
* 0 *
* *
3***4
tiles:
{
{ ' ', ' ', ' ', ' ', ' ' },
{ ' ', ' ', ' ', ' ', ' ' },
{ '1', '*', '*', '*', '3' },
{ '*', ' ', ' ', ' ', '*' },
{ '*', ' ', '0', ' ', '*' },
{ '*', ' ', ' ', ' ', '*' },
{ '2', '*', '*', '*', '4' },
{ ' ', ' ', ' ', ' ', ' ' },
{ ' ', ' ', ' ', ' ', ' ' }
}
tiles[5][3]: 0
tiles(5,3): 0
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment