luatext-parsing

How to get numbers from a string in Lua?


I have the string "0,0,0,-58.43083113,,".

How could I get all the 4 numbers as double with Lua? Thanks!

I tried it with string.match(). But it didn't work.


Solution

  • local text = "0,0,0,-58.43083113,,"
    
    local numbers = {}
    text:gsub("[^,]+", function (str) table.insert(numbers, tonumber(str)+.0) end)
    print(table.concat(numbers, ", "))
    

    or

    for str in text:gmatch("[^,]+") do
      table.insert(numbers, tonumber(str) + .0)
    end
    

    Of course this assumes that you only have number representations and commas in your string.