lua-users home
lua-l archive

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


On Wed, May 31, 2017 at 7:15 PM J Doe <general@nativemethods.com> wrote:
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.

[...]

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 ?

Remember that Lua was designed first and foremost as an embedded language. The C API doesn't have a function to "run this script"; it only compiles chunks and calls functions. So every script and module is loaded into a "chunk" of source code, then that chunk is compiled as if it were the body of an anonymous function prefixed by "function (...)" and suffixed by "end". You can then call that function if you wish. (The standalone interpreter does all of this for you behind the scenes using the same C API calls.)

So in your example, main() is actually a nested function (function within a function) from the perspective of Lua, and the local declarations at the same level as main() would be local to the anonymous function representing the script.