• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

GML var inside the if loop block

E

el_Bro

Guest
Hi, I know we can omit parentheses:
var x = 5;
if(x)
show_debug_message("x = 5");
var y = 1;
show_debug_message("y = 1");
output:
// x = 5
// y = 1
Is variable 'y' inside or outside the loop? How to put it in if statement that doesn't have parentheses?
And is this that case when I have to write parentheses necessarily?
 

FrostyCat

Redemption Seeker
You can omit the braces in if, for, while, do, repeat, with only when it presides over a single command after it. Any more and the commands must be enclosed between braces to count as part of the same control structure. In your example, the if is braceless and the y line is not the immediate next command, so the y line is outside the if.
 

TheouAegis

Member
Code:
var x = 5;
if x {
    show_debug_message("x = 5");
    var y = 1;
    show_debug_message("y = 1");
}
That will set the temporary variable y to 1, creating the variable if it hasn't yet been created in the current block of code, if and only if the temporary variable x has a value greater than +1/2. If that's what you're referring to, then as Frosty said, you need those brackets.

Bonus tidbit: You also need those brackets if you want the third part of a for loop to have multiple actions.
Code:
for(var a=0, i=0; i<10; {a=++a & 3; i+=!(a&3);})
     some_code();
And in the case of a for loop, those parentheses () are required.

if (conditional)
The () around the conditional are not required in GM, they just make code "proper" for some people.
The same is true for repeat and do/until.

with (instance)
The () around the instance are not required in GM, they just make code "proper" for some people.

for (statement; condition; expression; )
The () are required since the command functions like a script and all three "arguments" are required.
Semicolons are required after the statement and condition, but not after the expression.

if conditional;
with instance;
for (statement; condition; expression);

All three of these will cause a "malformed statement" error upon compile because the semicolon at the end of each one terminates them prematurely.

if conditional {}
This is junk code, but GM will recognize it as a branch to an empty subroutine. In this case, the { } brackets are required even though it's a single action.
 
Top