2024-12-12 08:00:06

Lua字符串到int

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

我有一个这样的字符串:

a = "10"

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


当前回答

local a = "10"
print(type(a))
local num = tonumber(a)
print(type(num))

输出

   string                                                                                                                                                                          
   number

其他回答

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这样的操作符仍然会返回一个浮点数。

我建议你去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 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
local a = "10"
print(type(a))
local num = tonumber(a)
print(type(num))

输出

   string                                                                                                                                                                          
   number