lua-users home
lua-l archive

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


Quoth Andreas Matthias <andreas.matthias@gmail.com>, on 2010-08-24 00:19:22 +0200:
> Ok, that's reasonable. But why does lua find bar() if it is
> defined as a non-local? Why doesn't it need a kind of
> function prototype then?

It _doesn't_ find it, or more specifically it doesn't find a function
there.  That's what "attempt to call global 'bar' (a nil value)"
means.  Lua does no static checking of types or of global variable
accesses by default, and nor is accessing undefined globals an error;
they are just like table accesses.  After entering foo(), you have an
attempt to retrieve the global 'bar' (which succeeds with nil, because
no such variable has been defined) and then call the resulting value
(which fails, because nil is not a function).

IOW, you can do the same thing without ever defining 'bar' at all, at
you will get the same error.

> local bar
> 
> function foo()
>    bar()
> end
> 
> local bar = function () end
> 
> These two `bar's seem not to be the same. Why?

Because each 'local' statement declares a new 'bar' variable.  The
former contains nil, and the function definition (which you happen to
assign to the global 'foo', but that's actually irrelevant here) gets
access to that first 'bar' variable as a closed-over upvalue.  Then
you declare a new 'bar', which shadows the first one for each lexical
occurrence of 'bar' from after that statement to the end of the block.

> Ciao
> Andreas

   ---> Drake Wilson