有没有一种方法可以在Lua中用true获得1,用false获得0?
tobool
可以将1或0转换为true或false,但是tonumber
在使用true或false时会返回nil值。
and
和or
子句。function bool_to_number(value)
return value and 1 or 0
end
bool_to_number={ [true]=1, [false]=0 }
print(bool_to_number[value])
debug.setmetatable(true, {__len = function (value) return value and 1 or 0 end})
print(#true)
print(#false)
a < b
会引发“尝试比较两个布尔值”的错误,这是语言设计上的一个缺陷。明显的解决方法(not a) and b
并不能解决将布尔值视为具有一致语法的有序集合的问题。 - Egor Skriptunoffhjpotter92的答案将任何非nil值视为true值(返回1)。而这个代码片段只将true或false作为true值。
local value = true
print(value == true and 1 or value == false and 0)
-- we add the false check because it would drop 0 in case it was nil
local value = true
local function bool_to_number(value)
return value == true and 1 or value == false and 0
end
print(bool_to_number(value))
print(value and 1 or 0)
@HellProtectionprint(value and 1 or 0)
- hjpotter92nil
视为false
,这可能不是OP想要的,如果是这种情况,lhf的解决方案更准确。 - tonypdmtr