lua-users home
lua-l archive

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


On Mon, Aug 23, 2010 at 16:19, Andreas Matthias
<andreas.matthias@gmail.com> wrote:
> Drake Wilson wrote:
>
>> Quoth Andreas Matthias <andreas.matthias@gmail.com>, on 2010-08-23 23:11:15 +0200:
>>> function foo()
>>>    bar()
>>> end
>>>
>>> local function bar()
>>> end
>> [...]
>>> What's going on here? I don't understand it.
>>
>> The scope of a lexical local starts after its declaration and extends
>> to the end of the containing block.  A local function is just like any
>> other local variable in that regard.
>
> 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?
>
>>  One way of doing what you seem
>> to want is to declare « local bar » above, then use « bar = function()
>> ... end ».  Another, more obvious way would be to just let it be a
>> 'global' (in the current environment table).
>
> I see. So the following works:
>
>
> local bar
>
> function foo()
>   bar()
> end
>
> bar = function () end
>
>
> But what's happening if I change this to:
>
>
> local bar
>
> function foo()
>   bar()
> end
>
> local bar = function () end
>
>
> These two `bar's seem not to be the same. Why?
>
>
> Ciao
> Andreas
>
>

Basically, when you define a function, it looks in the current scope
for any variables referenced within. If they aren't found in the local
scope, it assumes they're globals. Locals defined after the function
don't affect this lookup.

To demonstrate:

local a=1 --a is now defined in local scope.
function print_a() print(a) end --will refer to the a defined above.
print_a() --finds local a, prints 1

a = 2 --modifying the same a.
print_a() --finds local a, prints 2

_G['a'] = 9 --defining a global a.
print_a() --still prints 2, because it looks at *local* a, not global a.

local a=8 --creates a NEW local a. We can no longer access the old one, but
          --print_a() will still use it - the new local a is a different
          --variable despite having the same name.
print_a() --still prints 2

function print_b() print(b) end --b is not defined yet, so assumes it's a global
print_b() --global b is not defined, so prints nil

b = 3 --defining global b
print_b() --prints 3

local b = 7 --defining local b
print_b() --still prints 3, because it looks at *global* b, since local b did
          --not exist when this function was defined.
print(b) --prints 7, because local b exists now.

function print_c() print(c) end --assumes c is a global
local c = 9 --defining local c
print_c() --prints nil, because print_c() is looking at global c


I hope that's clear enough. The gist of it is, a function uses the
locals that existed when it was defined, not when it's called.

-- 
Sent from my toaster.