2024-12-12 08:00:06

Lua字符串到int

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

我有一个这样的字符串:

a = "10"

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


当前回答

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

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

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

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

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

其他回答

使用tonumber函数。如a = tonumber("10")。

您可以创建一个访问器,以保持其中的“10”为int 10。

例子:

x = tonumber("10")

如果你输出x变量,它将输出一个int 10而不是"10"

和Python进程一样

X = int("10")

谢谢。

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

输出

   string                                                                                                                                                                          
   number
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

自从lua 5.3以来,有了一个新的数学。将字符串转换为整数的Tointeger函数。只是整数,没有浮点数。

例如:

print(math.tointeger("10.1")) -- nil
print(math.tointeger("10")) -- 10

如果你想转换整数和浮点数,tonumber函数更合适。