Battlezone Lua Script Utility Functions

Document Revised 2018-04-15

Covers Battlezone up to version 1.5.2.27u1

Covers Battlezone 98 Redux versions 2.1+

This document describes the global script utility functions available for user-created Lua mission scripts. They offer the same functionality that the original designers used when creating the single-player campaign, along with new functionality back-ported from Battlezone II: Combat Commander or added to fill notable gaps.

Version numbers appearing in [square brackets] indicate the earliest version that supports the value or function. While a script could check the version number, it's faster and easier to check if the value or function is nil.

Globals

The Lua scripting system defines some global variables that can be of use to user scripts.

string GameVersion

Contains current build version (e.g. "1.5.2.27u1").

Battlezone 1.5 versions start with "1" and Battlezone 98 Redux versions start with "2".

integer Language [2.0+]

Contains the index of the current language.

  1. English
  2. French
  3. German
  4. Spanish
  5. Italian
  6. Portuguese
  7. Russian

string LanguageName [2.0+]

Contains the full name of the current language in all-caps:
"ENGLISH", "FRENCH", "GERMAN", "SPANISH", "ITALIAN", "PORTUGUESE", or "RUSSIAN"

string LanguageSuffix [2.0+]

Contains the two-letter language code of the current language:
"en", "fr", "de", "es", "it", "pt" or "ru"

string LastGameKey

Contains the most recently pressed game key (e.g. "Ctrl+Z")

Script Event Handlers

The Lua scripting system calls these script-defined functions when various script events occur. LuaMission looks up the functions by name so they can have different functions assigned to them at runtime.

Load ( ... )

Called when loading state from a save game file, allowing the script to restore its state.

Data values returned from Save will be passed as parameters to Load in the same order they were returned. Load supports nil, boolean, handle, integer, number, string, vector, and matrix data types. It does not support function, thread, or arbitrary userdata types.

The console window will print the loaded values in human-readable format.

... Save ()

Called when saving state to a save game file, allowing the script to preserve its state.

Any values returned by this function will be passed as parameters to Load when loading the save game file. Save supports nil, boolean, handle, integer, number, string, vector, and matrix data types. It does not support function, thread, or arbitrary userdata types.

The console window will print the saved values in human-readable format.

Start ()

Called when the mission starts for the first time.

Use this function to perform any one-time script initialization.

GameKey ( string key )

Called any time a game key is pressed.

Key is a string that consisting of zero or more modifiers (Ctrl, Shift, Alt) and a base key.

The base key for keys corresponding to a printable ASCII character is the upper-case version of that character.

The base key for other keys is the label on the keycap (e.g. PageUp, PageDown, Home, End, Backspace, and so forth).

Update ( number timestep )

Called once per frame after updating the network system and before simulating game objects.

This function performs most of the mission script's game logic.

CreateObject ( handle h )

Called after any game object is created.

Handle is the game object that was created.

This function will get a lot of traffic so it should not do too much work.

AddObject ( handle h )

Called when a game object gets added to the mission

Handle is the game object that was added

This function is normally called for "important" game objects, and excludes things like Scrap pieces.

DeleteObject ( handle h )

Called before a game object is deleted.

Handle is the game object to be deleted.

This function will get a lot of traffic so it should not do too much work.

CreatePlayer ( integer id, string name, integer team )

Called when a player joins the session.

Players that join before the host launches trigger CreatePlayer just before the first Update.

Players that join joining after the host launches trigger CreatePlayer on entering the pre-game lobby.

This function gets called for the local player.

AddPlayer ( integer id, string name, integer team )

Called when a player starts sending state updates.

This indicates that a player has finished loaded and started simulating.

This function is not called for the local player.

DeletePlayer ( integer id, string name, integer team )

Called when a player leaves the session.

boolean Receive ( integer from, string type, ... )

Called when a script-defined message arrives.

This function should return true if it handled the message and false, nil, or none if it did not.

From is the network player id of the sender.

Type is an arbitrary one-character string indicating the script-defined message type.

Data values passed as parameters to Send will arrive as parameters to Receive in the same order they were sent. Receive supports nil, boolean, handle, integer, number, string, vector, and matrix data types. It does not support function, thread, or arbitrary userdata types.

boolean Command ( string command, string arguments )

Called for any in-game chat command that was not handled by the system, allowing script-defined commands.

This function should return true if it handled the command and false, nil, or none if it did not.

LuaMission breaks the command into

Command is the string immediately following the '/'. For example, the command for "/foo" is "foo".

Arguments arrive as a string parameter to Command. For example "/foo 1 2 3" would receive "1 2 3".

The Lua string library provides several functions that can split the string into separate items.

You can use string.match with captures if you have a specific argument list:

local foo, bar, baz = string.match(arguments, "(%g+) (%g+) (%g+)")

You can use string.gmatch, which returns an iterator, if you want to loop through arguments:

for arg in string.gmatch(arguments, "%g+") do ... end

Check the Lua patterns tutorial and patterns manual for more details.

Audio Messages

These functions control audio messages, 2D sounds typically used for radio messages, voiceovers, and narration.

Audio messages use the Voice Volume setting from the Audio Options menu.

RepeatAudioMessage ()

Repeat the last audio message.

message AudioMessage ( string filename )

Plays the given audio file, which must be an uncompressed RIFF WAVE (.WAV) file.

Returns an audio message handle.

boolean IsAudioMessageDone ( message msg )

Returns true if the audio message has stopped. Returns false otherwise.

StopAudioMessage ( message msg )

Stops the given audio message.

boolean IsAudioMessagePlaying ()

Returns true if any audio message is playing. Returns false otherwise.

Sound Effects

These functions control sound effects, either positional 3D sounds attached to objects or global 2D sounds.

Sound effects use the Effects Volume setting from the Audio Options menu.

StartSound ( string filename, [ Handle h ], [ integer priority ], [ boolean loop ], [ integer volume ], [ integer rate ] )

Plays the given audio file, which must be an uncompressed RIFF WAVE (.WAV) file.

Specifying an object handle creates a positional 3D sound that follows the object as it moves and stops automatically when the object goes away. Otherwise, the sound plays as a global 2D sound.

Priority ranges from 0 to 100, with higher priorities taking precedence over lower priorities when there are not enough channels. The default priority is 50 if not specified.

Looping sounds will play forever until explicitly stopped with StopSound or the object to which it is attached goes away. Non-looping sounds will play once and stop. The default is non-looping if not specified.

Volume ranges from 0 to 100, with 0 being silent and 100 being maximum volume. The default volume is 100 if not specified.

Rate overrides the playback rate of the sound file, so a value of 22050 would cause a sound file recorded at 11025 Hz to play back twice as fast. The rate defaults to the file's native rate if not specified.

StopSound ( string filename, [ Handle h ] )

Stops the sound using the given filename and associated with the given object. Use a handle of none or nil to stop a global 2D sound.

Game Object

These functions create, manipulate, and query game objects (vehicles, buildings, people, powerups, and scrap) and return or take as a parameter a game object handle.

Object handles are always safe to use, even if the game object itself is missing or destroyed.

handle GetHandle ( string label )

Returns the handle of the game object with the given label. Returns nil if none exists.

handle BuildObject ( string odfname, integer teamnum, handle h )

Creates a game object with the given odf name and team number at the location of a game object.

Returns the handle of the created object if it created one. Returns nil if it failed.

handle BuildObject ( string odfname, integer teamnum, string path, [ integer point ] )

Creates a game object with the given odf name and team number at a point on the named path. It uses the start of the path if no point is given.

Returns the handle of the created object if it created one. Returns nil if it failed.

