Split a string using string.gmatch() in Lua

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

By adding one extra ; at the end of the string, the string now becomes "one;two;;four;", everything you want to capture can use the pattern "([^;]*);" to match: anything not ; followed by a ;(greedy).

Test:

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

Output:

1: one
2: two
3:
4: four

Leave a Comment

tech