OFPEC Forum

Editors Depot - Mission Editing and Scripting => OFP - Editing/Scripting General => Topic started by: Mr.Peanut on 09 Dec 2004, 14:22:34

Title: Variable scope in functions: is the underscore really necessary?
Post by: Mr.Peanut on 09 Dec 2004, 14:22:34
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.
Title: Re:Variable scope in functions: is the underscore really necessary?
Post by: Mr.Peanut on 09 Dec 2004, 17:22:02
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.
Title: Re: Variable scope in functions: is the underscore really necessary?
Post by: tcp on 07 Sep 2009, 21:28:59
Conversely, is it necessary to use the private function if you are using _underscores?
Title: Re: Variable scope in functions: is the underscore really necessary?
Post by: h- on 07 Sep 2009, 22:11:47
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.
Title: Re: Variable scope in functions: is the underscore really necessary?
Post by: tcp on 08 Sep 2009, 05:13:27
Thanks, very much.