Lua中如何检查值是否为数字

我想确保玩家不能在该值中输入字母或符号,如何检查它是否仅为数字?

function seed1()
    ESX.UI.Menu.CloseAll()

    ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'amountseed1', {
        title = '商店'
    }, function(data, menu)
        local amount = tostring(data.value)
        if amount == nil then
            ...
        else
            [[我应该在这里放什么来检查它是否只包含数字?]]
        end
    end, function(data, menu)
        menu.close()
    end)
end

我可以像这样放置一些内容,但这可能不是一个好的方法:

else
    if amount > 0 and amount < 9999 then
         ...
    else
        print('无效的金额或金额超过9999')
    end
end
点赞
用户4567755
用户4567755

由于您只关心数字,所以没有必要将值转换为字符串:

local amount = tostring(data.value)
--             ^^^^^^^^ 部分无用

相反,直接使用数字:

local amount = tonumber(data.value)
if amount == nil then
    -- 不是数字
else
    -- 是数字
end

最后,请记住,tonumber 尝试将值转换为数字,并在失败的情况下返回 nil

2020-11-25 13:16:47
用户4984564
用户4984564

tostring 替换为 tonumber。如果可能,它会将字符串转换为数字,并在无法转换时返回 nil

请注意:tonumber 不仅仅可以取字符串的最大有效前缀,因此 tonumber("20 foo") 将返回 nil 而不是 20。它还支持 Lua 中编写数字字面值的所有方式,因此 tonumber("2.3e2") 将返回 230,而 tonumber("0xff") 将返回 255

2020-11-25 13:17:57