lua-users home
lua-l archive

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



On 4-Oct-06, at 3:09 AM, Nick Gammon wrote:


On 04/10/2006, at 6:01 PM, David Olofson wrote:


	procedure do_stuff(y)
	{
		for local x = 1, 10
			for local y = 1, 10
				<stuff>;
	}

This will not compile, as the declaration 'local y' in the inner loop
tries to redeclare the 'y' argument of the procedure. Same thing if x
was declared outside the procedure; it wouldn't compile because
'local x' would be an attempted redeclaration.


However Lua currently allows redefinition, eg.

local y = 1;
f ()  -- uses 1st y
local y = 2;
f () -- uses 2nd y

Actually, neither y is visible inside f(). The case where it
would be is:

local y = 1
function f()
  print(y)
  y = y + 1
end
local y = 2
function g()
  print(y)
  y = y + 2
end

The y in f() and the y in g() are different. That's a Good Thing.

As in C/C++, local variables are local to the block they're declared in. That's also a Good Thing: a local variable represents a resource, and even if that resource is "just" a stack slot, it's use ought to be as limited in scope as possible.

So the above example should have been written:

do
  local y = 1
  function f()
    print(y)
    y = y + 1
  end
end

do
  local y = 2
  function g()
    print(y)
    y = y + 2
  end
end

Some languages, like Python, allow variables to be local only to a function (execution frame). That's wrong. Languages like Lua and C/C++ correctly scope variables to the block they're defined in. Lua, unlike C/C++, does not conflate scope with lifetime.