Home   Help Search Login Register  

Author Topic: Variable scope in functions: is the underscore really necessary?  (Read 1397 times)

0 Members and 1 Guest are viewing this topic.

Offline Mr.Peanut

  • Former Staff
  • ****
  • urp!
In a function variables are declared as follows:

Code: [Select]
Private ["_a","_b"]
Are the underscores really necessary since I am using the Private directive?

Can I just use:

Code: [Select]
Private ["a","b"]
instead to declare variables private to the function? I am translating an algorithm in a different language and the prospect of adding all those underscores is daunting.
urp!

Offline Mr.Peanut

  • Former Staff
  • ****
  • urp!
I've just been trying in vain to debug my code and found it will NOT accept private variables unless they start with an underscore. I guess that answers my question.
« Last Edit: 10 Dec 2004, 02:58:28 by Mr.Peanut »
urp!

Offline tcp

  • Members
  • *
    • Violator Gaming
Conversely, is it necessary to use the private function if you are using _underscores?

Offline h-

  • OFPEC Site
  • Administrator
  • *****
  • Formerly HateR_Kint
    • OFPEC
Instead of digging up almost 5 years old topic you could have started a new one..  :cop:

Anyhoo, using private with functions is mandatory because the function you call in a script shares the same scope with the script so if you have a variable called _var both in the script and in the function they override each other (depending in which it comes last) unless you private it in the function.
(this is true at least in OFP, I haven't tested this in A1/A2)

So if you have a script executed by a soldier unit
Code: (script.sqs) [Select]
_var = _this select 0

#check
~3

_stuff = _var call myfunction

?(alive _var): goto "check"

And the function
Code: (myfunction.sqf) [Select]
_unit = _this
_var = magazines _unit

..codecodecodecode

That would cause you errors/problems because in the script the variable _var would now be the _var from the function and not the unit it was originally set as.
« Last Edit: 07 Sep 2009, 22:15:53 by h- »
Project MCAR   ---   Northern Fronts   ---   Emitter 3Ditor
INFORMATIVE THREAD TITLES PLEASE. "PLEASE HELP" IS NOT ONE..
Chuck Norris can divide by zero.

Offline tcp

  • Members
  • *
    • Violator Gaming
Thanks, very much.