Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What's the difference between Scope and Code Blocks?

Asked by 8 years ago

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?

2 answers

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

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.

0
Thanks for the great definition of scope :) now I'm sure I'll always have it right! HaloStorm22 10 — 8y
Ad
Log in to vote
0
Answered by 8 years ago

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.

0
Thanks a lot! Great clarification! Thanks :) HaloStorm22 10 — 8y

Answer this question