# Fibonacci numbers (Lua)

**Other implementations**: bc | C | C Plus Plus templates | dc | E | Erlang | FORTRAN | Haskell | Icon | Java | JavaScript | Lisp |**Lua**| occam | Oz | PIR | Prolog | Python | Sed | sh | sh, iterative | T-SQL | Visual Basic .NET

The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by

Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.

In this article we show two ways of calculating fibonacci numbers in Lua.

<<fib.lua>>=fib fastfib test

## [edit] Recursive

This is a very simple recursive implementation. This will become slow on big numbers, because the numbers are recalculated for each recursion.

<<fib>>=functionfib(n)returnn<2andnorfib(n-1)+fib(n-2)end

## [edit] Iterative with table

This is a faster, but also somewhat more complicated way to calculate fibonacci numbers. To avoid recalculation and recursion, all results are stored in a table.

<<fastfib>>=functionfastfib(n)fibs={1,1}fori=3,ndofibs[i]=fibs[i-1]+fibs[i-2]endreturnfibs[n]end

## [edit] Test

If we run this test code, we can see that the iterative method is significantly faster then the recursive.

<<test>>=forn=1,30doprint(fib(n))endforn=1,30doprint(fastfib(n))end

Download code |