有没有办法像Python列表obj一样拆分Lua表

Is there a way you can split a Lua table like you can a Python list obj

我正在建立一个lib库,我需要分割一个字符串,该字符串是这样的

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

在python中,我可以将其转换为列表,然后拆分列表,例如

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

现在有了清单,我可以像这样拼接它,

1
2
3
a = strlst[:0]
b = strlst[0:]
c = strlst[0]

可以在Lua中完成。


请注意,对于长度为2或更大的分隔符,以下拆分功能将失败。 因此,您将无法将其与,:之类的分隔符一起使用。

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

您将按以下方式使用它:

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

现在,对于lua表,索引从1而不是0开始,并且您可以使用table.unpack切片小表。 因此,您将拥有:

1
2
3
4
5
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在Lua 5.2中有效,在Lua 5.1中仅为unpack)

对于较大的表,您可能需要编写自己的浅表复制功能。


支持任意长度的分隔符的版本:

1
2
3
4
5
6
7
8
9
10
11
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