handle BuildObject ( string odfname, integer teamnum, vector position )

Creates a game object with the given odf name and team number at the given position vector.

Returns the handle of the created object if it created one. Returns nil if it failed.

handle BuildObject ( string odfname, integer teamnum, matrix transform )

Creates a game object with the given odf name and team number with the given transform matrix.

Returns the handle of the created object if it created one. Returns nil if it failed.

RemoveObject ( handle h )

Removes the game object with the given handle.

boolean IsOdf ( handle h, string odfname )

Returns true if the game object's odf name matches the given odf name. Returns false otherwise.

string GetOdf ( handle h )

Returns the odf name of the game object. Returns nil if none exists.

string GetBase ( handle h )

Returns the base config of the game object which determines what VDF/SDF model it uses. Returns nil if none exists.

string GetLabel ( handle h )

Returns the label of the game object (e.g. "avtank0_wingman"). Returns nil if none exists.

SetLabel ( Handle h, string label )

Set the label of the game object (e.g. "tank1").

Note: this function was misspelled as SettLabel in 1.5. It can be renamed compatibly with a short snippet of code at the top of the mission script:

SetLabel = SetLabel or SettLabel

string GetClassSig ( handle h )

Returns the four-character class signature of the game object (e.g. "WING"). Returns nil if none exists.

string GetClassLabel ( handle h )

Returns the class label of the game object (e.g. "wingman"). Returns nil if none exists.

integer GetClassId ( handle h )

Returns the numeric class identifier of the game object. Returns nil if none exists.

Looking up the class id number in the ClassId table will convert it to a string. Looking up the class id string in the ClassId table will convert it back to a number.

ClassId

This is a global table that converts between class identifier numbers and class identifier names. For example, ClassId.SCRAP or ClassId["SCRAP"] returns the class identifier number (7) for the Scrap class; ClassId[7] returns the class identifier name ("SCRAP") for class identifier number 7. For maintainability, always use this table instead of raw class identifier numbers.

Available class identifiers: NONE, HELICOPTER, STRUCTURE1, POWERUP, PERSON, SIGN, VEHICLE, SCRAP, BRIDGE, FLOOR, STRUCTURE2, SCROUNGE, SPINNER, HEADLIGHT_MASK, EYEPOINT, COM, WEAPON, ORDNANCE, EXPLOSION, CHUNK, SORT_OBJECT, NONCOLLIDABLE, VEHICLE_GEOMETRY, STRUCTURE_GEOMETRY, WEAPON_GEOMETRY, ORDNANCE_GEOMETRY, TURRET_GEOMETRY, ROTOR_GEOMETRY, NACELLE_GEOMETRY, FIN_GEOMETRY, COCKPIT_GEOMETRY, WEAPON_HARDPOINT, CANNON_HARDPOINT, ROCKET_HARDPOINT, MORTAR_HARDPOINT, SPECIAL_HARDPOINT, FLAME_EMITTER, SMOKE_EMITTER, DUST_EMITTER, PARKING_LOT

string GetNation ( handle h )

Returns the one-letter nation code of the game object (e.g. "a" for American, "b" for Black Dog, "c" for Chinese, and "s" for Soviet).

The nation code is usually but not always the same as the first letter of the odf name. The ODF file can override the nation in the [GameObjectClass] section, and player.odf is a hard-coded exception that uses "a" instead of "p".

boolean IsValid ( handle h )

Returns true if the game object exists. Returns false otherwise.

boolean IsAlive ( handle h )

Returns true if the game object exists and (if the object is a vehicle) controlled. Returns false otherwise.

boolean IsAliveAndPilot ( handle h )

Returns true if the game object exists and (if the object is a vehicle) controlled and piloted. Returns false otherwise.

boolean IsCraft ( handle h )

Returns true if the game object exists and is a vehicle. Returns false otherwise.

boolean IsBuilding ( handle h )

Returns true if the game object exists and is a building. Returns false otherwise.

boolean IsPerson ( handle h )

Returns true if the game object exists and is a person. Returns false otherwise.

boolean IsDamaged ( handle h [, float threshold] )

Returns true if the game object exists and has less health than the threshold. Returns false otherwise.

boolean IsRecycledByTeam ( handle h, integer team ) [2.1+]

Returns true if the game object was recycled by a Construction Rig on the given team.

Team Number

These functions get and set team number. Team 0 is the neutral or environment team.

integer GetTeamNum ( handle h )

Returns the game object's team number.

SetTeamNum ( handle h, integer team )

Sets the game object's team number.

teamnum GetPerceivedTeam ( handle h, teamnum t )

Returns the game object's perceived team number (as opposed to its real team number).

The perceived team will differ from the real team when a player enters an empty enemy vehicle without being seen until they attack something.

SetPerceivedTeam ( handle h, teamnum t )

Set the game object's perceived team number (as opposed to its real team number).

Units on the game object's perceived team will treat it as friendly until it "blows its cover" by attacking, at which point it will revert to its real team.

Units on the game object's real team will treat it as friendly regardless of its perceived team.

Target

These function get and set a unit's target.

SetUserTarget ( handle t )

Sets the local player's target.

handle GetUserTarget ()

Returns the local player's target. Returns nil if it has none.

SetTarget ( handle h, handle t )

Sets the game object's target.

handle GetTarget ( handle h )

Returns the game object's target. Returns nil if it has none.

Owner

These functions get and set owner. The default owner for a game object is the game object that created it.

SetOwner ( handle h, handle o )

Sets the game object's owner.

handle GetOwner ( handle h )

Returns the game object's owner. Returns nil if it has none.

Pilot Class

These functions get and set vehicle pilot class.

SetPilotClass ( handle h, string odfname )

Sets the vehicle's pilot class to the given odf name. This does nothing useful for non-vehicle game objects. An odf name of nil resets the vehicle to the default assignment based on nation.

string GetPilotClass ( handle h )

Returns the odf name of the vehicle's pilot class. Returns nil if none exists.

Position and Orientation

These functions get and set position and orientation.

SetPosition ( handle h, string path, [ integer point ] )

Teleports the game object to a point on the named path. It uses the start of the path if no point is given.

SetPosition ( handle h, vector position )

Teleports the game object to the position vector.

SetPosition ( handle h, matrix transform )

Teleports the game object to the position of the transform matrix.

vector GetPosition ( handle h )

Returns the game object's position vector. Returns nil if none exists.

vector GetPosition ( string path, [ integer point ] )

Returns the path point's position vector. Returns nil if none exists.

vector GetFront ( handle h )

Returns the game object's front vector. Returns nil if none exists.

SetTransform ( handle h, matrix transform )

Teleports the game object to the given transform matrix.

matrix GetTransform ( handle h )

Returns the game object's transform matrix. Returns nil if none exists.

Linear Velocity

These functions get and set linear velocity.

vector GetVelocity ( handle h )

Returns the game object's linear velocity vector. Returns nil if none exists.

SetVelocity ( handle h, vector velocity )

Sets the game object's angular velocity vector.

Angular Velocity

These functions get and set angular velocity.

vector GetOmega ( handle h )

Returns the game object's angular velocity vector. Returns nil if none exists.

SetOmega ( handle h, vector omega )

Sets the game object's angular velocity vector.

Position Helpers

These functions help generate position values close to a center point.

vector GetCircularPos ( vector center, [ number radius ], [ number angle ] )

Returns a ground position offset from the center by the radius in a direction controlled by the angle.

If no radius is given, it uses a default radius of zero.

If no angle is given, it uses a default angle of zero.

