Convert string to numbers in Lua

lua
11,692

Solution 1

You can use string.gsub with a function as the replacement value.

If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order.

An example of usage would look like this:

local function tovector(s)
    local t = {}
    s:gsub('%-?%d+', function(n) t[#t+1] = tonumber(n) end)
    return t
end

Using it is straight forward:

local t = tovector '231 523 402 1223 9043 -1 4'

The result is a vector (or sequence in Lua terminology):

for i,v in ipairs(t) do print(i,v) end
1       231
2       523
3       402
4       1223
5       9043
6       -1
7       4

Solution 2

Use tonumber to convert strings to numbers. Use string patterns to get the numbers from the string http://www.lua.org/manual/5.3/manual.html#pdf-string.gmatch

local example = "123 321 -2"
for strNumber in string.gmatch(example, "%d+") do
  tonumber(strNumber)
end

"%d+" will match any string segmet that consists of one or more consequent digits.

As this is not a free coding service I leave it to you to handle find the minus symbol :) Just read the reference. Its pretty easy.

Once you have your numbers you can insert them into a Lua table. http://www.lua.org/manual/5.3/manual.html#pdf-table.insert

Share:
11,692
C. Wang
Author by

C. Wang

Updated on June 04, 2022

Comments

  • C. Wang
    C. Wang 12 months

    In Lua, I have a string like this: 231 523 402 1223 9043 -1 4 which contains several numbers separated by space. Now I would like to convert it into a vector of int numbers, how to achieve it with some built-in functions?