lua-users home
lua-l archive

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


> Hello,

Hi

> ... snip
> > for i = 1, getn(a) do
> >> print(a[i])
> error: `do' expected;
>   last token read: `doprint' at line 1 in stdin
> ... snip

> I had to insert a space before print to make it work correctly. Is it the
> expected behaviour?

It's not what I would have expected :-)

> 2. Can't recursive functions be defined as local like in:
> fac = function (n)
>          local fc = function(n)
>                       if n < 2 then
>                          return 1
>                 else
>                    return n * fc(n-1)
>                 end
>              end
>         return fc(n)
>      end
>--> error: attempt to call global `fc' (a nil value)


No, they can't, sorry. You have to say:

local fc
fc = function(n) ... end

The scope of a local declaration starts with the following statement. So
the use of "fc" inside the local statement refers to the global scope, in
which fc doesn't exist.

This may seem odd, but its consistent. If you had said:

local a, b = b, a

You would have been setting a local a to the global b and a local b to the
global a. Clearly:

local a = a

would not be meaningful if the scope of the local declaration started with
the local statement itself.

Many Scheme-like languages (or Lisp-like languages for those of us who
predate Scheme) have two versions of "local" declarations. In Scheme these
are "let" and "letrec"; letrec is a mysterious abbreviation of "let
recursive" in which the scope includes the definition, precisely in order
to allow the definition of local recursive functions.

Lua does not have this mysterious keyword, but it does offer the
work-around described above. Opinions vary about this :-)


> 3. last thing
> I've found a nice place for beginners, called PLEAC
> (http://pleac.sourceforge.net/). It sure would be nice if lua had an
entry there
> too!!

Very nice. Thanks for the pointer.

Rici