如何检查输入是否为数字

如何检查输入是否为数字?我的理论是这样的:

local isNumber = tonumber(arg[1])

if isNumber then
print"这是一个数字"
else
print"这不是一个数字"
end

那么,你觉得呢?

点赞
用户2858170
用户2858170

arg[1] 如果 tonumber(arg[1]) 不返回 nil 则表示一个数字。所以,这也适用于字符串 "1"

如果您想确保它是数字值,请检查 type(arg[1]) == "number"

https://www.lua.org/manual/5.4/manual.html#pdf-tonumber

https://www.lua.org/manual/5.4/manual.html#pdf-type

2021-04-30 10:05:04
用户11740758
用户11740758

如果你想知道一个数字是整数还是浮点数,可以使用 math.type()

> type(math.pi) -- 普通
number
> math.type(math.pi) -- 扩展
float
> math.type(math.maxinteger) -- 永远不会只输出 "number"
integer
-- 若要使用 pcall() 和 assert() 进行检查,请执行以下操作
> do
>> local rc,res=pcall(assert,math.type(math.pi)=='float')
>> if rc and res then
>> return math.deg(math.pi),rc,res
>> else
>> error('尝试其他方法')
>> end
>> end
180.0   true    true

上述最后一个 do ... end 块显示了 Lua 中类似于其他编程语言中已知的 "Try/Catch" 异常处理的等效代码。

2021-04-30 10:51:43
用户15803159
用户15803159
局部变量 isNumber 等于 arg[1]
如果 isNumber 的类型不是 "number",则将其转换为数字类型:tonumber(isNumber)
2021-04-30 17:44:10