简体   繁体   中英

Convert string to numbers in Lua

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?

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

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

You can transform the list into this code

return {231,523,402,1223,9043,-1,4}

and let Lua do the hard work:

s="231 523 402 1223 9043 -1 4"
t=loadstring("return {"..s:gsub("%s+",",").."}")()
for k,v in ipairs(t) do print(k,v) end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM