zjk
zjk

Reputation: 2153

Get an array from a string of numbers separated with comma

How can I convert a string like s = "6.1101,17.592,3.3245\n" to numbers in Lua.

In python, I usually do

a = s.strip().split(',')
a = [float(i) for i in a]

What is the proper way to do this with Lua?

Upvotes: 2

Views: 2723

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473447

This is fairly trivial; just do a repeated match:

for match in s:gmatch("([%d%.%+%-]+),?") do
  output[#output + 1] = tonumber(match)
end

This of course assumes that there are no spaces in the numbers.

Upvotes: 3

Related Questions