Split string on Delimiter (LUA)

Basic function to split a string on a delimiter in LUA. Syntax is like PHP's explode - delimiter then string

Returns a table of the identified substrings

One known limitation is that it won't include an empty key where two delimiters occur in sequence - e.g. 'foo,,bar' - will return a table with two entries instead of 3. But I didn't need that behaviour when I wrote it, so didn't spend any extra time on it

Similar To

  • PHP explode()
  • Python split()
  • Javascript split()

Details

Snippet

function strSplit(delim,str)
    local t = {}

    for substr in string.gmatch(str, "[^".. delim.. "]*") do
        if substr ~= nil and string.len(substr) > 0 then
            table.insert(t,substr)
        end
    end

    return t
end

Usage Example

local s = "foo?bar??sed"
local t = strSplit("?",s)
print(t[1])
print(t[2])
print(t[3])

Video