Split a string by "return\\newline

Hi

I load a string via http. The string contains lines of text, and I would like to split the string where there is return
ewline.

Therefore I have found this small code in the forum


function split(str, delim)
    -- Eliminate bad cases...
    if string.find(str, delim) == nil then return { str } end

    local result,pat,lastpos = {},"(.-)" .. delim .. "()",nil
    for part, pos in string.gfind(str, pat) do table.insert(result, part); lastPos = pos; end
    table.insert(result, string.sub(str, lastPos))
    return result
end

(Sorry I don’t remember the contributer)

But how can I split by return
ewline? In php I would use chr(10).chr(13). I have tried string.char(10)…string.char(13) but that doesn’t seem to work

Is it possible? And strange that split isn’t a standard string function…

A quick search on google ‘lua split string into lines’ gives: (function ‘lines’)

--# Main
-- test split
-- credits : http://lua-users.org/wiki/SplitJoin

-- Use this function to perform your initial setup
function setup()
    str = "abc\
\\rdef"
    print(str)
    tabl = lines(str)
    for i,v in pairs(tabl) do print(v) end
end

-- This function gets called once every frame
function draw()
end

function lines(str)
  local t = {}
  local function helper(line) table.insert(t, line) return "" end
  helper((str:gsub("(.-)\\r?\
", helper)))
  return t
end

according to the author, works fine except when there is just 1 line with no return at the end…
Google is our friend. :slight_smile:

Number 1a

It is CR+LF, not LF+CR, or in numbers 13+10, not 10+13, or in escape strings "\r
". E.g.:


lines = split(httpstring, "\\r\
")

Number 1b

Be aware that strings over HTTP may simply contain LF without CR, even if it is demanded that CRLF is being sent. That’s the conservative / liberal approach.

Number 2a

There’s a typo in the function that is difficult to detect, it reads local lastpos but then uses lastPos later on. It’s not ground shaking and doesn’t break the function’s code but a typo. And it leaves a trail in the form of a global variable lastPos.

Number 2b

Let me write the function a bit shorter, it is essential now that the variable is named properly. Imagine what would happen if the typo still existed:


function split(str, delim)
    local result,pat,lastPos = {},"(.-)" .. delim .. "()",1
    for part, pos in string.gfind(str, pat) do
        table.insert(result, part); lastPos = pos
    end
    table.insert(result, string.sub(str, lastPos))
    return result
end

Thanks to you both.

I"m still new to codea, and did not think of looking other places than in the help :slight_smile:

I’ll have a look at it.
13+10, and not 10+13 doh.