Author Topic: Doubt about variables  (Read 903 times)

Theremin

  • Full Member
  • ***
  • Posts: 154
  • Karma: +48/-18
  • Worst Server Owner
    • View Profile
    • Visit my YouTube channel
Doubt about variables
« on: September 03, 2015, 01:13:14 am »
Is it correct to put a local variable outside a function? One example in this thread made me doubtful.

You see there are local variables outside functions, here:
Code: [Select]
local godmode = false;
local isadmin = false;

function onClientRender() {
local plr = FindLocalPlayer();
if (godmode)
{
plr.Health = 100;
plr.Armour = 100;
}
}

function onClientSpawn( pClass )
{
local player = FindLocalPlayer();
if (player.Name == "yournamehere")
{
IsAdmin = true;
}
}

function onClientCommand ( szCommand, szParams )
{
if (szCommand == "godmode")
{
if (IsAdmin)
{
if (godmode) {
godmode = false;
Message("Godmode turned off");
}
else {
godmode = true;
Message("Godmode turned on");
}
}
}
return 1;
}
Is this correct?

Ankris

  • Full Member
  • ***
  • Posts: 110
  • Karma: +29/-44
    • View Profile
Re: Doubt about variables
« Reply #1 on: September 04, 2015, 09:50:14 pm »
Yep, it is.

Quote
Local variables can be declared at any point in the program; they exist between their declaration to the end of the block where they have been declared. EXCEPTION: a local declaration statement is allowed as first expression in a for loop.

Theremin

  • Full Member
  • ***
  • Posts: 154
  • Karma: +48/-18
  • Worst Server Owner
    • View Profile
    • Visit my YouTube channel
Re: Doubt about variables
« Reply #2 on: September 05, 2015, 03:38:17 am »
Quote
to the end of the block where they have been declared

I've read the squirrel pdf already before creating this thread but what's the meaning of the above? as "end of the block" I took it for the end of the function maybe, otherwise I don't know, end of the script? Seems unlikely to me. Also, if a local variable keeps existing until the end of the script, what's the point of a global variable?

All this stuff confuses me even more ><

Ankris

  • Full Member
  • ***
  • Posts: 110
  • Karma: +29/-44
    • View Profile
Re: Doubt about variables
« Reply #3 on: September 05, 2015, 12:22:31 pm »
Quote
to the end of the block where they have been declared
[...]

Code: [Select]
if (val_2 == 1) print(1); //error, cos 'val_2' need be declared first

local val_2 = 0; //start of declaration
function test {
 local val = 0; //start of declaration
} // <- end of the block

if (val_2 == 0) print(1);

// end of da script/block //

you can use locals, conditions, everything outside of funcs
the only difference i saw (time ago) between global and local declaration is: local is used one time, and global can be used anytime.. (i mean, if you use 'compilestring' with a local, you can't access to change it, but with global variable ye)
« Last Edit: September 05, 2015, 12:24:24 pm by Ankris »

 

© Liberty Unleashed Team.