[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: question about local function closures
- From: Russell Smith <russ.ls@...>
- Date: Fri, 18 Feb 2005 15:49:33 -0800
hi,
i have a question about why locally defined functions behave as they
do in Lua 5.0. if i run the following snippet of code:
--- example 1 ---
helper = 1
function test()
local helper = function()
print (helper)
end
helper()
end
test()
---
a '1' is printed, indicating that inside the helper function the
helper variable is not picked up as part of helper's closure state.
however if i rewrite this function slightly, like this:
--- example 2 ---
helper = 1
function test()
local helper
helper = function()
print (helper)
end
helper()
end
test()
---
then 'function: XXXXXXXX' is printed, indicating that now 'helper'
*is* part of the closure. my question is why these two examples should
be different - to my way of thinking "local a=b" and "local a; a=b"
should always be equivalent (and for me the first example should print
'function').
this code pattern is useful for recursive functions (calling helper
inside helper) and i use it all the time. anyway, there is probably a
good reason that i've overlooked why it is this way ... and of course
changing the language in a subtle way like this would introduce all
kinds of hard to find bugs in people's code :)
russ.
--
Russ Smith
http://www.q12.org/