Split a string with string.gmatch () in Lua

There are some discussions and utility functions here for line splitting, but for a very simple task I need a one-line, one-line.

I have the following line:

local s = "one;two;;four"

And I want to break it into ";". I want, in the end, to receive { "one", "two", "", "four" }in return.

So, I tried:

local s = "one;two;;four"

local words = {}
for w in s:gmatch("([^;]*)") do table.insert(words, w) end

But the result (table words) { "one", "", "two", "", "", "four", "" }. This, of course, is not what I want.

Now, as I noticed, there are some discussions about line splitting here, but they have “long” functions in them, and I need something concise. I need this code for a program where I show the virtues of Lua, and if I add a long function to make something so trivial, it would go against me.

+4
2
local s = "one;two;;four"
local words = {}
for w in (s .. ";"):gmatch("([^;]*);") do 
    table.insert(words, w) 
end

;, "one;two;;four;", , , "([^;]*);" : ;, ; ().

:

for n, w in ipairs(words) do
    print(n .. ": " .. w)
end

:

1: one
2: two
3:
4: four
+10
function split(str,sep)
    local array = {}
    local reg = string.format("([^%s]+)",sep)
    for mem in string.gmatch(str,reg) do
        table.insert(array, mem)
    end
    return array
end
local s = "one;two;;four"
local array = split(s,";")

for n, w in ipairs(array) do
    print(n .. ": " .. w)
end

:

1:

2:

3:

-1

All Articles