Conditionals

MoonScript:

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

Lua:

local have_coins = false
if have_coins then
  print("Got coins")
else
  print("No coins")
end

A short syntax for single statements can also be used:

MoonScript:

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

Lua:

local have_coins = false
if have_coins then
  print("Got coins")
else
  print("No coins")
end

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

MoonScript:

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

Lua:

local have_coins = false
print((function()
  if have_coins then
    return "Got coins"
  else
    return "No coins"
  end
end)())

Conditionals can also be used in return statements and assignments:

MoonScript:

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

Lua:

local is_tall
is_tall = function(name)
  if name == "Rob" then
    return true
  else
    return false
  end
end
local message
if is_tall("Rob") then
  message = "I am very tall"
else
  message = "I am not so tall"
end
print(message)

The opposite of if is unless:

MoonScript:

unless os.date("%A") == "Monday"
  print "it is not Monday!"

Lua:

if not (os.date("%A") == "Monday") then
  print("it is not Monday!")
end

MoonScript:

print "You're lucky!" unless math.random! > 0.1

Lua:

if not (math.random() > 0.1) then
  print("You're lucky!")
end

results matching ""

    No results matching ""