How do I split string with whitespaces and numbers in it by comma?
e.g
str = "bar, bar123, bar 123, 123"
to a table containing
{"bar", "bar123", "bar 123", "123"}
How do I split string with whitespaces and numbers in it by comma?
e.g
str = "bar, bar123, bar 123, 123"
to a table containing
{"bar", "bar123", "bar 123", "123"}
 
    
    The key to simplifying pattern matching is to ensure uniformity. In this case, this is achieved by ensuring that every field has a terminating comma:
for w in (str..","):gmatch("(.-),%s*") do
   print("["..w.."]")
end
 
    
    Install the split module from luarocks, then
split = require("split").split
t = split(str, ', ')
for _, val in ipairs(t) do print(">" .. val .. "<") end
>bar<
>bar123<
>bar 123<
>123<
 
    
    You can use this function.
function string:split(_sep)
    local sep, fields = _sep or ":", {}
    local pattern = string.format("([^%s]+)", sep)
    self:gsub(pattern, function(c) fields[#fields+1] = c end)
    return fields
end
This will return a table which is split by '_sep'.
 
    
    In case someone else is directed here by google looking for a working answer with basic lua:
str_tbl = {}
for value in string.gmatch(str, '([^, *]+)') do
  str_tbl[#str_tbl+1] = value 
end