2

I'm building a lib and I need need to split a string, the string is like this

'PROTOCAL:ROOM:USER:MESSAGE:MESSAGE_ID:TIME_FLOAT'

In python I could just convert it into a list and then split the list, for example

string = 'PROTOCAL:ROOM:USER:MESSAGE:MESSAGE_ID:TIME_FLOAT'
string = string.split(':', 1)
strlst = list()
for stri in string: strlst.append(stri)

Now with the list I could splice it like so,

a = strlst[:0]
b = strlst[0:]
c = strlst[0]

Can this be done in Lua.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user3103366
  • 65
  • 1
  • 9
  • What would be the end results in `a`, `b` and `c`? – hjpotter92 Mar 23 '14 at 08:25
  • with the c variable I can get the first element in the list. With the b variable I can get everything but the first element and so on. – user3103366 Mar 23 '14 at 08:29
  • 2
    `split` already gives you a list. Making another list and appending all the items from one to the other is unnecessary. – user2357112 Mar 23 '14 at 08:52
  • Also, `strlst[:0]` is an empty list, and `strlst[0:]` is a copy of the whole `strlst`. You might want to review how `split` and list slicing work, because you're doing much more work than necessary. – user2357112 Mar 23 '14 at 08:54

2 Answers2

2

Note that the following split function would fail for a separator of length two or more. So, you wouldn't be able to use it with something like ,: as a separator.

function split( sInput, sSeparator )
    local tReturn = {}
    for w in sInput:gmatch( "[^"..sSeparator.."]+" ) do
        table.insert( tReturn, w )
    end
    return tReturn
end

You'll use it as follows:

str = 'PROTOCAL:ROOM:USER:MESSAGE:MESSAGE_ID:TIME_FLOAT'
strlist = split( str, ':' )

Now, for lua-tables, the indexing starts at 1 and not 0, and you can use table.unpack to slice small tables. So, you'll have:

a1 = {table.unpack(strlist, 1, 0)} -- empty table
a2 = {table.unpack(strlist, 1, 1)} -- just the first element wrapped in a table
b1 = {table.unpack(strlist, 1, #list)} -- copy of the whole table
b2 = {table.unpack(strlist, 2, #list)} -- everything except first element
c = strlist[1]

(table.unpack works in Lua 5.2, it is just unpack in Lua 5.1)

For larger tables you may need to write your own shallow table copy function.

Community
  • 1
  • 1
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
0

A version which supports separators of any length:

local function split(s, sep)
    local parts, off = {}, 1
    local first, last = string.find(s, sep, off, true)
    while first do
        table.insert(parts, string.sub(s, off, first - 1))
        off = last + 1
        first, last = string.find(s, sep, off, true)
    end
    table.insert(parts, string.sub(s, off))
    return parts
end
Winston
  • 71
  • 2