Reputation: 2546
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?
Upvotes: 4
Views: 14100
Reputation: 28950
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
%-
will match a minus sign, while %-?
will match minus sign optionally, in other words, there may be a minus.
%d+
will match any string segment that consists of one or more consequent digits.
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
Upvotes: 3
Reputation: 3103
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
Upvotes: 6
Reputation: 72312
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
Upvotes: 0