[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Visibility and upvalues (and macros)
- From: Dave Bollinger <DBollinger@...>
- Date: Wed, 28 Jul 1999 21:51:20 -0400
Somewhat lengthy message follows...
It seems that I work with Lua for a while, feeling comfortable with the
static nature of upvalues, and then I make a dumb mistake and start to
wonder about them again. I wonder why can't a local function access an
enclosing function's local variables? (I'm sure this is caused by
expectactions picked up while working with Pascal, in particular; and
declared variables, in general) I understand the explanation that the
variable might no longer exist - and I *assume* that this is because Lua
needs to be able to make a compile-time decision on this issue, yes?
Consider the following contrived example:
function f(x)
local fl
local g = function(a)
local gl = fl -- ERROR: cannot access a variable in outer scope
end
fl = 7
g(123) -- if allowed, this would have been a "good" call
fl = nil
g(234) -- this is the situation Lua's visibility rule is trying to
prevent
-- but why can't g see the "value" of fl as nil?
end
Admittedly this is an extremely contrived example. (simply passing fl
as a formal parameter would fix it) But I can't get seem to get a firm
handle on why this should be illegal. How is it different from this (which
does work):
Also, just regarding local variable visibility in general: I know some
discussion has gone on before in the list about local versus globals vars,
but... Let's say I build a string like "fl = 123" and execute it via
dostring() within the body of f() above. What happens? The assignment
occurs to a global "fl" not a local "fl". Is it another aspect of a
compile-time issue that prevents Lua from having some mechanism for forcing
an expression to be evaluated in a more local scope?
It might be legitimate to ask why I care. <grin> The other thread
regarding macros got me thinking about this again. If functions could
execute with local scope inside a function you could do a bit more
macro-type coding - defining "for" loops for example that process local
data. Hmm, can I come up with an example... This is probably the silliest
implementation of a "for" statement from a performance standpoint, but just
for amusement consider:
function testfor()
local i
local for = function(init, comp, incr, body)
dostring(init)
while dostring("return ("..comp..")") do
dostring(body)
dostring(incr)
end
end
for("i=1", "i <= 10", "i=i+1", [[
local i2 = i * i
print("square of "..i.." is "..i2)
]])
print(i) -- is still nil, not 11
-- what we were attempting to get was *local* effects from the
function call
end
testfor()
Again, very contrived. But I think that functions with local scope
*could* be made to behave very much like macros in many cases. I'm looking
forward to real macros though. :-)
Cheers,
Dave