list - 有没有一种方法可以像 Python 列表 obj 一样拆分 Lua 表

标签 list lua lua-table

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

'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 中完成吗?

最佳答案

请注意,对于长度为 2 或以上的分隔符,以下 split 函数将失败。因此,您无法将其与 ,: 等内容一起用作分隔符。

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-tables,索引从 1 开始,而不是 0,您可以使用 table.unpack 来切片小表。因此,您将拥有:

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,它只是unpack在Lua 5.1中)

对于较大的表,您可能需要编写自己的 shallow table copy功能。

关于list - 有没有一种方法可以像 Python 列表 obj 一样拆分 Lua 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22588535/

相关文章:

python - 更多 'Pythonic' alternate list shuffle 方式

python - 循环遍历包含内容和索引的列表

lua - 从 Lua 中的数组中删除多个元素

python - 无法在正确位置连接两个列表

string - Lua unicode,使用 string.sub() 和两字节字符

lua - 对 lua 的 os.clock 的精度感到困惑

audio - Lua 的快速傅立叶变换 FFT?

lua - ServiceStack Redis,如何将Lua表返回为List

c - 在 lua 和 C 之间共享数组

c# - 在没有 .ToList() 复制操作的情况下将 List<Concrete> 转换为 List<Inherited Interface>