Download code
From LiteratePrograms
Back to Fibonacci_numbers_(Lua)
Download for Windows: single file, zip
Download for UNIX: single file, zip, tar.gz, tar.bz2
fib.lua
1 -- Copyright (c) 2008 the authors listed at the following URL, and/or 2 -- the authors of referenced articles or incorporated external code: 3 -- http://en.literateprograms.org/Fibonacci_numbers_(Lua)?action=history&offset=20081019232035 4 -- 5 -- Permission is hereby granted, free of charge, to any person obtaining 6 -- a copy of this software and associated documentation files (the 7 -- "Software"), to deal in the Software without restriction, including 8 -- without limitation the rights to use, copy, modify, merge, publish, 9 -- distribute, sublicense, and/or sell copies of the Software, and to 10 -- permit persons to whom the Software is furnished to do so, subject to 11 -- the following conditions: 12 -- 13 -- The above copyright notice and this permission notice shall be 14 -- included in all copies or substantial portions of the Software. 15 -- 16 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 21 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 22 -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 -- 24 -- Retrieved from: http://en.literateprograms.org/Fibonacci_numbers_(Lua)?oldid=15146 25 26 27 function fib(n) return n<2 and n or fib(n-1)+fib(n-2) end 28 29 30 function fastfib(n) 31 fibs={[0]=0, 1, 1} -- global variable, outside the function 32 33 for i=3,n do 34 fibs[i]=fibs[i-1]+fibs[i-2] 35 end 36 37 return fibs[n] 38 end 39 40 41 metafib = { [0]=0, 1, 1 } 42 local mt = { 43 __call = function(t, ...) 44 local args = {...} 45 local n = args[1] 46 47 if not t[n] then 48 for i = 3, n do 49 t[i] = t[i-2] + t[i-1] 50 end 51 end 52 53 return t[n] 54 end 55 } 56 57 setmetatable(metafib, mt) -- now, metafib can be called as if it were a normal function 58 59 60 for n=0,30 do print(fib(n)) end 61 for n=0,30 do print(fastfib(n)) end 62 for n=0,30 do print(metafib(n)) end 63 64 65 66
