github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/runtime/lua/closure.lua (about)

     1  local function counter(start, step)
     2      return function()
     3          local val = start
     4          start = start + step
     5          return val
     6      end
     7  end
     8  
     9  local nxt = counter(5, 3)
    10  print(nxt(), nxt(), nxt(), nxt())
    11  --> =5	8	11	14
    12  
    13  local function fib(a, b)
    14      return function()
    15          local c = a
    16          a, b = b, a + b
    17          return c
    18      end
    19  end
    20  
    21  local f = fib(1, 1)
    22  print(f(), f(), f(), f(), f(), f())
    23  --> =1	1	2	3	5	8
    24  
    25  -- equality of closures
    26  local function mkf()
    27      return function(x) return x + _ENV.x end
    28  end
    29  
    30  print(mkf() == mkf())
    31  --> =true