lua - Lua中将字符串转换为数字

标签 lua

在 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/

相关文章:

function - 本地函数相互调用

object - 如何在lua中找出对象的所有属性?

lua - 如何动态命名lua表中的元素

android - 下载并检查未为 luac 定义的目标

nginx - 如何在 Nginx 中动态添加上游?

lua - 打印所有环境变量的列表

C++ 和 Lua 与 SQLite

c++ - 在 C 中存储对 Lua 值的引用,如何实现?

file - 用 Lua 编写多行文本文件

android - 当图像表太宽时该怎么办?