# Fibonacci numbers (Lua)

### From LiteratePrograms

**Other implementations**: ALGOL 68 | Alice ML | bc | C | C Plus Plus templates | dc | E | Eiffel | Erlang | Forth | FORTRAN | Haskell | Hume | Icon | Java | JavaScript | Lisp | Logo |**Lua**| Mercury | OCaml | occam | Oz | Pascal | PIR | PostScript | Python | Ruby | Scala | Scheme | Sed | sh | sh, iterative | Smalltalk | 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

- 1 \\ \end{cases} ."/>

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 metafib test

## Contents |

## 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

## 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. This is a common technique called memoization.

<<fastfib>>=functionfastfib(n)fibs={[0]=0, 1, 1}-- global variable, outside the function for i=3,n do fibs[i]=fibs[i-1]+fibs[i-2] end return fibs[n] end

## Metatables

The outer table can be avoided by using metatables to fuse the external table and the function in a single object.

<<metafib>>=metafib ={[0]=0, 1, 1}localmt ={__call =function(t, ...)localargs ={...}localn = args[1]ifnott[n]thenfori = 3, ndot[i]= t[i-2]+ t[i-1]endendreturnt[n]end}setmetatable(metafib, mt)-- now, metafib can be called as if it were a normal function

## Test

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

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

Download code |