lua-users home
lua-l archive

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


I posted a Scheme program and an equivalent Lua program
earlier.  Here are improved versions.  (As I said, I'm not
fluent in Scheme, so they might not be exactly equivalent,
but they're close enough for our purposes.)

  ;; Scheme version:
  (define func nil)
  (let ((foo 'bar))
    (set! func (lambda ()
                    foo))
    (set! foo 'baz)) ;; Alters the foo within func.
  ;; Outside the 'let':
  (define foo 'quux) ;; If this were a 'set!', we'd get an
                     ;; error.
  (func) ;; Returns baz.

  -- Lua version:
  do
    local foo = "bar"
    function func()
      return foo
    end -- func
    foo = "baz" -- Alters the foo within func.
  end
  -- Outside the 'do' block:
  foo = "quux" -- This is global, but even if it had 'local'
    -- in front of it, the 'foo' inside 'func' is still
    -- unreachable.
  print(func()) -- Prints "baz"

Remember that every Lua program is one 'chunk' -- that is,
it's surrounded by an implicit 'do' block, kind of like
being in a giant 'let'.  (Or 'let*' or 'letrec' or
whatever.)

-- 
Aaron