-1

I have a txt file with the following text:

5;2;8;3;

I need get the numeric values, using ; as delimiter, and put them into an array. How could this be achieved?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
chele
  • 51
  • 2

1 Answers1

4

The easiest way is to just use string.gmatch to match the numbers:

local example = "5;2;8;3;"
for i in string.gmatch(example, "%d+") do
  print(i)
end

Output:

5                                                                                                                                                                   
2                                                                                                                                                                   
8                                                                                                                                                                   
3 

A "harder" way with a specific Split function:

function split(str, delimiter)
    local result = {}
    local regex = string.format("([^%s]+)%s", delimiter, delimiter)
    for entry in str:gmatch(regex) do
        table.insert(result, entry)
    end
    return result
end

local split_ex = split(example, ";")
print(unpack(split_ex))

Output:

5       2       8       3 

Have a look at a sample program here.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563