lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Rich Artym wrote:

  ; Defines and applies function incfoo1 using free variable foo
  ; but overrides (foo 10) with (foo 20) before function is used.
  (let* ((foo
              (lambda () (+ foo 0.1)))
              (let* ((foo         ; Let's change foo (as in Lua)
                         20))     ; to try to make incfoo1 use 20.
                    incfoo1))     ; Will this closure be affected?
       (incfoo2))     ; No, prints 10.1 because incfoo1 is a closure
                      ; which protects it against the change in foo
  ; ----------------------------------------------------------------

A Lua equivalent of that is the following, which acts the
same way:

    local foo = 10
    local incfoo1 = function()
                      return foo + 0.1
                    end -- incfoo1
    local incfoo2 = function()
                      local foo = 20 -- Changing a new foo in
                        -- a different scope; doesn't affect
                        -- incfoo1.
                      return incfoo1()
                    end -- incfoo2
    local bar = 65
    print(incfoo2()) -- Prints 10.1 because Lua is lexically scoped.

Instead of thinking of 'local' as being like one of the
versions of 'let' (I can never remember which version is
which), think of the space between the 'do' and the 'end' as
being the 'let', and the individual 'local's are like
different variables being set within the same 'let'.