【问题标题】:Is there a way you can split a Lua table like you can a Python list obj有没有办法像 Python 列表 obj 一样拆分 Lua 表
【发布时间】:2014-04-30 13:52:16
【问题描述】:

我在建一个lib,需要拆分一个字符串,字符串是这样的

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

【问题讨论】:

  • abc 的最终结果是什么?
  • 使用 c 变量我可以获得列表中的第一个元素。使用 b 变量,我可以获得除第一个元素以外的所有内容等等。
  • split 已经为您提供了一份清单。制作另一个列表并将所有项目从一个附加到另一个是不必要的。
  • 另外,strlst[:0] 是一个空列表,strlst[0:] 是整个 strlst 的副本。您可能想查看split 和列表切片的工作方式,因为您所做的工作比必要的要多。

标签: list lua lua-table


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-17
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      • 2020-11-12
      相关资源
      最近更新 更多