Conditionals
have_coins = falseif have_coins print "Got coins"else print "No coins"have_coins = falseif have_coins print "Got coins"else print "No coins"A short syntax for single statements can also be used:
have_coins = falseif have_coins then print "Got coins" else print "No coins"have_coins = falseif 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 = falseprint if have_coins then "Got coins" else "No coins"have_coins = falseprint 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 tallis_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 tallThe opposite of if is unless:
unless os.date("%A") == "Monday" print "it is not Monday!"unless os.date("%A") == "Monday" print "it is not Monday!"print "You're lucky!" unless math.random! > 0.1print "You're lucky!" unless math.random! > 0.1In Expression
Section titled “In Expression”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"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 tablehas = "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 tableA single-element list or table checks for equality with that element:
-- [1,] checks if value == 1c = a in [1,]
-- {1} also checks if value == 1c = a in {1}
-- Without comma, [1] is indexing (tb[1])with tb c = a in [1]-- [1,] checks if value == 1c = a in [1,]
-- {1} also checks if value == 1c = a in {1}
-- Without comma, [1] is indexing (tb[1])with tb c = a in [1]