lua-users home
lua-l archive

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

On Aug 26, 2013, at 12:15 PM, Sven Olsen <> wrote:

> Well, there is a bit of a hiccup, because Lua creates implicit "shadowed" locals anytime you write nested for loops.
> But, I suppose such cases are easily identified -- they'll be overlaps between locals with names that aren't legal ids -- things like "(for generator)".  
> If the behavior you want is to emit an error in response to something like Steve's shadow.lua, hooking into the parser to turn such situations into compile time errors would be fairly straightforward.  I'd suggest performing a check after each call to adjustlocalvars()  -- iterating through the local variable list, and checking that the new locals have startpc's higher than the endpc's of any locals that share the same name.
> I'm still not convinced it's a great idea though :)  As the nested for loop case illustrates; there are perfectly valid reasons for Lua programmers to use shadowed locals.  So if you do write a patch for it, I'd certainly make it something that can be turned on and off via a debug function.
> -Sven

I don't think this is quite as simple as all that. Consider this:

local a = 1
function foo()
	return a
local a = 2

Clearly, foo() prints 2, as it should, since a is an upvalue. Now, it's been a while since I looked at Roberto's paper on how the VM handles upvalues, but clearly deciding on when a "new" local of the same name can reuse a stack slot assigned to a previous one is not just as a simple as checking the name and scope of the local. I suspect that is why the compiler takes a conservative approach (remember, the compiler is supposed to be very fast, and these smart checks take time), since the downside is pretty minor.

My original parasitic case seemed sufficiently odd that I felt it only warranted a "don't do this" note in the docs.