Include empty matches when using string.gmatch to split a string in lua 5.1

462 Views Asked by At

I have a comma seperated input string that needs to support empty entries. So a string like a,b,c,,d should result in a table with 5 entries, where the 4'th is an empty value.

A simplified example

str="a,b,c,,d"
count=0

for v in string.gmatch(str, '([^,]*)') do
    count = count + 1
end

print(count)

This code outputs

9

in Lua 5.1, although there are only 5 entries.

I can change the * in the regex to + - then it reports the 4 entries a,b,c,d but not the empty one. It seems that this behaviour has been fixed in Lua 5.2, because the code above works fine in lua 5.2, but I'm forced to find a solution for lua 5.1

My current implementation

function getValues(inputString)
  local result = {}

  for v in string.gmatch(inputString, '([^,]*)') do
    table.insert(result, v)
  end

  return result
end

Any suggestions about how to fix?

2

There are 2 best solutions below

1
Wiktor Stribiżew On BEST ANSWER

You may append a comma to the text and grab all values using a ([^,]*), pattern:

function getValues(inputString)
  local result = {}

  for v in string.gmatch(inputString..",", '([^,]*),') do
    table.insert(result, v)
  end

  return result
end

The output:

a
b
c

d
2
DarkWiiPlayer On
local str="a,b,c,,d"
local count=1
for value in string.gmatch(str, ',') do
    count = count + 1
end
print(count)

And if you want to get the values, you could do something like


local function values(str, previous)
    previous = previous or 1
    if previous <= #str then
        local comma = str:find(",", previous) or #str+1
        return str:sub(previous, comma-1), values(str, comma+1)
    end
end