有没有一种方式可以像Python列表对象一样分割Lua表格?

我正在构建一个库,我需要分割一个字符串,字符串如下:

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

在 Python 中,我可以将它转换成列表,然后分割列表,例如:

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

现在有了列表,我可以像这样拼接它:

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

这在 Lua 中是否可行?

点赞
用户1190388
用户1190388

注意,以下的拆分函数对于长度为两个或更多的分隔符会失败。因此,你不能将其与像 ,: 这样的分隔符一起使用。

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

你可以按以下方式使用它:

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

现在,对于 Lua 表,索引从 1 而不是 0 开始,你可以使用 table.unpack 来切割小表。所以,你将有:

a1 = {table.unpack(strlist, 1, 0)} -- 空表
a2 = {table.unpack(strlist, 1, 1)} -- 只有第一个元素包裹在一个表中
b1 = {table.unpack(strlist, 1, #list)} -- 整个表的拷贝
b2 = {table.unpack(strlist, 2, #list)} -- 除了第一个元素之外的所有内容
c = strlist[1]

(table.unpack 在 Lua 5.2 中有效,而在 Lua 5.1 中是 unpack)

对于更大的表,你可能需要编写你自己的 浅层表复制 函数。

2014-03-23 08:32:09
用户375651
用户375651

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

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
2014-03-24 04:10:36