简体   繁体   English

在Lua中将字符串转换为数字

[英]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. 在Lua中,我有一个像这样的字符串: 231 523 402 1223 9043 -1 4它包含几个用空格分隔的数字。 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. 您可以将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. 如果repl是一个函数,则每次匹配时都会调用此函数,所有捕获的子字符串均按顺序作为参数传递。

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): 结果是一个向量(或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

Use tonumber to convert strings to numbers. 使用tonumber将字符串转换为数字。 Use string patterns to get the numbers from the string http://www.lua.org/manual/5.3/manual.html#pdf-string.gmatch 使用字符串模式从字符串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. "%d+"将匹配由一个或多个后续数字组成的任何字符串段。

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. 拥有号码后,您可以将其插入Lua表中。 http://www.lua.org/manual/5.3/manual.html#pdf-table.insert 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: 让Lua努力工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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