Search code examples
stringsplitlualua-patterns

Splitting string into 2 dimensional table in Lua


Let's say I have this string:

map_data = "     *-*  ;    /|x|\ ;   *-*-*-*;  /|x|x|x|;-*-*-*-*-*;  \|x|x|x|;   *-*-*-*;    \|x|/ ;     *-*  ;"

I would like to split the string into an ordered table at the semicolons. Once I have done that I would like to take each element of the table and split each character into an ordered table (nested within the first table). The idea is to create a 2 dimensional table for an ascii map.

I have tried this (but it's not working and I also suspect there is an easier way):

map_data = "     *-*  ;    /|x|\ ;   *-*-*-*;  /|x|x|x|;-*-*-*-*-*;  \|x|x|x|;   *-*-*-*;    \|x|/ ;     *-*  ;"

map = {}

p = 1
pp = 1
for i in string.gmatch(map_data, "(.*);") do
    map[p] = {}
    for ii in string.gmatch(i, ".") do
        map[p][pp] = ii
        pp = pp + 1
    end
    p = p + 1
end

Solution

  • It's been years since I've touched Lua but assuming you fix the escape character issue can't you then just do something along the lines of...

    map = {{}} -- map initially contains one empty line 
    for i = 1, #map_data do
        local c = map_data:sub(i,i)
        if c == ';' then
            map[#map+1] = {} -- add another line to the end of map
        else
            map[#map][ #map[#map] + 1] = c -- add c to last line in map
        end
    end