lua-users home
lua-l archive

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


Hello,

I am currently reading through "Lua Programming Gems" (2008).  I am on chapter 2 where Roberto discusses the advantage of local variables in terms of optimization.

The one part I am confused about is when a reference to a function is made local in what appears to be the global scope.

I understand why:

local sin = math.sin
for i = 1, 1000000 do
	local x = sin(i)
end

...is faster, due to the local reference before the loop.  I also understand that, in the case of a function:

local sin = math.sin
function foo (x)
	for i = 1, 1000000 do
		x = x + sin(i)
	end
	return x
end

...is faster than having the local reference inside of the function (but outside of the loop).    I've confirmed this with some os.clock() calls and repetitions to gain averages.

What is confusing me is when the local *APPEARS* to my C/C++ eyes as being a part of the global space.  A quick example:

local sin = math.sin

local function foo (x)
	for i = 1, 1000000 do
		x = x + sin(i)
	end
	return x
end

local function main()
	foo(10)
end

main()

The fact that the local reference is made in the same "space" as main() would cause me to think that it is in the global scope, because it's free of any enclosing function.  However, when I examine the variable in the debugger of the Lua plugin in Eclipse Neon (Lua Dev Tools 1.4.1 using Lua 5.2 - I realize that I am not using the most up to date version of Lua, but the product I am using Lua with - ModSecurity 2.9.1 - uses Lua 5.2), the debugger correctly places sin at a scope other than the global scope.

Is it just because I am used to C/C++ rules that I am confused ?  I can see that the addition of "local" means "not in the global memory area", but what is the scope of the reference to math.sin() actually called in this instance ?  What "chunk" does it belong to ?

Thanks,

- J