Skip to content

Conditionals

have_coins = false
if have_coins
print "Got coins"
else
print "No coins"

A short syntax for single statements can also be used:

have_coins = false
if have_coins then print "Got coins" else print "No coins"

Because if statements can be used as expressions, this can also be written as:

have_coins = false
print if have_coins then "Got coins" else "No coins"

Conditionals can also be used in return statements and assignments:

is_tall = (name) ->
if name == "Rob"
true
else
false
message = if is_tall "Rob"
"I am very tall"
else
"I am not so tall"
print message -- prints: I am very tall

The opposite of if is unless:

unless os.date("%A") == "Monday"
print "it is not Monday!"
print "You're lucky!" unless math.random! > 0.1

You can write range checking code with an in-expression.

a = 5
if a in [1, 3, 5, 7]
print "checking equality with discrete values"
if a in list
print "checking if `a` is in a list"

The in operator can also be used with tables and supports the not in variant for negation:

has = "foo" in {"bar", "foo"}
if a in {1, 2, 3}
print "a is in the table"
not_exist = item not in list
check = -> value not in table

A single-element list or table checks for equality with that element:

-- [1,] checks if value == 1
c = a in [1,]
-- {1} also checks if value == 1
c = a in {1}
-- Without comma, [1] is indexing (tb[1])
with tb
c = a in [1]

YueScriptCompiler

Loading compiler…