LSL Wiki : CrashCourse3

HomePage :: PageIndex :: RecentChanges :: RecentlyCommented :: UserSettings :: You are
Chapter Listing
< 1 2 3 4 5 6 7 8 9 >

3) Codeblocks
A codeblock is a well-formed sub-piece of a program/script. In LSL, it is enclosed in curly braces. It's important to keep curly braces: { }, brackets: ( ) and square brackets: [ ] straight. They're all used in different situations, which can be confusing.

if (0 == 1)
   // this could never occur! if it does, shoot me!
   llWhisper(0, "Houston, we have a problem.");
Notice that the block contains a comment and a function call. We are passing two arguments to the function llWhisper, enclosed in parentheses, namely the 0 (an integer literal), and "Houston, we have a problem." (a string literal), respectively.

You may declare variables inside a code block, and they will be useable within that block or sub-blocks inside it. Outside the context of that block (called "scope"), things are not meaningful. So the following is nonsense:
integer x = 0;
// ... (some other code)
if (x == 0)
   integer y = 1;
x = y; // this is not valid -- y is only in scope within the above sub-code-block
When we try to assign the variable x the value stored in y, we notice that y is no longer in scope, so we'll get an error. If we had declared y outside that block, in the parent block (which is implied), it would be okay. In other words, a code block inside another code block hides its contents from the outer block, but the inner block can "see" everything in the outer block, in addition to its own scope.

Now you may realize: variables declared near the top of the script, outside any code block, are called global -- they are in scope for the entire script, which can be useful, but can also be abused. In general, try to avoid using global variables if you don't need them. But of course, it's good to make constants global. Variables that are declared inside a code block are called local.

Previous | Next

Homepage | Tutorial | CrashCourse | Glossary
Comments [Hide comments/form]
Shouldn't the line in the second to last paragraph read, "If we had declared y", not 'x'? Sorry if I'm mistaken.
-- MonahanWake (2006-01-12 10:20:42)
For most small scripts, it's easy to spot problems (e.g., assigning a new value to something that's supposed to be constant). When your functions grow large, I recommend "Hungarian notation" as an easy way to make sure that wrong code looks wrong.

For more info on Hungarian notation, visit
-- (2007-08-12 23:21:03)
Attach a comment to this page: