![](https://secure.gravatar.com/avatar/c5ae4f9aa0d3a9bd5376e92b322c3e50.jpg?s=120&d=mm&r=g)
On Sat, 2 Aug 2014, luigi scarso wrote:
On Sat, Aug 2, 2014 at 12:59 AM, John Kitzmiller
wrote: Here is Lua code that prints the first nine fibonacci numbers:
local function fib(n) f={1,1} for i=3,9 do f[i]=f[i-1]+f[i-2] end return(f[n]) end for n=1,9 do print(fib(n)) end
Here is Context+Lua that prints 3 x 3 table of the first nine natural numbers:
\starttext \setupTABLE[each][each][frame=off,align=left,width=4em,height=2em] \startluacode context.bTABLE() for j = 0, 2 do context.bTR() for k = 1, 3 do context.bTD() context(3*j+k) context.eTD() end context.eTR() end context.eTABLE() \stopluacode \stoptext
How can these be combined to print a 3 x 3 table of the first nine fibonacci numbers?
I have tried a couple of ways to iterate over the lua table f in the most indented line of context, looked at what pertinent threads I could find, the Wiki entries, CLD, and tried Aditya's method from Stack Exchange; I am missing something.
You have a *global* table f that collides with the internals of context local function fib(n) f={1,1} for i=3,9 do f[i]=f[i-1]+f[i-2] end return(f[n]) end
\starttext \setupTABLE[each][each][frame=off,align=left,width=8em,height=2em]
\startluacode local function fib(n) local f={1,1} for i=3,9 do f[i]=f[i-1]+f[i-2] end return(f[n]) end context.bTABLE() for j = 0, 2 do context.bTR() for k = 1, 3 do context.bTD() context("fib(%s)=%s" ,3*j+k, fib(3*j+k) ) context.eTD() end context.eTR() end context.eTABLE() \stopluacode \stoptext
This version recomputes all fibnocci numbers from scrach each time. Here is a memoized version: \setupTABLE[each][each][frame=off,align=left,width=8em,height=2em] \starttext \startluacode local fibs = {1, 1} local function fib(n) if fibs[n] == nil then print(">>>>", "Computing fib:" .. n) fibs[n] = fib(n-1) + fib(n-2) end return fibs[n] end context.bTABLE() for j = 0, 2 do context.bTR() for k = 1, 3 do context.bTD() context("fib(%s)=%s" ,3*j+k, fib(3*j+k) ) context.eTD() end context.eTR() end context.eTABLE() \stopluacode \stoptext Aditya