I thought that Scope was the body in between the function and end, but I've now learned that this is referred to as a code block. What's the difference?
The scope of a variable is where that variable can be used. The 'of a variable' part is important, since scope depends on which variable you're talking about.
The scope of local variables (and variables initialized in for
loops and function arguments) ends at the end of the block they were defined in.
However, it begins at the variable's definition, rather than at the beginning of the block it was defined in (compare this behavior to JavaScript, MATLAB, etc). Thus while a scope is usually at least approximately across one block, it could be less.
In addition, repeat
has a weird scope in that the until
is still part of the block.
Also, the scope of global variables is the whole program. Having large scopes can be problematic because it allows you to make extremely complicated code--many places can simultaneously be important. This is the reason global variables (and even worse, _G
) usually ought to be avoided.
A block of code is the group of statements between then
, do
, else
, function
and end
else
, elseif
, or between repeat
and until
.
Difference?
There's no significant different between them. There's always a person who can make an argument saying all scopes are code blocks, but not all code blocks are scopes
, however this would be taking it in a very literal sense.
Explanation
"Code block" is basically the definition of what a scope is, so either term can be used. However I'd use "code block" a little more loosely than "scope", simply because saying scope is implying you've created a new "environment" (don't take that literally) for variables, whereas a block of code can be anything.
Summed up
Summed all up, don't think to hard about it. They're both 99% the same.