【发布时间】:2020-07-24 01:51:30
【问题描述】:
我正在尝试在 lua 中创建一个带有分隔符的 split() 函数,默认为空格。 默认工作正常。当我为函数指定分隔符时,问题就开始了。由于某种原因,它不会返回最后一个子字符串。 功能:
function split(str,sep)
if sep == nil then
words = {}
for word in str:gmatch("%w+") do table.insert(words, word) end
return words
end
return {str:match((str:gsub("[^"..sep.."]*"..sep, "([^"..sep.."]*)"..sep)))} -- BUG!! doesnt return last value
end
我尝试运行这个:
local str = "a,b,c,d,e,f,g"
local sep = ","
t = split(str,sep)
for i,j in ipairs(t) do
print(i,j)
end
我得到:
1 a
2 b
3 c
4 d
5 e
6 f
无法弄清楚错误在哪里......
【问题讨论】:
-
这是因为字符串末尾没有 sep。但是模式是
[^,]*,。 PS。供宣传github.com/moteus/lua-split.