Argument Defaults

It is possible to provide default values for the arguments of a function. An argument is determined to be empty if its value is nil. Any nil arguments that have a default value will be replace before the body of the function is run.

MoonScript:

my_function = (name="something", height=100) ->
  print "Hello I am", name
  print "My height is", height

Lua:

local my_function
my_function = function(name, height)
  if name == nil then
    name = "something"
  end
  if height == nil then
    height = 100
  end
  print("Hello I am", name)
  return print("My height is", height)
end

An argument default value expression is evaluated in the body of the function in the order of the argument declarations. For this reason default values have access to previously declared arguments.

MoonScript:

some_args = (x=100, y=x+1000) ->
  print x + y

Lua:

local some_args
some_args = function(x, y)
  if x == nil then
    x = 100
  end
  if y == nil then
    y = x + 1000
  end
  return print(x + y)
end

results matching ""

    No results matching ""