lua-users home
lua-l archive

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


[Aaron Brown <aaron-lua@oakadaptive.com>]
> 
> 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'.
> 

Yeah, comparing Lua's
  x = y
to "let" in Lisp or Scheme as totally wrong. Assignment in Lua is a
destructive update, like 'set!' in Scheme.

To translate 'let*' to lua, you need to use multiple scopes (i.e.,
multiple do...end blocks). To see how lua's lexical scoping behavior
exists also in Scheme, you need to use set!, as in the following:

    (define x 5)
    (define (inc-x)
     (set! x (+ x 1))
      (display x)(newline))

    (display x) ;; prints 5
    (newline)
    (inc-x)     ;; prints 6
    (display x) ;; prints 6
    (newline)
    (set! x 10)
    (display x) ;; prints 10
    (newline)
    (inc-x)     ;; prints 11
    (display x) ;; prints 11
    (newline)

(I've tried to dot the i's and cross the t's, to leave no room for
equivocation.) 

The proof is in the pudding:

    [mhellige: mhellige]$ guile -s foo.scm
    5
    6
    6
    10
    11
    11
    [mhellige: mhellige]$ 

Here's the precisely equivalent lua code:

    do
      local x = 5
      function inc_x()
        x = x + 1
        print(x)
      end

      print(x)
      inc_x()
      print(x)
      x = 10
      print(x)
      inc_x()
      print(x)
    end
 
and the proof:

    [mhellige: mhellige]$ lua foo.lua
    5
    6
    6
    10
    11
    11
    [mhellige: mhellige]$ 

Matt

-- 
Matt Hellige                  matt@immute.net