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
%- 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With