An angle of zero is +X (due east), pi * 0.5 is +Z (due north), pi is -X (due west), and pi * 1.5 is -Z (due south).

vector GetPositionNear ( vector center, [ number minradius ], [ number maxradius ] )

Returns a ground position in a ring around the center between minradius and maxradius with roughly the same terrain height as the terrain height at the center.

This is good for scattering spawn positions around a point while excluding positions that are too high or too low.

If no radius is given, it uses the default radius of zero.

Shot

These functions query a game object for information about ordnance hits.

handle GetWhoShotMe ( handle h )

Returns who scored the most recent hit on the game object. Returns nil if none exists.

float GetLastEnemyShot ( handle h )

Returns the last time an enemy shot the game object.

float GetLastFriendShot ( handle h )

Returns the last time a friend shot the game object.

Alliances

These functions control and query alliances between teams.

The team manager assigns each player a separate team number, starting with 1 and going as high as 15. Team 0 is the neutral "environment" team.

Unless specifically overridden, every team is friendly with itself, neutral with team 0, and hostile to everyone else.

DefaultAllies ()

Sets team alliances back to default.

LockAllies ( boolean lock )

Sets whether team alliances are locked. Locking alliances prevents players from allying or un-allying, preserving alliances set up by the mission script.

Ally ( integer team1, integer team2 )

Makes the two teams allies of each other.

This function affects both teams so Ally(1, 2) and Ally(2, 1) produces the identical results, unlike the "half-allied" state created by the "ally" game key.

UnAlly ( integer team1, integer team2 )

Makes the two teams enemies of each other.

This function affects both teams so UnAlly(1, 2) and UnAlly(2, 1) produces the identical results, unlike the "half-enemy" state created by the "unally" game key.

boolean IsTeamAllied ( integer team1, integer team2 )

Returns true if team1 considers team2 an ally. Returns false otherwise.

Due to the possibility of player-initiated "half-alliances", IsTeamAllied(team1, team2) might not return the same result as IsTeamAllied(team2, team1).

boolean IsAlly ( handle me, handle him )

Returns true if game object "me" considers game object "him" an ally. Returns false otherwise.

Due to the possibility of player-initiated "half-alliances", IsAlly(me, him) might not return the same result as IsAlly(him, me).

Objective Marker

These functions control objective markers.

Objectives are visible to all teams from any distance and from any direction, with an arrow pointing to off-screen objectives. There is currently no way to make team-specific objectives.

SetObjectiveOn ( handle h )

Sets the game object as an objective to all teams.

SetObjectiveOff ( handle h )

Sets the game object back to normal.

string GetObjectiveName ( handle h )

Gets the game object's visible name.

SetObjectiveName ( handle h, string name )

Sets the game object's visible name.

SetName ( handle h, string name ) [2.1+]

Sets the game object's visible name. This function is effectively an alias for SetObjectiveName.

Distance

These functions measure and return the distance between a game object and a reference point.

number GetDistance ( handle h1, handle h2 )

Returns the distance in meters between the two game objects.

number GetDistance ( handle h1, string path, [ integer point ] )

Returns the distance in meters between the game object and a point on the path. It uses the start of the path if no point is given.

number GetDistance ( handle h1, vector position )

Returns the distance in meters between the game object and a position vector.

number GetDistance ( handle h1, matrix transform )

Returns the distance in meters between the game object and the position of a transform matrix.

boolean IsWithin ( handle h1, handle h2, number dist )

Returns true if the units are closer than the given distance of each other. Returns false otherwise.

(This function is equivalent to GetDistance (h1, h2) < d)

bool IsTouching( handle h1, handle h2, [ number tolerance ] ) [2.1+]

Returns true if the bounding spheres of the two game objects are within the specified tolerance. The default tolerance is 1.3 meters if not specified.

Nearest

These functions find and return the game object of the requested type closest to a reference point.

handle GetNearestObject ( handle h )

Returns the game object closest to the given game object. Returns nil if none exists.

handle GetNearestObject ( string path, [ integer point ] )

Returns the game object closest to a point on the path. It uses the start of the path if no point is given. Returns nil if none exists.

handle GetNearestObject ( vector position )

Returns the game object closest to the position vector. Returns nil if none exists.

handle GetNearestObject ( matrix transform )

Returns the game object closest to the position of the transform matrix. Returns nil if none exists.

handle GetNearestVehicle ( handle h )

Returns the craft closest to the given game object. Returns nil if none exists.

handle GetNearestVehicle ( string path, [ integer point ] )

Returns the craft closest to a point on the path. It uses the start of the path if no point is given. Returns nil if none exists.

handle GetNearestVehicle ( vector position )

Returns the vehicle closest to the position vector. Returns nil if none exists.

handle GetNearestVehicle ( matrix transform )

Returns the vehicle closest to the position of the transform matrix. Returns nil if none exists.

handle GetNearestBuilding ( handle h )

Returns the building closest to the given game object. Returns nil if none exists.

handle GetNearestBuilding ( string path, [ integer point ] )

Returns the building closest to a point on the path. It uses the start of the path if no point is given. Returns nil if none exists.

handle GetNearestBuilding ( vector position )

Returns the building closest to the position vector. Returns nil if none exists.

handle GetNearestBuilding ( matrix transform )

Returns the building closest to the position of the transform matrix. Returns nil if none exists.

handle GetNearestEnemy ( handle h )

Returns the enemy closest to the given game object. Returns nil if none exists.

handle GetNearestEnemy ( string path, [ integer point ] )

Returns the enemy closest to a point on the path. It uses the start of the path if no point is given. Returns nil if none exists.

handle GetNearestEnemy ( vector position )

Returns the enemy closest to the position vector. Returns nil if none exists.

handle GetNearestEnemy ( matrix transform )

Returns the enemy closest to the position of the transform matrix. Returns nil if none exists.

handle GetNearestFriend ( handle h ) [2.0+]

Returns the friend closest to the given game object. Returns nil if none exists.

handle GetNearestFriend ( string path, [ integer point ] ) [2.0+]

Returns the friend closest to a point on the path. It uses the start of the path if no point is given. Returns nil if none exists.

handle GetNearestFriend ( vector position ) [2.0+]

Returns the friend closest to the position vector. Returns nil if none exists.

handle GetNearestFriend ( matrix transform ) [2.0+]

Returns the friend closest to the position of the transform matrix. Returns nil if none exists.

handle GetNearestUnitOnTeam ( handle h, int team ) [2.1+]

Returns the craft or person on the given team closest to the given game object. Returns nil if none exists.

handle GetNearestUnitOnTeam ( string path, [ integer point ], int team ) [2.1+]

Returns the craft or person on the given team closest to a point on the path. It uses the start of the path if no point is given. Returns nil if none exists.

handle GetNearestUnitOnTeam ( vector position, int team ) [2.1+]

Returns the craft or person on the given team closest to the position of the transform matrix. Returns nil if none exists.

handle GetNearestUnitOnTeam ( matrix transform, int team ) [2.1+]

Returns the craft or person on the given team closest to the position vector. Returns nil if none exists.

integer CountUnitsNearObject ( handle h, number dist, integer team, string odfname )

Returns how many objects with the given team and odf name are closer than the given distance.

Iterators

These functions return iterator functions for use with Lua's "for <variable> in <expression> do ... end" form. For example: "for h in AllCraft() do print(h, GetLabel(h)) end" will print the game object handle and label of every craft in the world.

iterator ObjectsInRange ( number dist, handle h )

Enumerates game objects within the given distance of the game object.

iterator ObjectsInRange ( number dist, name path, [ integer point ] )

Enumerates game objects within the given distance of the path point. It uses the start of the path if no point is given.

iterator ObjectsInRange ( number dist, vector position )

Enumerates game objects within the given distance of the position vector.

iterator ObjectsInRange ( number dist, matrix transform )

Enumerates game objects within the given distance of the transform matrix.

iterator AllObjects ()

Enumerates all game objects.

Use this function sparingly at runtime since it enumerates all game objects, including every last piece of scrap. If you're specifically looking for craft, use AllCraft() instead.

iterator AllCraft ()

Enumerates all craft.

iterator SelectedObjects ()

Enumerates all game objects currently selected by the local player.

iterator ObjectiveObjects ()

Enumerates all game objects marked as objectives.

Scrap Management

These functions remove scrap, either to reduce the global game object count or to remove clutter around a location.

GetRidOfSomeScrap ( [ integer limit ] )

While the global scrap count is above the limit, remove the oldest scrap piece. It no limit is given, it uses the default limit of 300.

ClearScrapAround ( number distance, handle h )

Clear all scrap within the given distance of a game object.

ClearScrapAround ( number distance, string path, [ integer point ] )

Clear all scrap within the given distance of a point on the path. It uses the start of the path if no point is given.

ClearScrapAround ( number distance, vector position )

Clear all scrap within the given distance of a position vector.

ClearScrapAround ( number distance, matrix transform )

Clear all scrap within the given distance of the position of a transform matrix.

Team Slots

These functions look up game objects in team slots.

TeamSlot

This is a global table that converts between team slot numbers and team slot names. For example, TeamSlot.PLAYER or TeamSlot["PLAYER"] returns the team slot (0) for the player; TeamSlot[0] returns the team slot name ("PLAYER") for team slot 0. For maintainability, always use this table instead of raw team slot numbers.

Available slots: UNDEFINED, PLAYER, RECYCLER, FACTORY, ARMORY, CONSTRUCT, MIN_OFFENSE, MAX_OFFENSE, MIN_DEFENSE, MAX_DEFENSE, MIN_UTILITY, MAX_UTILITY, MIN_BEACON, MAX_BEACON, MIN_POWER, MAX_POWER, MIN_COMM, MAX_COMM, MIN_REPAIR, MAX_REPAIR, MIN_SUPPLY, MAX_SUPPLY, MIN_SILO, MAX_SILO, MIN_BARRACKS, MAX_BARRACKS, MIN_GUNTOWER, MAX_GUNTOWER.

Slots starting with MIN_ and MAX_ represent the lower and upper bound of a range of slots.

handle GetTeamSlot ( integer slot, [ integer team ] )

Get the game object in the specified team slot.

It uses the local player team if no team is given.

handle GetPlayerHandle ( [ integer team ])

Returns the game object controlled by the player on the given team. Returns nil if none exists.

It uses the local player team if no team is given.

handle GetRecyclerHandle ( [ integer team ] )

Returns the Recycler on the given team. Returns nil if none exists.

It uses the local player team if no team is given.

handle GetFactoryHandle ( [ integer team ] )

Returns the Factory on the given team. Returns nil if none exists.

It uses the local player team if no team is given.

handle GetArmoryHandle ( [ integer team ] )

Returns the Armory on the given team. Returns nil if none exists.

It uses the local player team if no team is given.

handle GetConstructorHandle ( [ integer team ] )

Returns the Constructor on the given team. Returns nil if none exists.

It uses the local player team if no team is given.

Team Pilots

These functions get and set pilot counts for a team.

integer AddPilot ( integer team, integer count )

Adds pilots to the team's pilot count, clamped between zero and maximum count.

Returns the new pilot count.

integer SetPilot ( integer team, integer count )

Sets the team's pilot count, clamped between zero and maximum count.

Returns the new pilot count.

integer GetPilot ( integer team )

Returns the team's pilot count.

integer AddMaxPilot ( integer team, integer count )

Adds pilots to the team's maximum pilot count.

Returns the new pilot count.

integer SetMaxPilot ( integer team, integer count )

Sets the team's maximum pilot count.

Returns the new pilot count.

integer GetMaxPilot ( integer team )

Returns the team's maximum pilot count.

Team Scrap

These functions get and set scrap values for a team.

integer AddScrap ( integer team, integer count )

Adds to the team's scrap count, clamped between zero and maximum count.

Returns the new scrap count.

integer SetScrap ( integer team, integer count )

Sets the team's scrap count, clamped between zero and maximum count.

Returns the new scrap count.

integer GetScrap ( integer team )

Returns the team's scrap count.

integer AddMaxScrap ( integer team, integer count )

Adds to the team's maximum scrap count.

Returns the new maximum scrap count.

integer SetMaxScrap ( integer team, integer count )

Sets the team's maximum scrap count.

Returns the new maximum scrap count.

integer GetMaxScrap ( integer team )

Returns the team's maximum scrap count.

Deploy

These functions control deployable craft (such as Turret Tanks or Producer units).

boolean IsDeployed ( handle h )

Returns true if the game object is a deployed craft. Returns false otherwise.

Deploy ( handle h )

Tells the game object to deploy.

Selection

These functions access selection state (i.e. whether the player has selected a game object)

boolean IsSelected ( handle h )

Returns true if the game object is selected. Returns false otherwise.

Mission-Critical [2.0+]

The "mission critical" property indicates that a game object is vital to the success of the mission and disables the "Pick Me Up" and "Recycle" commands that (eventually) cause IsAlive() to report false.

boolean IsCritical ( handle h ) [2.0+]

Returns true if the game object is marked as mission-critical. Returns false otherwise.

SetCritical ( handle h , [ bool critical ] ) [2.0+]

Sets the game object's mission-critical status.

If critical is true or not specified, the object is marked as mission-critical. Otherwise, the object is marked as not mission critical.

Weapon

These functions access unit weapons and damage.

SetWeaponMask ( handle h, integer mask )

Sets what weapons the unit's AI process will use.

To calculate the mask value, add up the values of the weapon hardpoint slots you want to enable.

weaponHard1: 1 weaponHard2: 2 weaponHard3: 4 weaponHard4: 8 weaponHard5: 16

GiveWeapon ( handle h, [ string weaponname ], [ integer slot ] )

Gives the game object the named weapon in the given slot. If no slot is given, it chooses a slot based on hardpoint type and weapon priority like a weapon powerup would. If the weapon name is empty, nil, or blank and a slot is given, it removes the weapon in that slot.

Returns true if it succeeded. Returns false otherwise.

string GetWeaponClass ( handle h, integer slot )

Returns the odf name of the weapon in the given slot on the game object. Returns nil if the game object does not exist or the slot is empty.

For example, an "avtank" game object would return "gatstab" for index 0 and "gminigun" for index 1.

FireAt ( handle me, handle him )

Tells the game object to fire at the given target.

Damage ( handle h, number amount )

Applies damage to the game object.

Time

These function report various global time values.

number GetTime ()

Returns the elapsed time in seconds since the start of the mission.

number GetTimeStep ()

Returns the simulation time step in seconds.

number GetTimeNow ()

Returns the current system time in milliseconds. This is mostly useful for performance profiling.

Mission

These functions control general mission properties like strategic AI and mission flow

SetAIControl ( integer team, [ boolean control ] )

Enables (or disables) strategic AI control for a given team. As of version 1.5.2.7, mission scripts must enable AI control for any team that intends to use an AIP.

IMPORTANT SAFETY TIP: only call this function from the "root" of the Lua mission script! The strategic AI gets set up shortly afterward and attempting to use SetAIControl later will crash the game.

boolean GetAIControl ( integer team )

Returns true if a given team is AI controlled. Returns false otherwise.

Unlike SetAIControl, this function may be called at any time.

string GetAIP ( [ integer team ] )

Returns the current AIP for the team. It uses team 2 if no team number is given.

SetAIP ( string aipname, [ integer team ] )

Switches the team's AI plan. It uses team 2 if no team number is given.

FailMission ( number time, [ string filename ] )

Fails the mission after the given time elapses. If supplied with a filename (usually a .des), it sets the failure message to text from that file.

SucceedMission ( number time, [ string filename ] )

Succeeds the mission after the given time elapses. If supplied with a filename (usually a .des), it sets the success message to text from that file.

Objective Messages

These functions control the objective panel visible at the right of the screen.

ClearObjectives ()

Clears all objective messages.

AddObjective ( string name, [ string color ], [ number duration ], [ string text ] )

Adds an objective message with the given name and properties.

The message defaults to white if no color is given. The color may be "black", "dkgrey", "grey", "white", "blue", "dkblue", "green", "dkgreen", "yellow", "dkyellow", "red", or "dkred"; the value is case-insensitive.

The message lasts 8 seconds if no duration is given.

The message text defaults to the contents of of the file with the specified name (usually an .otf).

Script-supplied message text is only available in version 2.0.121.1 or higher.

UpdateObjective ( string name, [ string color ], [ number duration ], [ string text ] )

Updates the objective message with the given name. If no objective exists with that name, it does nothing.

The message defaults to white if no color is given. The color may be "black", "dkgrey", "grey", "white", "blue", "dkblue", "green", "dkgreen", "yellow", "dkyellow", "red", or "dkred"; the value is case-insensitive.

The message lasts 8 seconds if no duration is given.

The message text will keep its previous value if no text is given.

Script-supplied message text is only available in version 2.0.121.1 or higher.

RemoveObjective ( string name )

Removes the objective message with the given file name. Messages after the removed message will be moved up to fill the vacancy. If no objective exists with that file name, it does nothing.

Cockpit Timer

These functions control the large timer at the top of the screen.

StartCockpitTimer ( integer time, [ integer warn ], [ integer alert ] )

Starts the cockpit timer counting down from the given time. If a warn time is given, the timer will turn yellow when it reaches that value. If an alert time is given, the timer will turn red when it reaches that value. All time values are in seconds.

The start time can be up to 35999, which will appear on-screen as 9:59:59. If the remaining time is an hour or less, the timer will show only minutes and seconds.

StartCockpitTimerUp ( integer time, [ integer warn ], [ integer alert ] )

Starts the cockpit timer counting up from the given time. If a warn time is given, the timer will turn yellow when it reaches that value. If an alert time is given, the timer will turn red when it reaches that value. All time values are in seconds.

The on-screen timer will always show hours, minutes, and seconds The hours digit will malfunction after 10 hours.

StopCockpitTimer ()

Stops the cockpit timer.

HideCockpitTimer ()

Hides the cockpit timer.

integer GetCockpitTimer ()

Returns the current time in seconds on the cockpit timer.

Earthquake

These functions control the global earthquake effect.

StartEarthquake ( number magnitude )

Starts a global earthquake effect.

UpdateEarthQuake ( number magnitude )

Changes the magnitude of an existing earthquake effect.

Important: note the inconsistent capitalization, which matches the internal C++ script utility functions.

StopEarthquake ()

Stops the global earthquake effect.

Path Type

These functions get and set the looping type of a path.

Looking up the path type number in the PathType table will convert it to a string. Looking up the path type string in the PathType table will convert it to a number.

SetPathType ( string path, integer type ) [2.0+]

Changes the named path to the given path type.

integer GetPathType ( string path ) [2.0+]

Returns the type of the named path.

SetPathOneWay ( string path )

Changes the named path to one-way. Once a unit reaches the end of the path, it will stop.

SetPathRoundTrip ( string path )

Changes the named path to round-trip. Once a unit reaches the end of the path, it will follow the path backwards to the start and begin again.

SetPathLoop ( string path )

Changes the named path to looping. Once a unit reaches the end of the path, it will continue along to the start and begin again.

Path Points [2.0+]

integer GetPathPointCount( string path ) [2.0+]

Returns the number of points in the named path, or 0 if the path does not exist.

Path Area [2.0+]

These functions treat a path as the boundary of a closed polygonal area.

integer GetWindingNumber( string path, handle h ) [2.0+]

Returns how many times the named path loops around the given game object.

Each full counterclockwise loop adds one and each full clockwise loop subtracts one.

integer GetWindingNumber( string path, vector position ) [2.0+]

Returns how many times the named path loops around the given position.

Each full counterclockwise loop adds one and each full clockwise loop subtracts one.

integer GetWindingNumber( string path, matrix transform ) [2.0+]

Returns how many times the named path loops around the position of the given transform.

Each full counterclockwise loop adds one and each full clockwise loop subtracts one.

boolean IsInsideArea( string path, handle h ) [2.0+]

Returns true if the given game object is inside the area bounded by the named path. Returns false otherwise.

This function is equivalent to

GetWindingNumber( path, h ) ~= 0

boolean IsInsideArea( string path, vector position ) [2.0+]

Returns true if the given position is inside the area bounded by the named path. Returns false otherwise.

This function is equivalent to

GetWindingNumber( path, position ) ~= 0

boolean IsInsideArea( string path, matrix transform ) [2.0+]

Returns true if the position of the given transform is inside the area bounded by the named path. Returns false otherwise.

This function is equivalent to

GetWindingNumber( path, transform ) ~= 0

Unit Commands

These functions send commands to units or query their command state.

AiCommand

This is a global table that converts between command numbers and command names. For example, AiCommand.GO or AiCommand["GO"] returns the command number (3) for the "go" command; AiCommand[3] returns the command name ("GO") for command number 3. For maintainability, always use this table instead of raw command numbers.

Available commands: NONE, SELECT, STOP, GO, ATTACK, FOLLOW, FORMATION, PICKUP, DROPOFF, NO_DROPOFF, GET_REPAIR, GET_RELOAD, GET_WEAPON, GET_CAMERA, GET_BOMB, DEFEND, GO_TO_GEYSER, RESCUE, RECYCLE, SCAVENGE, HUNT, BUILD, PATROL, STAGE, SEND, GET_IN, LAY_MINES, CLOAK [2.1+], DECLOAK [2.1+].

boolean CanCommand ( handle me )

Returns true if the game object can be commanded. Returns false otherwise.

boolean CanBuild ( handle me )

Returns true if the game object is a producer that can build at the moment. Returns false otherwise.

boolean IsBusy ( handle me )

Returns true if the game object is a producer and currently busy. Returns false otherwise.

integer GetCurrentCommand ( handle me )

Returns the current command for the game object. Looking up the command number in the AiCommand table will convert it to a string. Looking up the command string in the AiCommand table will convert it back to a number.

handle GetCurrentWho ( handle me )

Returns the target of the current command for the game object. Returns nil if it has none.

integer GetIndependence( handle me )

Gets the independence of a unit.

SetIndependence ( handle me, integer independence)

Sets the independence of a unit. 1 (the default) lets the unit take initiative (e.g. attack nearby enemies), while 0 prevents that.

SetCommand ( handle me, integer command, [ integer priority ], [ handle who ], [ matrix|vector|string where ], [ number when ], [ string param ] )

Commands the unit using the given parameters. Be careful with this since not all commands work with all units and some have strict requirements on their parameters.

"Command" is the command to issue, normally chosen from the global AiCommand table (e.g. AiCommand.GO).

"Priority" is the command priority; a value of 0 leaves the unit commandable by the player while the default value of 1 makes it uncommandable.

"Who" is an optional target game object.

"Where" is an optional destination, and can be a matrix (transform), a vector (position), or a string (path name).

"When" is an optional absolute time value only used by command AiCommand.STAGE.

"Param" is an optional odf name only used by command AiCommand.BUILD.

Attack ( handle me, handle him , [ integer priority ] )

Commands the unit to attack the given target.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Goto ( handle me, string path , [ integer priority ] )

Commands the unit to go to the named path.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Goto ( handle me, handle him , [ integer priority ] )

Commands the unit to go to the given target

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Goto ( handle me, vector position , [ integer priority ] )

Commands the unit to go to the given position vector

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Goto ( handle me, matrix transform , [ integer priority ] )

Commands the unit to go to the position of the given transform matrix

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Mine ( handle me, string path , [ integer priority ] )

Commands the unit to lay mines at the named path; only minelayer units support this.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Mine ( handle me, vector position, [ integer priority ] )

Commands the unit to lay mines at the given position vector

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Mine ( handle me, matrix transform, [ integer priority ] )

Commands the unit to lay mines at the position of the transform matrix

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Follow ( handle me, handle him, [ integer priority ] )

Commands the unit to follow the given target.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

boolean IsFollowing(handle me, handle him) [2.1+]

Returns true if the unit is currently following the given target.

Defend ( handle me, [ integer priority ] )

Commands the unit to defend its current location.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Defend2 ( handle me, handle him, [ integer priority ] )

Commands the unit to defend the given target.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Stop ( handle me, [ integer priority ] )

Commands the unit to stop at its current location.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Patrol ( handle me, string path, [ integer priority ] )

Commands the unit to patrol along the named path. This is equivalent to Goto with an independence of 1.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Retreat ( handle me, string path, [ integer priority ] )

Commands the unit to retreat to the named path. This is equivalent to Goto with an independence of 0.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Retreat ( handle me, handle him , [ integer priority ] )

Commands the unit to retreat to the given target. This is equivalent to Goto with an independence of 0.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

GetIn ( handle me, handle him, [ integer priority ] )

Commands the pilot to get into the target vehicle.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Pickup ( handle me, handle him, [ integer priority ] )

Commands the unit to pick up the target object. Deployed units pack up (ignoring the target), scavengers pick up scrap, and tugs pick up and carry objects.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Dropoff ( handle me, string path, [ integer priority ] )

Commands the unit to drop off at the named path. Tugs drop off their cargo and Construction Rigs build the selected item at the location using their current facing.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Dropoff ( handle me, vector position, [ integer priority ] )

Commands the unit to drop off at the position vector. Tugs drop off their cargo and Construction Rigs build the selected item at the location using their current facing.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Dropoff ( handle me, matrix transform, [ integer priority ] )

Commands the unit to drop off at the position of the transform matrix. Tugs drop off their cargo and Construction Rigs build the selected item with the facing of the transform matrix.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Build ( handle me, string odfname, [ integer priority ] )

Commands a producer to build the given odf name. The Armory and Construction Rig need an additional Dropoff to give them a location to build but first need at least one simulation update to process the Build.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

BuildAt ( handle me, string odfname, handle target, [ integer priority ] )

Commands a producer to build the given odf name at the location of the target game object. A Construction Rig will build at the location and an Armory will launch the item to the location. Other producers will ignore the location.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

BuildAt ( handle me, string odfname, string path, [ integer priority ] )

Commands a producer to build the given odf name at the named path. A Construction Rig will build at the location and an Armory will launch the item to the location. Other producers will ignore the location.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

BuildAt ( handle me, string odfname, vector position, [ integer priority ] )

Commands a producer to build the given odf name at the position vector. A Construction Rig will build at the location with their current facing and an Armory will launch the item to the location. Other producers will ignore the location.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

BuildAt ( handle me, string odfname, matrix transform, [ integer priority ] )

Commands a producer to build the given odf name at the transform matrix. A Construction Rig will build at the location with the facing of the transform and an Armory will launch the item to the location. Other producers will ignore the location.

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Formation ( handle me, handle him, [ integer priority ] ) [2.1+]

Commands the unit to follow the given target closely. This function is equivalent to SetCommand(me, AiCommand.FORMATION, priority, him).

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Hunt ( handle me, [ integer priority ] ) [2.1+]

Commands the unit to hunt for targets autonomously. This function is equivalent to SetCommand(me, AiCommand.HUNT, priority).

Priority 0 leaves the unit commandable while the default priority 1 makes it uncommandable.

Tug Cargo

These functions query Tug and Cargo.

boolean HasCargo ( handle tug )

Returns true if the unit is a tug carrying cargo.

handle GetCargo ( handle tug ) [2.1+]

Returns the handle of the cargo if the unit is a tug carrying cargo. Returns nil otherwise.

handle GetTug ( handle cargo )

Returns the handle of the tug carrying the object. Returns nil if not carried.

Pilot Actions

These functions control the pilot of a vehicle.

EjectPilot ( handle h )

Commands the vehicle's pilot to eject.

HopOut ( handle h )

Commands the vehicle's pilot to hop out.

KillPilot ( handle h )

Kills the vehicle's pilot as if sniped.

RemovePilot ( handle h )

Removes the vehicle's pilot cleanly.

handle HoppedOutOf ( handle h )

Returns the vehicle that the pilot most recently hopped out of.

Health Values

These functions get and set health values on a game object.

number GetHealth ( handle h )

Returns the fractional health of the game object between 0 and 1.

number GetCurHealth ( handle h )

Returns the current health value of the game object.

number GetMaxHealth ( handle h )

Returns the maximum health value of the game object.

SetCurHealth ( handle h, number health )

Sets the current health of the game object.

SetMaxHealth ( handle h, number health )

Sets the maximum health of the game object.

AddHealth ( handle h, number health )

Adds to the current health of the game object.

GiveMaxHealth ( handle h ) [2.1+]

Sets the unit's current health to maximum.

Ammo Values

These functions get and set ammo values on a game object.

number GetAmmo ( handle h )

Returns the fractional ammo of the game object between 0 and 1.

number GetCurAmmo ( handle h )

Returns the current ammo value of the game object.

number GetMaxAmmo ( handle h )

Returns the maximum ammo value of the game object.

SetCurAmmo ( handle h, number ammo )

Sets the current ammo of the game object.

SetMaxAmmo ( handle h, number ammo )

Sets the maximum ammo of the game object.

AddAmmo ( handle h, number ammo )

Adds to the current ammo of the game object.

GiveMaxAmmo ( handle h ) [2.1+]

Sets the unit's current ammo to maximum.

Cinematic Camera

These functions control the cinematic camera for in-engine cut scenes (or "cineractives" as the Interstate '76 team at Activision called them).

boolean CameraReady ()

Starts the cinematic camera and disables normal input.

Always returns true.

boolean CameraPath ( string path, integer height, integer speed, handle target )

Moves a cinematic camera along a path at a given height and speed while looking at a target game object.

Returns true when the camera arrives at its destination. Returns false otherwise.

boolean CameraPathDir ( string path, integer height, integer speed )

Moves a cinematic camera long a path at a given height and speed while looking along the path direction.

Returns true when the camera arrives at its destination. Returns false otherwise.

boolean PanDone ()

Returns true when the camera arrives at its destination. Returns false otherwise.

boolean CameraObject ( handle base, integer right, integer up, integer forward, handle target )

Offsets a cinematic camera from a base game object while looking at a target game object. The right, up, and forward offsets are in centimeters.

Returns true if the base or handle game object does not exist. Returns false otherwise.

boolean CameraFinish ()

Finishes the cinematic camera and enables normal input.

Always returns true.

boolean CameraCancelled ()

Returns true if the player canceled the cinematic. Returns false otherwise.

Info Display

boolean IsInfo ( string odfname )

Returns true if the game object inspected by the info display matches the given odf name.

Network

LuaMission currently has limited network support, but can detect if the mission is being run in multiplayer and if the local machine is hosting.

boolean IsNetGame ()

Returns true if the game is a network game. Returns false otherwise.

boolean IsHosting ()

Returns true if the local machine is hosting a network game. Returns false otherwise.

SetLocal ( handle h )

Sets the game object as local to the machine the script is running on, transferring ownership from its original owner if it was remote. Important safety tip: only call this on one machine at a time!

boolean IsLocal ()

Returns true if the game is local to the machine the script is running on. Returns false otherwise.

boolean IsRemote ()

Returns true if the game object is remote to the machine the script is running on. Returns false otherwise.

DisplayMessage ( string message )

Adds a system text message to the chat window on the local machine.

Send ( integer to, string type, ... )

Send a script-defined message across the network.

To is the player network id of the recipient. None, nil, or 0 broadcasts to all players.

Type is a one-character string indicating the script-defined message type.

Other parameters will be sent as data and passed to the recipient's Receive function as parameters. Send supports nil, boolean, handle, integer, number, string, vector, and matrix data types. It does not support function, thread, or arbitrary userdata types.

The sent packet can contain up to 244 bytes of data (255 bytes maximum for an Anet packet minus 6 bytes for the packet header and 5 bytes for the reliable transmission header)

TypeBytes
nil1
boolean1
handleinvalid (zero)1
valid (nonzero)1 + sizeof(int) = 5
numberzero1
char (integer -128 to 127)1 + sizeof(char) = 2
short (integer -32768 to 32767)1 + sizeof(short) = 3
int (integer)1 + sizeof(int) = 5
double (non-integer)1 + sizeof(double) = 9
stringlength < 311 + length
length >= 312 + length
tablecount < 311 + count + size of keys and values
count >= 312 + count + size of keys and values
userdataVECTOR_3D1 + sizeof(VECTOR_3D) = 13
MAT_3D1 + sizeof(REDUCED_MAT) = 12

Read ODF

These functions read values from an external ODF, INI, or TRN file.

odfhandle OpenODF ( string filename )

Opens the named file as an ODF. If the file name has no extension, the function will append ".odf" automatically.

If the file is not already open, the function reads in and parses the file into an internal database. If you need to read values from it relatively frequently, save the handle into a global variable to prevent it from closing.

Returns the file handle if it succeeded. Returns nil if it failed.

boolean, boolean GetODFBool ( odfhandle odf, [ string section ], string label, [ boolean default ] )

Reads a boolean value from the named label in the named section of the ODF file. Use a nil section to read labels that aren't in a section.

It considers values starting with 'Y', 'y', 'T', 't', or '1' to be true and value starting with 'N', 'n', 'F', 'f', or '0' to be false. Other values are considered undefined.

If a value is not found or is undefined, it uses the default value. If no default value is given, the default value is false.

Returns the value and whether the value was found.

integer, boolean GetODFInt ( odfhandle odf, [ string section ], string label, [ integer default ] )

Reads an integer value from the named label in the named section of the ODF file. Use nil as the section to read labels that aren't in a section.

If no value is found, it uses the default value. If no default value is given, the default value is 0.

Returns the value and whether the value was found.

number, boolean GetODFFloat ( odfhandle odf, [ string section ], string label, [ number default ] )

Reads a floating-point value from the named label in the named section of the ODF file. Use nil as the section to read labels that aren't in a section.

If no value is found, it uses the default value. If no default value is given, the default value is 0.0.

Returns the value and whether the value was found.

string, boolean GetODFString ( odfhandle odf, [ string section ], string label, [ string default ] )

Reads a string value from the named label in the named section of the ODF file. Use nil as the section to read labels that aren't in a section.

If a value is not found, it uses the default value. If no default value is given, the default value is nil.

Returns the value and whether the value was found.

Terrain

These functions return height and normal from the terrain height field.

number, vector GetTerrainHeightAndNormal ( handle h )

Returns the terrain height and normal vector at the location of the game object.

number, vector GetTerrainHeightAndNormal ( string path [, integer point ] )

Returns the terrain height and normal vector at a point on the named path. It uses the start of the path if no point is given.

number, vector GetTerrainHeightAndNormal ( vector position )

Returns the terrain height and normal vector at the position vector.

number, vector GetTerrainHeightAndNormal ( matrix transform )

Returns the terrain height and normal vector at the position of the transform matrix.

Floor

These functions return height and normal from the terrain height field and the upward-facing polygons of any entities marked as floor owners.

number, vector GetFloorHeightAndNormal ( handle h )

Returns the floor height and normal vector at the location of the game object.

number, vector GetFloorHeightAndNormal ( string path [, integer point ] )

Returns the floor height and normal vector at a point on the named path. It uses the start of the path if no point is given.

number, vector GetFloorHeightAndNormal ( vector position )

Returns the floor height and normal vector at the position vector.

number, vector GetFloorHeightAndNormal ( matrix transform )

Returns the floor height and normal vector at the position of the transform matrix.

Map

string GetMissionFilename () [2.0+]

Returns the name of the BZN file for the map. This can be used to generate an ODF name for mission settings.

string GetMapTRNFilename ()

Returns the name of the TRN file for the map. This can be used with OpenODF() to read values from the TRN file.

Files [2.0+]

string UseItem( string filename ) [2.0+]

Returns the contents of the named file as a string, or nil if the file could not be opened.

Effects [2.0+]

ColorFade ( number ratio, number rate, integer r, integer g, integer b ) [2.0+]

Starts a full screen color fade.

Ratio sets the opacity, with 0.0 transparent and 1.0 almost opaque

Rate sets how fast the opacity decreases over time.

R, G, and B set the color components and range from 0 to 255

Vector

This is a custom userdata representing a position or direction. It has three number components: x, y, and z.

vector SetVector ( [ number x ], [ number y ], [ number z ] )

Returns a vector whose components have the given number values. If no value is given for a component, the default value is 0.0.

number DotProduct ( vector a, vector a )

Returns the dot product between vectors a and b.

Equivalent to a.x * b.x + a.y * b.y + a.z * b.z.

vector CrossProduct ( vector a, vector b )

Returns the cross product between vectors a and b.

Equivalent to SetVector(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x).

vector Normalize ( vector v )

Returns the vector scaled to unit length.

Equivalent to SetVector(v.x * scale, v.y * scale, v.z * scale) where scale is 1.0f / sqrt(v.x2 + v.y2 + v.z2).

number Length ( vector v )

Returns the length of the vector.

Equivalent to sqrt(v.x2 + v.y2 + v.z2).

number LengthSquared ( vector v )

Returns the squared length of the vector.

Equivalent to v.x2 + v.y2 + v.z2.

number Distance2D ( vector a, vector b )

Returns the 2D distance between vectors a and b.

Equivalent to sqrt((b.x - a.x)2 + (b.z - a.z)2).

number Distance2DSquared ( vector a, vector b )

Returns the squared 2D distance of the vector.

Equivalent to (b.x - a.x)2 + (b.z - a.z)2.

number Distance3D ( vector a, vector b )

Returns the 3D distance between vectors a and b.

Equivalent to sqrt((b.x - a.x)2 + (b.y - a.y)2 + (b.z - a.z)2).

number Distance3DSquared ( vector a, vector b )

Returns the squared 3D distance of the vector.

Equivalent to (b.x - a.x)2 + (b.y - a.y)2 + (b.z - a.z)2.

-vector

Negate the vector.

Equivalent to SetVector(-vector.x, -vector.y, -vector.z).

vector1 + vector2

Add two vectors.

Equivalent to SetVector(vector1.x + vector2.x, vector1.y + vector2.y, vector1.z + vector2.z).

vector1 - vector2

Subtract two vectors.

Equivlent to SetVector(vector1.x - vector2.x, vector1.y - vector2.y, vector1.z - vector2.z).

number * vector

Multiply a number by a vector.

Equivalent to SetVector( number * vector.x, number * vector.y, number * vector.z).

vector * number

Multiply a vector by a number.

Equivalent to SetVector(vector.x * number, vector.y * number, vector.z * number).

vector1 * vector2

Multiply two vectors.

Equivlent to SetVector(vector1.x * vector2.x, vector1.y * vector2.y, vector1.z * vector2.z)

number / vector

Divide a number by a vector.

Equivalent to SetVector( number / vector.x, number / vector.y, number / vector.z).

vector / number

Divide a vector by a number.

Equivalent to SetVector(vector.x / number, vector.y / number, vector.z / number).

vector1 / vector2

Divide two vectors.

Equivlent to SetVector(vector1.x / vector2.x, vector1.y / vector2.y, vector1.z / vector2.z)

vector1 == vector2

Check if two vectors are equal.

vector1 ~= vector2

Check if two vectors are not equal.

Matrix

This is a custom userdata representing an orientation and position in space. It has four vector components (right, up, front, and posit) sharing space with twelve number components (right_x, right_y, right_z, up_x, up_y, up_z, front_x, front_y, front_z, posit_x, posit_y, posit_z).

matrix SetMatrix ( [ number right_x ], [ number right_y ], [ number right_z ], [ number up_x ], [ number up_y ], [ number up_z ], [ number front_x ], [ number front_y ], [ number front_z ], [ number posit_x ], [ number posit_y ], [ number posit_z ] )

Returns a matrix whose components have the given number values. If no value is given for a component, the default value is zero. Be careful with this since it's easy to build a non-orthonormal matrix that will break all kinds of built-in assumptions.

matrix IdentityMatrix

Global value representing the identity matrix.

Equivalent to SetMatrix(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0).

matrix BuildAxisRotationMatrix ( [ number angle ], [ number axis_x ], [ number axis_y ], [ number axis_z ] )

Build a matrix representing a rotation by an angle around an axis. The angle is in radians. If no value is given for the angle or an axis component, the default value is zero. The axis must be unit-length (i.e. axis_x2 + axis_y2 + axis_z2 = 1.0 or the resulting matrix will be wrong.

matrix BuildAxisRotationMatrix ( [ number angle ], vector axis )

Build a matrix representing a rotation by an angle around an axis. The angle is in radians. If no value is given for the angle, the default value is zero. The axis must be unit-length (i.e. axis.x2 + axis.y2 + axis.z2 = 1.0 or the resulting matrix will be wrong.

matrix BuildPositionRotationMatrix ( [ number pitch ], [ number yaw ], [ number roll ], [ number posit_x ], [ number posit_y ], [ number posit_z ] )

Build a matrix with the given pitch, yaw, and roll angles and position. The angles are in radians. If no value is given for a component, the default value is zero.

matrix BuildPositionRotationMatrix ( [ number pitch ], [ number yaw ], [ number roll ], vector position )

Build a matrix with the given pitch, yaw, and roll angles and position. The angles are in radians. If no value is given for a component, the default value is zero.

matrix BuildOrthogonalMatrix ( [ vector up ], [ vector heading ] )

Build a matrix with zero position, its up axis along the specified up vector, oriented so that its front axis points as close as possible to the heading vector. If up is not specified, the default value is the Y axis. If heading is not specified, the default value is the Z axis.

matrix BuildDirectionalMatrix ( [ vector position ], [ vector direction ] )

Build a matrix with the given position vector, its front axis pointing along the direction vector, and zero roll. If position is not specified, the default value is a zero vector. If direction is not specified, the default value is the Z axis.

matrix * matrix

Multiply two matrices.

matrix * vector

Transform a vector by a matrix.

Portal Functions [2.1+]

These functions control the Portal building introduced in The Red Odyssey expansion.

PortalOut ( handle portal ) [2.1+]

Sets the specified Portal direction to "out", indicated by a blue visual effect while active.

PortalIn ( handle portal ) [2.1+]

Sets the specified Portal direction to "in", indicated by an orange visual effect while active.

DeactivatePortal ( handle portal ) [2.1+]

Deactivates the specified Portal, stopping the visual effect.

ActivatePortal ( handle portal ) [2.1+]

Activates the specified Portal, starting the visual effect.

bool IsIn ( handle portal ) [2.1+]

Returns true if the specified Portal direction is "in". Returns false otherwise.

bool isPortalActive ( handle portal ) [2.1+]

Returns true if the specified Portal is active. Returns false otherwise.

Important: note the capitalization!

handle BuildObjectAtPortal ( string odfname, integer teamnum, handle portal ) [2.1+]

Creates a game object with the given odf name and team number at the location of a portal.

The object is created at the location of the visual effect and given a 50 m/s initial velocity.

Cloak [2.1+]

These functions control the cloaking state of craft capable of cloaking.

Cloak ( handle h ) [2.1+]

Makes the specified unit cloak if it can.

Note: unlike SetCommand(h, AiCommand.CLOAK), this does not change the unit's current command.

Decloak ( handle h ) [2.1+]

Makes the specified unit de-cloak if it can.

Note: unlike SetCommand(h, AiCommand.DECLOAK), this does not change the unit's current command.

SetCloaked ( handle h ) [2.1+]

Instantly sets the unit as cloaked (with no fade out).

SetDecloaked ( handle h ) [2.1+]

Instant sets the unit as uncloaked (with no fade in).

bool IsCloaked ( handle h ) [2.1+]

Returns true if the unit is cloaked. Returns false otherwise

EnableCloaking ( handle h, bool enable ) [2.1+]

Enable or disable cloaking for a specified cloaking-capable unit.

Note: this does not grant a non-cloaking-capable unit the ability to cloak.

EnableAllCloaking ( bool enable ) [2.1+]

Enable or disable cloaking for all cloaking-capable units.

Note: this does not grant a non-cloaking-capable unit the ability to cloak.

Hide [2.1+]

These functions hide and show game objects. When hidden, the object is invisible (similar to Phantom VIR and cloak) and undetectable on radar (similar to RED Field and cloak). The effect is similar to but separate from cloaking. For the most part, AI units ignore the hidden state.

void Hide( handle h ) [2.1+]

Hides a game object.

void UnHide( handle h ) [2.1+]

Un-hides a game object.

Explosion [2.1+]

These functions create explosions at a specified location. They do not return a handle because explosions are not game objects and thus not visible to the scripting system.

MakeExplosion ( string odfname, handle h ) [2.1+]

Creates an explosion with the given odf name at the location of a game object.

MakeExplosion ( string odfname, string path ) [2.1+]

Creates an explosion with the given odf name at the start of the named path.

MakeExplosion ( string odfname, vector position ) [2.1+]

Creates an explosion with the given odf name at the given position vector.

MakeExplosion ( string odfname, matrix transform ) [2.1+]

Creates an explosion with the given odf name with the given transform matrix.