Lua string to int
如何在Lua中将字符串转换为整数?
我有一个像这样的字符串:
1 | a ="10" |
我希望将其转换为10。
使用
您可以通过在
1 2 3 4 | local a ="10" print(type(a)) local num = tonumber(a) print(type(num)) |
输出量
1 2 | string number |
Lua中的所有数字均为浮点数(编辑:Lua 5.2或更小)。如果您确实要转换为" int"(或至少复制此行为),则可以执行以下操作:
1 2 3 | local function ToInteger(number) return math.floor(tonumber(number) or error("Could not cast '" .. tostring(number) .."' to number.'")) end |
在这种情况下,您可以将字符串(或实际上,无论它是什么)显式转换为数字,然后像Java中的(int)强制转换一样截断数字。
编辑:即使在Lua 5.3包含实整数的情况下,它仍然可以在Lua 5.3中使用,因为
说您要转换为数字的字符串在变量
1 | a=tonumber(S) |
假设有数字并且只有
但是,如果有任何不是数字的字符(浮点数除外)
它将返回nil
更清楚的选择是使用tonumber。
从5.3.2开始,此函数将自动检测(带符号)整数,浮点数(如果存在点)和十六进制(整数和浮点数,如果字符串以" 0x"或" 0X"开头)。
以下代码段较短,但不等效:
-
1a + 0 -- forces the conversion into float, due to how + works.
-
1
2a | 0 -- (| is the bitwise or) forces the conversion into integer.
-- However, unlike `math.tointeger`, it errors if it fails.
您可以使访问器将" 10"保留为int 10。
例:
1 | x = tonumber("10") |
如果打印x变量,它将输出int 10而不是" 10"
像Python过程一样
x = int(" 10")
谢谢。
我建议检查Hyperpolyglot,它有一个很棒的比较:http://hyperpolyglot.org/
http://hyperpolyglot.org/more#str-to-num-note
ps。实际上,Lua转换为双精度而不是整数。
The number type represents real (double-precision floating-point)
numbers.
http://www.lua.org/pil/2.3.html
应当注意,
例如,表示为整数的-10.4通常会被截断或舍入为-10。但是math.floor()的结果并不相同:
1 | math.floor(-10.4) => -11 |
对于使用类型转换的截断,以下辅助函数将起作用:
1 2 3 4 | function tointeger( x ) num = tonumber( x ) return num < 0 and math.ceil( num ) or math.floor( num ) end |
参考:http://lua.2524044.n2.nabble.com/5-3-Converting-a-floating-point-number-to-integer-td7664081.html
返回值
如果未提供
1 2 3 | > a = '101' > tonumber(a) 101 |
如果提供了base,它将其转换为给定的base。
1 2 3 4 5 6 7 8 9 10 11 | > a = '101' > > tonumber(a, 2) 5 > tonumber(a, 8) 65 > tonumber(a, 10) 101 > tonumber(a, 16) 257 > |
如果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | > --[[ Failed because base 2 numbers consist (0 and 1) --]] > a = '112' > tonumber(a, 2) nil > > --[[ similar to above one, this failed because --]] > --[[ base 8 consist (0 - 7) --]] > --[[ base 10 consist (0 - 9) --]] > a = 'AB' > tonumber(a, 8) nil > tonumber(a, 10) nil > tonumber(a, 16) 171 |
我回答了考虑使用Lua5.3
1 2 3 4 5 6 7 8 9 | Lua 5.3.1 Copyright (C) 1994-2015 Lua.org, PUC-Rio > math.floor("10"); 10 > tonumber("10"); 10 >"10" + 0; 10.0 >"10" | 0; 10 |
这是你应该放的东西
1 2 3 4 5 6 7 | local stringnumber ="10" local a = tonumber(stringnumber) print(a + 10) output: 20 |