我正在构建一个库,我需要分割一个字符串,字符串是这样的
'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/