在 Lua 中,我有一个这样的字符串:231 523 402 1223 9043 -1 4
其中包含多个由空格分隔的数字。现在我想把它转换成一个整数向量,如何用一些内置函数来实现呢?
最佳答案
您可以使用 string.gsub用一个函数作为替换值。
If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order.
使用示例如下所示:
local function tovector(s)
local t = {}
s:gsub('%-?%d+', function(n) t[#t+1] = tonumber(n) end)
return t
end
使用它很简单:
local t = tovector '231 523 402 1223 9043 -1 4'
结果是一个向量(或 Lua 术语中的序列):
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
关于lua - Lua中将字符串转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37587658/