在 Lua 中,可以通过使用 tonumber
函数把字符串转换为数字,也可以通过使用 tonumber
函数把数字转换为字符串。如果转换失败,则返回 nil
。因此,可以采用如下方式检查 Lua 中的值是否为空:
local a = "123"
local b = 456
local c = "789.0"
local empty_value = nil
if (type(a) == "string" and tonumber(a) == nil) or (type(b) == "number" and tonumber(b) == nil) or (type(c) == "string" and tonumber(c) == empty_value) then
-- 空值
else
-- 非空值
end
在上述代码中,empty_value
变量用于存储 tonumber
函数返回的 nil
值,这样可以方便地检查一个值是否为空。如果一个值是数字,但是 tonumber
函数返回 nil
,则说明这个值是空值。如果一个值是字符串,但是 tonumber
函数返回 nil
,则说明这个值不是数字,也不是空值。如果一个值是数字,但是 tonumber
函数返回数字,则说明这个值不是空值。
领取专属 10元无门槛券
手把手带您无忧上云