我正在尝试使用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
无法找出错误所在...
[^,]*,
。附注:为了宣传 https://github.com/moteus/lua-split。 - moteus