Optional Arguments for SQF


Rather than writing more than one function to handle basically one action, you can build in defaults and optional arguments into your SQF scripts by using a simple if statement.

Lets say we had a function that would spawn a carpet for our soldier to sit on if he were tired. But what if he has friends around who would like to sit in a chair? Instead of writing two SQF files, one for making the carpet and one for the chair, we can use options in our arguments and spawn one or both with a single SQF file.

Here’s two ways you could call this script:

// Just the carpet.
// nul = [unit] execVM "cozy.sqf";

// Carpet and chair!
// nul = [unit, true] execVM "cozy.sqf";

We’ll use an if statement counting how many arguments there are in the magic _this array. If it’s more than 1 (the unit) we’ll use whatever it gives us (true) otherwise we’ll default to false. Here is the code for the script.

// Who is tired?
_tired = _this select 0;

// Do they have friends with them?
_friends = if (count _this > 1) then {_this select 1} else {false};

// Find a spot around the tired person within 3m and create a carpet to sit on.
_loc = [(getPos _tired select 0) + (3 * sin(random(360))), (getPos _tired select 1) + (3 * cos(random(360))), 0];
_carpet = "Land_Carpet_EP1" createVehicle _loc;

// If they have friends, create a chair for their friend to sit on.
if (_friends) then {
	_loc = [(getPos _tired select 0) + (3 * sin(random(360))), (getPos _tired select 1) + (3 * cos(random(360))), 0];	
	_chair = "Land_Chair_EP1" createVehicle _loc;
};

Comments are closed.