Boolean

class Boolean extends Integer

The type of a truth value. Built-in comparisons and logical negation yield a Boolean, as does Map.Has. The true and false keywords are Boolean values too. An overloaded operator may return any value.

A Boolean behaves as the Integer 1 or 0 in every other respect.

The class is exported by the KS module:

#Import "Ks" { Boolean }

Table of Contents

Behaves as an Integer

In particular:

Testing for a Boolean

Value is Boolean is what distinguishes a truth value from an ordinary Integer.

#Import "Ks" { Boolean }

MsgBox (1 > 0) is Boolean    ; 1
MsgBox (1 > 0) is Integer    ; 1
MsgBox 1 is Boolean          ; 0
MsgBox 1 is Integer          ; 1

Json.Encode writes a Boolean as JSON true or false; see Json for how types map.

Boolean()

Converts a value to a Boolean, deciding it exactly as If would.

Value := Boolean(Expression)

Parameters

Expression

Type: Any

The value to convert.

If the value is an object with a ?() definition, the operator is called and its return value is converted by the same rules. This process repeats if another such object is returned. An object without ?() is true.

Return Value

Type: Boolean

Returns true if Expression is truthy, else false.

Error Handling

An unset expression or an unset result from ?() raises UnsetError. Any other error raised by ?() is passed on to the caller. The script must ensure that recursive truth tests terminate.

Examples

Built-in comparisons and logical negation produce Booleans.

#Import "Ks" { Boolean }

MsgBox (1 > 0) is Boolean              ; 1
MsgBox (1 = 1) is Boolean              ; 1
MsgBox (!0) is Boolean                 ; 1
MsgBox Map("a", 1).Has("a") is Boolean ; 1
MsgBox InStr("abc", "b") is Boolean    ; 0, InStr returns a position

Normalising a setting that may arrive as a number, a string or a real Boolean.

#Import "Ks" { Boolean, Json }

Config := Json.Decode(FileRead("config.json"))

; Accepts true, 1 and "yes" alike.
Enabled := Boolean(Config["enabled"])

; Writes a real JSON boolean back out, whatever the file contained.
Config["enabled"] := Enabled
FileOpen("config.json", "w").Write(Json.Encode(Config, 2))

Rejecting a setting that is not genuinely a boolean, which a plain truth test cannot do.

#Import "Ks" { Boolean, Json }

Config := Json.Decode('{"pinned": 1}')

if !(Config["pinned"] is Boolean)
    MsgBox "pinned must be true or false"   ; shown: it is the number 1

Integer, Float, Number, Type, Json, KS module