Skip to content

2. Functions


1. Functions

----------------------------------------------------
-- 2. Functions.
----------------------------------------------------

function Fib(n)
  if n < 2 then return 1 end

  return Fib(n - 2) + Fib(n - 1)
end

-- Closures and anonymous functions are ok:
function Adder(x)
  -- The returned function is created when adder is called,
  -- and remembers the value of x:
  return function(y) return x + y end
end

A1 = Adder(9)
A2 = Adder(36)
print(A1(16))
print(A2(64))

-- Returns, func calls, and assignments all work
-- with lists that may be mismatched in length.
-- Unmatched receivers are nil;
-- unmatched senders are discarded.

X, Y, Z = 1, 2, 3, 4
-- Now X = 1, Y = 2, Z = 3, and 4 is thrown away.

function Bar(a, b, c)
  print(a, b, c)
  return 4, 8, 15, 16, 23, 42
end

X, Y = Bar("zaphod") --> Prints "zaphod nil nil"
-- Now X = 4, Y = 8, values 15...42 are discarded.

-- Functions are first-class, may be local/global.
-- These are the same:
function F(x) return x * x end

F = function(x) return x * x end

-- And so are these:
local function g(x) return math.sin(x) end

local g;
g = function(x) return math.sin(x) end
--the 'local g' decl makes g-self-references ok.

-- Trig funcs work in radians, by the way.

-- Calls with one string param don't need parens:
print "hello" -- Works fine.

References