Function Literals

All functions are created using a function expression. A simple function is denoted using the arrow: ->

MoonScript:

my_function = ->
my_function() -- call the empty function

Lua:

local my_function
my_function = function() end
my_function()

The body of the function can either be one statement placed directly after the arrow, or it can be a series of statements indented on the following lines:

MoonScript:

func_a = -> print "hello world"

func_b = ->
  value = 100
  print "The value:", value

Lua:

local func_a
func_a = function()
  return print("hello world")
end
local func_b
func_b = function()
  local value = 100
  return print("The value:", value)
end

If a function has no arguments, it can be called using the ! operator, instead of empty parentheses. The ! invocation is the preferred way to call functions with no arguments.

MoonScript:

func_a!
func_b()

Lua:

func_a()
func_b()

Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses:

MoonScript:

sum = (x, y) -> print "sum", x + y

Lua:

local sum
sum = function(x, y)
  return print("sum", x + y)
end

Functions can be called by listing the arguments after the name of an expression that evaluates to a function. When chaining together function calls, the arguments are applied to the closest function to the left.

MoonScript:

sum 10, 20
print sum 10, 20

a b c "a", "b", "c"

Lua:

sum(10, 20)
print(sum(10, 20))
a(b(c("a", "b", "c")))

In order to avoid ambiguity in when calling functions, parentheses can also be used to surround the arguments. This is required here in order to make sure the right arguments get sent to the right functions.

MoonScript:

print "x:", sum(10, 20), "y:", sum(30, 40)

Lua:

print("x:", sum(10, 20), "y:", sum(30, 40))

There must not be any space between the opening parenthesis and the function.

Functions will coerce the last statement in their body into a return statement, this is called implicit return:

MoonScript:

sum = (x, y) -> x + y
print "The sum is ", sum 10, 20

Lua:

local sum
sum = function(x, y)
  return x + y
end
print("The sum is ", sum(10, 20))

And if you need to explicitly return, you can use the return keyword:

MoonScript:

sum = (x, y) -> return x + y

Lua:

local sum
sum = function(x, y)
  return x + y
end

Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas:

MoonScript:

mystery = (x, y) -> x + y, x - y
a,b = mystery 10, 20

Lua:

local mystery
mystery = function(x, y)
  return x + y, x - y
end
local a, b = mystery(10, 20)

results matching ""

    No results matching ""