2024-12-12 08:00:06

Lua字符串到int

如何在Lua中将字符串转换为整数?

我有一个这样的字符串:

a = "10"

我想把它转换成10,这个数字。


当前回答

需要注意的是,math.floor()总是向下舍入,因此对于负浮点值不会产生合理的结果。

例如,表示为整数的-10.4通常会被截断或舍入为-10。然而math.floor()的结果是不一样的:

math.floor(-10.4) => -11

对于使用类型转换的截断,以下辅助函数将工作:

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

其他回答

我建议你去Hyperpolyglot看看,它有一个很棒的对比:http://hyperpolyglot.org/

http://hyperpolyglot.org/more#str-to-num-note

ps.实际上Lua转换的是双精度数而不是整型数。

数字类型表示实数(双精度浮点数) 数字。

http://www.lua.org/pil/2.3.html

可以使用tonumber()将字符串转换为数字,可以是浮点数或int型。

例如:tonumber("11")——返回:11

Lua中的所有数字都是浮点数(编辑:Lua 5.2或以下)。如果你真的想转换为“int”(或者至少复制这个行为),你可以这样做:

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有实整数,因为math.floor()返回一个整数,而如果number是一个浮点数,那么像number // 1这样的操作符仍然会返回一个浮点数。

需要注意的是,math.floor()总是向下舍入,因此对于负浮点值不会产生合理的结果。

例如,表示为整数的-10.4通常会被截断或舍入为-10。然而math.floor()的结果是不一样的:

math.floor(-10.4) => -11

对于使用类型转换的截断,以下辅助函数将工作:

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

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