Condicionais
have_coins = falseif have_coins print "Tem moedas"else print "Sem moedas"have_coins = falseif have_coins print "Tem moedas"else print "Sem moedas"Uma sintaxe curta para instruções únicas também pode ser usada:
have_coins = falseif have_coins then print "Tem moedas" else print "Sem moedas"have_coins = falseif have_coins then print "Tem moedas" else print "Sem moedas"Como instruções if podem ser usadas como expressões, isso também pode ser escrito como:
have_coins = falseprint if have_coins then "Tem moedas" else "Sem moedas"have_coins = falseprint if have_coins then "Tem moedas" else "Sem moedas"Condicionais também podem ser usados em instruções de retorno e atribuições:
is_tall = (name) -> if name == "Rob" true else false
message = if is_tall "Rob" "Sou muito alto"else "Não sou tão alto"
print message -- imprime: Sou muito altois_tall = (name) -> if name == "Rob" true else false
message = if is_tall "Rob" "Sou muito alto"else "Não sou tão alto"
print message -- imprime: Sou muito altoO oposto de if é unless:
unless os.date("%A") == "Monday" print "não é segunda-feira!"unless os.date("%A") == "Monday" print "não é segunda-feira!"print "Você tem sorte!" unless math.random! > 0.1print "Você tem sorte!" unless math.random! > 0.1Em expressão
Seção intitulada “Em expressão”Você pode escrever código de verificação de intervalo com uma in-expression.
a = 5
if a in [1, 3, 5, 7] print "verificando igualdade com valores discretos"
if a in list print "verificando se `a` está na lista"a = 5
if a in [1, 3, 5, 7] print "verificando igualdade com valores discretos"
if a in list print "verificando se `a` está na lista"O operador in também pode ser usado com tabelas e suporta a variante not in para negação:
has = "foo" in {"bar", "foo"}
if a in {1, 2, 3} print "a está na tabela"
not_exist = item not in list
check = -> value not in tablehas = "foo" in {"bar", "foo"}
if a in {1, 2, 3} print "a está na tabela"
not_exist = item not in list
check = -> value not in tableUma lista ou tabela de único elemento verifica igualdade com esse elemento:
-- [1,] verifica se valor == 1c = a in [1,]
-- {1} também verifica se valor == 1c = a in {1}
-- Sem vírgula, [1] é acesso por índice (tb[1])with tb c = a in [1]-- [1,] verifica se valor == 1c = a in [1,]
-- {1} também verifica se valor == 1c = a in {1}
-- Sem vírgula, [1] é acesso por índice (tb[1])with tb c = a in [1]