ScriptUtils
----BZ98R ScriptUtils Stub.
Definitions for Lua Language Server
Type declarations
A handle to a game object. This is a unique identifier for the object in the game world.
ODF ParameterDB
A handle to an audio message.
Team Number
Objective Color Label
TeamSlot Integer
Many of these values likely never appear in game and are leftover from Interstate '76
Wooden Structures
A structure which can contain the floor
The floor in a bridge
Metal Structures
Wooden Structures
A structure which can contain the floor
The floor in a bridge
Metal Structures
For maintainability, always use this enum instead of raw team slot numbers. Slots starting with MIN_ and MAX_ represent the lower and upper bound of a range of slots.
For maintainability, always use this enum instead of raw command numbers.
The Lua scripting system defines some global variables that can be of use to user scripts.
Contains current build version
Battlezone 1.5 versions start with "1"
Battlezone 98 Redux versions start with "2"
For example "1.5.2.27u1"
or "2.2.301"
Contains the index of the current language.
- English
- French
- German
- Spanish
- Italian
- Portuguese
- Russian
Contains the full name of the current language in all-caps: "ENGLISH"
, "FRENCH"
, "GERMAN"
, "SPANISH"
, "ITALIAN"
, "PORTUGUESE"
, or "RUSSIAN"
Contains the two-letter language code of the current language: "en"
, "fr"
, "de"
, "es"
, "it"
, "pt"
or "ru"
Contains the most recently pressed game key (e.g. "Ctrl+Z")
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.
Repeat the last audio message.
Plays the given audio file, which must be an uncompressed RIFF WAVE (.WAV) file. Returns an audio message handle.
Returns true if the audio message has stopped. Returns false otherwise.
Stops the given audio message.
Returns true if any audio message is playing. Returns false otherwise.
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.
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.
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.
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.
This is a global table that converts between class identifier numbers and class identifier names. Many of these values likely never appear in game and are leftover from Interstate '76
These function get and set a unit's target.
These functions get and set position and orientation.
If the target is a path this is the path point index, defaults to 0.
Returns the game object's or path point's position vector. Returns nil if none exists. @todo Can't depricate this because it's used for paths too, at least for now
These functions help generate position values close to a center point.
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).
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.
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.
Sets team alliances back to default.
Sets whether team alliances are locked. Locking alliances prevents players from allying or un-allying, preserving alliances set up by the mission script.
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.
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.
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).
These functions remove scrap, either to reduce the global game object count or to remove clutter around a location.
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.
Clear all scrap within the given distance of a position vector, transform matrix, game object, or named path. It uses the start of the path if no point is given.
These functions look up game objects in team slots.
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. Slots starting with MIN_ and MAX_ represent the lower and upper bound of a range of slots.
These functions get and set pilot counts for a team.
Adds pilots to the team's pilot count, clamped between zero and maximum count. Returns the new pilot count.
Sets the team's pilot count, clamped between zero and maximum count. Returns the new pilot count.
Returns the team's pilot count.
Adds pilots to the team's maximum pilot count. Returns the new pilot count.
Sets the team's maximum pilot count. Returns the new pilot count.
These functions get and set scrap values for a team.
Adds to the team's scrap count, clamped between zero and maximum count. Returns the new scrap count.
Sets the team's scrap count, clamped between zero and maximum count. Returns the new scrap count.
Returns the team's scrap count.
Adds to the team's maximum scrap count. Returns the new maximum scrap count.
Sets the team's maximum scrap count. Returns the new maximum scrap count.
These function report various global time values.
Returns the elapsed time in seconds since the start of the mission.
Returns the simulation time step in seconds.
Returns the current system time in milliseconds. This is mostly useful for performance profiling.
These functions control general mission properties like strategic AI and mission flow
defaults to true
When: 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.
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.
Returns true if a given team is AI controlled. Returns false otherwise. Unlike SetAIControl, this function may be called at any time.
Returns the current AIP for the team. It uses team 2 if no team number is given.
Switches the team's AI plan. It uses team 2 if no team number is given.
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.
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.
These functions control the large timer at the top of the screen.
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.
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.
Stops the cockpit timer.
Hides the cockpit timer.
Returns the current time in seconds on the cockpit timer.
These functions control the global earthquake effect.
Starts a global earthquake effect.
Changes the magnitude of an existing earthquake effect. Important: note the inconsistent capitalization, which matches the internal C++ script utility functions.
Stops the global earthquake effect.
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.
- one-way
- round-trip
- loop
Changes the named path to the given path type.
Returns the type of the named path.
Changes the named path to one-way. Once a unit reaches the end of the path, it will stop.
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.
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.
Returns the number of points in the named path, or 0 if the path does not exist.
These functions treat a path as the boundary of a closed polygonal area.
Returns how many times the named path loops around the given position vector, transform matrix, or object. Each full counterclockwise loop adds one and each full clockwise loop subtracts one.
Returns true if the given position vector, transform matrix, or object is inside the area bounded by the named path. Returns false otherwise. This function is equivalent to
GetWindingNumber( path, h ) ~= 0
These These functions send commands to units or query their command state.
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.
Returns true if the game object inspected by the info display matches the given odf or is the given handle.
@note see _gameobject
module.
LuaMission currently has limited network support, but can detect if the mission is being run in multiplayer and if the local machine is hosting.
Returns true if the game is a network game. Returns false otherwise.
Returns true if the local machine is hosting a network game. Returns false otherwise.
Multiplayer: The displayed message is entirely local regardless of hosting status, if you want a message to be visible to all players you should Send() a message to all players to display the given message.
Adds a system text message to the chat window on the local machine.
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)
Type | Bytes | |
---|---|---|
nil | 1 | |
boolean | 1 | |
handle | invalid (zero) | 1 |
valid (nonzero) | 1 + sizeof(int) = 5 | |
number | zero | 1 |
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 | |
string | length < 31 | 1 + length |
length >= 31 | 2 + length | |
table | count < 31 | 1 + count + size of keys and values |
count >= 31 | 2 + count + size of keys and values | |
userdata | VECTOR_3D | 1 + sizeof(VECTOR_3D) = 13 |
MAT_3D | 1 + sizeof(REDUCED_MAT) = 12 |
These functions return height and normal from the terrain height field.
Returns the terrain height and normal vector at a position vector, transform matrix, object, or point on a named path.
These functions return height and normal from the terrain height field and the upward-facing polygons of any entities marked as floor owners.
Returns the floor height and normal vector at a position vector, transform matrix, object, or point on a named path.
Returns the name of the BZN file for the map. This can be used to generate an ODF name for mission settings.
Returns the name of the TRN file for the map. This can be used with OpenODF() to read values from the TRN file.
Returns the contents of the named file as a string, or nil if the file could not be opened.
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
This is a custom userdata representing a position or direction. It has three number components: x, y, and z.
A Vector in 3D space
The x-coordinate.
The y-coordinate.
The z-coordinate.
Returns a vector whose components have the given number values. If no value is given for a component, the default value is 0.0.
Returns the dot product between vectors a and b. Equivalent to a.x * b.x + a.y * b.y + a.z * b.z.
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).
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).
Returns the length of the vector. Equivalent to sqrt(v.x2 + v.y2 + v.z2).
Returns the squared length of the vector. Equivalent to v.x2 + v.y2 + v.z2.
Returns the 2D distance between vectors a and b. Equivalent to sqrt((b.x - a.x)2 + (b.z - a.z)2).
Returns the squared 2D distance of the vector. Equivalent to (b.x - a.x)2 + (b.z - a.z)2.
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).
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.
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).
A Matrix
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.
Global value representing the identity matrix. Equivalent to SetMatrix(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0).
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.
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.
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.
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.
These functions control the cloaking state of craft capable of cloaking.
Enable or disable cloaking for a specified cloaking-capable unit. Note: this does not grant a non-cloaking-capable unit the ability to cloak.
Enable or disable cloaking for all cloaking-capable units. Note: this does not grant a non-cloaking-capable unit the ability to cloak.
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.
Multiplayer: Explosions are entirely local, this includes the visuals and the damage. This can be used to create clientside graphics.
Creates an explosion with the given odf name at the target position vector, transform matrix, object, or the start of the named path.
Bitwise operations on 32-bit integers.
TYPE: table
SPECIAL: field
GLYPH: bi bi-table
----Table of bitwise operation functions.
Normalizes a number to the numeric range for bit operations and returns it. This function is usually not needed since all bit operations already normalize all of their input arguments. Check the operational semantics for details.
function printx(x) print("0x"..bit.tohex(x)) end
print(0xffffffff) --> 4294967295
print(bit.tobit(0xffffffff)) --> -1
printx(bit.tobit(0xffffffff)) --> 0xffffffff
print(bit.tobit(0xffffffff + 1)) --> 0
print(bit.tobit(2^40 + 1234)) --> 1234
Returns the bitwise not of its argument.
Returns the bitwise and of its arguments.
Returns the bitwise or of its arguments.
Returns the bitwise xor of its arguments.
The number to shift.
The number of bits to shift.
Bitwise logical left-shift.
The number to shift.
The number of bits to shift.
Bitwise logical right-shift.
The number to shift.
The number of bits to shift.
Bitwise arithmetic right-shift.
The number to rotate.
The number of bits to rotate.
Bitwise left rotation.
The number to rotate.
The number of bits to rotate.
Bitwise right rotation.
The number to convert to hex.
The number of hex digits to generate. Positive numbers generate lowercase hex digits, negative numbers generate uppercase hex digits.
hex string representation of the number.
Converts its first argument to a hex string. The number of hex digits is given by the absolute value of the optional second argument. Positive numbers between 1 and 8 generate lowercase hex digits. Negative numbers generate uppercase hex digits. Only the least-significant 4*|n| bits are used. The default is to generate 8 lowercase hex digits.
print(bit.tohex(1)) --> 00000001
print(bit.tohex(-1)) --> ffffffff
print(bit.tohex(0xffffffff)) --> ffffffff
print(bit.tohex(-1, -8)) --> FFFFFFFF
print(bit.tohex(0x21, 4)) --> 0021
print(bit.tohex(0x87654321, 4)) --> 4321
===================================================
_api -> table: _api
- John "Nielk1" Klein
BZ98R LUA Extended API.
This API creates a full OOP wrapper and replacement the mission functions with an event based system for easier expansion.
This module is the core of the API and offers the following features:
- Loads the following modules
_logger
_fix
_utility
_hook
_gameobject
_customsavetype
_version
- Create events for all default game functions and custom events
Save
(AddSaveLoad
) [GAME]Load
(AddSaveLoad
) [GAME]PostLoad
(AddSaveLoad
) [CUSTOM]Start
(Add
) [GAME]GameKey
(Add
) [GAME]Update
(Add
) [GAME]MapObject
(Add
) [CUSTOM]CreateObject
(Add
) [GAME]AddObject
(Add
) [GAME]DeleteObject
(Add
) [GAME]CreatePlayer
(Add
) [GAME]AddPlayer
(Add
) [GAME]DeletePlayer
(Add
) [GAME]Receive
(Add
) [GAME]Command
(Add
) [GAME]
- Advanced Save/Load serialization system
- Custom Type Support (via
_customsavetype
) - Multi-reference handling
- Reference loop handling
- Child-parent loop reference resolution
- Custom Type Support (via
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.
loaded data
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.
Called after loading state from a save game file, allowing the script to do any post-load adjustments to data.
This may be very useful to deal with ephemeral tables which might need to be loaded as hard-tables before converted to their weaktable storage in PostLoad.
Called when the mission starts for the first time.
Use this function to perform any one-time script initialization.
zero or more modifiers (Ctrl, Shift, Alt) and a base 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).
Delta Time
Total Time
Called once per tick after updating the network system and before simulating game objects.
This function performs most of the mission script's game logic.
Called for each map game object on initial map load.
Handle is the game object that was created.
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.
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.
Called before a game object is fully deleted.
This function will get a lot of traffic so it should not do too much work.
Note: This is called after the object is largely removed from the game, so most Get functions won't return a valid value.
DPID number for this player
name for this player
Team number for this player
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.
DPID number for this player
name for this player
Team number for this player
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.
DPID number for this player
name for this player
Team number for this player
Called when a player leaves the session.
network player id of the sender.
an arbitrary one-character string indicating the script-defined message type.
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.
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.
parameters
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.
Fix any base mission callbacks that are not using the new event system. This will wrap the existing functions in the hook system and replace them with the hook triggering wrappers. This is called automatically when the API is loaded but can be called again at the end of a script to ensure that all events are wrapped. If you are already purely using events then you do not need to call this function.
===================================================
_camera -> table: _camera
- John "Nielk1" Klein
BZ98R LUA Extended API Camera.
Camera API wrapper. Wraps all stock camera functions with cleaner names and adds some additional functionality.
Dolly | Aim | Target |
---|---|---|
FollowPath | Aim | Object |
FollowPath | Aim | FollowPath |
FollowPath | Aim | Forward |
FollowPath | Aim | Path |
FollowObject | Aim | Object |
FollowObject | Aim | Object |
Starts the cinematic camera and disables normal input.
Finishes the cinematic camera and enables normal input. Does nothing if camera is not active.
Camera is currently active
Returns true when the camera arrives at its destination. Returns false otherwise.
Returns true if the player canceled the cinematic. Returns false otherwise. Cancelation becomes latched until UnCancel is called. Camera is latched as canceled in the engine itself after loading.
Resets the camera cancelled flag. This is needed if the camera cancelation was used to switch to another camera type.
meters above the ground
speed in meters per second
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.
meters above the ground
speed in meters per second
defaults to the same as speed
Moves a cinematic camera along a path at a given height and speed while looking at a target path. Returns true when the camera arrives at its destination. Returns false otherwise.
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. @todo consider changing to a direction vector
Moves a cinematic camera along a path at a given height and speed while looking at a target path point. Returns true when the camera arrives at its destination. Returns false otherwise.
Meters to the right of the base object.
Meters above the base object.
Meters in front of the base object.
true if the base or handle game object does not exist. Returns false otherwise.
Offsets a cinematic camera from a base game object while looking at a target game object. Returns true if the base or handle game object does not exist. Returns false otherwise.
===================================================
_cheatcode -> table: _cheatcode
- John "Nielk1" Klein
BZ98R LUA Extended API Cheat.
General cheat code handler.
Register custom cheat codes and hook the "Cheat" event to detect them.
require("_cheatcode").CreateCode("BZSKIP", "apcann.wav", 0, 0, 255);
local hook = require("_hook");
local camera = require("_camera");
hook.Add("Cheat", "Mission:Cheat", function (cheat)
if cheat == "BZSKIP" then
local machine_state = mission_data.mission_states.StateMachines.main_objectives;
machine_state:SecondsHavePassed(); -- clear timer in case we were in one
camera.End(); -- protected camera exit that won't crash
machine_state:next(); -- move to the next state
end
end);
Cheat key combo event
The name of the cheat code, must be all uppercase letters
Optional sound to play when the cheat is activated
Color flash red component (0-255)
Color flash green component (0-255)
Color flash blue component (0-255)
If true, the cheat can only be used once
Create a new cheat code.
===================================================
_cheat_bzrave
- John "Nielk1" Klein
BZ98R LUA Extended API Cheat.
BZRAVE cheat
Ctrl+Shift + BZRAVE
Replace all weapons with GTechno
require("_cheat_bzrave");
===================================================
_color -> table: _color
- John "Nielk1" Klein
BZ98R LUA Extended API Color.
Collection of color enumerations and functions.
Convert human readable color names to BZ98R color labels.
Convert BZ98R color labels to RGB color codes. This probably isn't useful but it's here.
RAVE GUN! color cycle. Each color is represented as a hexadecimal number: 0xRRGGBBFF.
The red component (0-255)
The green component (0-255)
The blue component (0-255)
The alpha component (0-255)
The red component (0-255)
The green component (0-255)
The blue component (0-255)
The alpha component (0-255)
Convert RGBA color to the closest game color code. This function takes an RGBA color and finds the closest game color code.
Ansi color codes for terminal output sorted by game color codes.
The ANSI 256 color code (0-255)
Convert RGBA color to ANSI 256 color escape code. This function takes an RGBA color and converts it to an ANSI 256 color code. It uses a color cube and grayscale range to find the closest match.
The ANSI 256 color escape code
Convert RGBA color to ANSI 256 color escape code. This function takes an RGBA color and converts it to an ANSI 256 color escape code.
The ANSI 24-bit color escape code
Convert RGBA color to ANSI 24-bit color escape code. This function takes an RGBA color and converts it to an ANSI 24-bit color escape code.
Convert human readable color names to BZ98R color labels.
===================================================
_config
- John "Nielk1" Klein
BZ98R LUA Extended API Configuration.
Constants used to configure the API's system. Note that reading any non-table value other than "locked" will lock the config table.
@usage local config = require("_config");
if not config.locked then config.hook_priority.DeleteObject.GameObject = -99999; end
===================================================
_customsavetype -> table: _customsavetype
- John "Nielk1" Klein
BZ98R LUA Extended API CustomSaveType.
Crude custom type to make data not save/load exploiting the custom type system.
local customsavetype = require("_customsavetype");
customsavetype.Register(ObjectDef);
Saving / Loading: Type Save/Load always run first, before any other save/load/postload hooks. This is needed to ensure the type instances that appear in later save/load calls will work properly. If a "TypePostLoad" is needed use a standard SaveLoad hook.
Custom Savable Type definition. This allows for complex structures to be saved and loaded and preserve their function metatable assignment. If a custom type is registered, it will be used instead of the default serialization methods.
The type name of the custom savable type.
If true, the type will not be saved or loaded, a nil will be saved instead.
If true, the type will not undergo checks for shared or looped references when saving.
TYPE: UNK_CustomSavableType
TYPE: UNK_CustomSavableType?
TYPE: nil
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----The base type to inherit from, if any.
Called when saving an instance of this type. Return value is saved.
Called when loading an instance of this type. Data is the value returned from Save.
Called on the type itself before any other data is saved.
Called on the type itself, before any other data is loaded.
Table to augment with unsaved data. If nil, a new table is created.
Creates a new table or augments the passed in table marking it as unsaved.
Register a custom savable type.
Does this custom savable type implement the given type?
Extract the custom savable type if implemented
===================================================
_deque
- Pierre 'catwell' Chapuis
BZ98R LUA Extended API dequeue library.
https://github.com/catwell/cw-lua/blob/master/deque/deque.lua
Deque implementation by Pierre 'catwell' Chapuis
Copyright (C) by Pierre Chapuis
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The index of the first element.
The index of the last element.
TYPE: UNK_any
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----The elements stored in the deque.
Save event function.
===================================================
_fix
- John "Nielk1" Klein
BZ98R LUA Extended API Lua Bug Fixer.
Contains fixes for bugs in the game's lua implementation and other polyfils.
- Polyfill:
table.unpack
for Lua 5.1 compatibility - Fix/Polyfill: Remap
SettLabel
toSetLabel
for BZ1.5 - Fix: Works around the possible stuck iterator in
ObjectiveObjects
- Fix/Polyfill: TeamSlot missing "PORTAL" = 90
- Fix: Tugs not respecting DropOff command due to invalid deploy state
- Fix/Polyfill: Fix for broken
Formation
order function - Fix: Powerups not using thrusters when falling if on an AI team
===================================================
_gameobject -> table: _gameobject
- John "Nielk1" Klein
BZ98R LUA Extended API GameObject.
GameObject wrapper functions.
GameObject An object containing all functions and data related to a game object.
TYPE: UNK_Handle
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----Handle used by BZ98R
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----Extended data saved into the object
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----Unsaved data used for housekeeping that is regenerated at load
GameObject An object containing all functions and data related to a game object.
Get Handle used by BZ98R.
Get the SeqNo of the GameObject. Note that the SeqNo is rather useless.
Save event function.
Handle
Load event function.
GameObject An object containing all functions and data related to a game object.
TypeSave event function.
Object data
TypeLoad event function.
Unsafe to use on a handle passed in by CreateObject(h), doing so will crash the game. If you need this functionality, you should defer the deletion until the next Update(dt).
Multiplayer: Very dangerous. There are innumerable cases which can cause objects to be improperly deleted and/or spawn explosion chunks which may only be visible to certain players. In order to safely delete a distributed object, ALL players must call RemoveObject(h) on the target object simultaneously. Additionally, attempting to delete the starting recycler in a strategy or MPI game will crash the game.
Remove GameObject from world.
Returns true if the game object inspected by the info display matches the current game object.
ODF filename
Is the GameObject this odf?
enemy1:IsOdf("svturr")
Get odf of GameObject
identifier for race
Get base of GameObject
name string
Get label of GameObject
Label
Is the GameObject this odf?
enemy1:SetLabel("special_object_7")
string
Returns the four-character class signature of the game object (e.g. "WING"). Returns nil if none exists.
label string
Returns the class label of the game object (e.g. "wingman"). Returns nil if none exists.
number
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.
identifier for race
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".
Does the GameObject exist in the world? Returns true if the game object exists. Returns false otherwise.
Is the GameObject alive and is still pilot controlled? Returns true if the game object exists and (if the object is a vehicle) controlled. Returns false otherwise.
Is the GameObject alive and piloted? Returns true if the game object exists and (if the object is a vehicle) controlled and piloted. Returns false otherwise.
Returns true if it's a Craft.
Returns true if it's a Building. Does not include guntowers.
Returns true if it's a person.
float
Returns true if the game object exists and has less health than the threshold. Returns false otherwise.
Returns true if the game object was recycled by a Construction Rig on the given team.
These functions get and set team number. Team 0 is the neutral or environment team.
number
Returns the game object's team number.
Sets the game object's team number.
number
Get perceived team number of the GameObject.
Set perceived team number of the GameObject.
These function get and set a unit's target.
Set this as the local player's target.
Set the game object's target.
Set this object as another object's target.
Returns the game object's target. Returns nil if it has none.
These functions get and set owner. The default owner for a game object is the game object that created it.
Sets the game object's owner. @todo confirm owner can be nil
Returns the game object's owner. Returns nil if it has none.
These functions get and set vehicle pilot class.
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.
Returns the odf name of the vehicle's pilot class. Returns nil if none exists.
Get object's position vector.
Get front vector.
Index of the path point in the path (optional)
Set the position of the GameObject.
Get object's tranform matrix.
Set the tranform matrix of the GameObject.
Get object's velocity vector.
Set the velocity of the GameObject.
Get object's omega.
Set the omega of the GameObject.
These functions query a game object for information about ordnance hits.
Returns who scored the most recent hit on the game object. Returns nil if none exists.
Returns the last time an enemy shot the game object.
Returns the last time a friend shot the game object.
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.
Do we consider this an ally?
Order GameObject to Attack target GameObject.
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.
Sets the game object as an objective to all teams.
Sets the game object back to normal.
if the game object is an objective
If the game object an objective?
of the objective/object
Sets the game object's visible name.
Name of the objective
Sets the game object's visible name.
Name of the objective
Sets the game object's visible name. (Technicly a unique function, but effectively an alias for SetObjectiveName) See: GameObject.SetObjectiveName
These functions measure and return the distance between a game object and a reference point.
Position vector, ransform matrix, Object, or path name.
If the target is a path this is the path point index, defaults to 0.
Returns the distance in meters between the game object and a position vector, transform matrix, another object, or point on a named path.
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)
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.
These functions find and return the game object of the requested type closest to a reference point.
Returns the game object closest to self.
Returns the craft closest to self.
Returns the building closest to self.
Returns the enemy closest to self.
Returns the friend closest to self.
Returns the friend closest to self. Returns nil if none exists.
Returns how many objects with the given team and odf name are closer than the given distance.
These functions look up game objects in team slots.
The new game object formerly in the slot, or nil if the slot was empty
Set the game object in the specified team slot. This could have major sideffects so be careful with it.
Sets the game object in the specified team slot. See: ~ScriptUtils.TeamSlot~
These functions control deployable craft (such as Turret Tanks or Producer units).
Returns true if the game object is a deployed craft. Returns false otherwise. @function IsDeployed
Tells the game object to deploy. @function Deploy
These functions access selection state (i.e. whether the player has selected a game object)
Returns true if the game object is selected. Returns false otherwise.
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.
Returns true if the game object is marked as mission-critical. Returns false otherwise.
defaults to true
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.
These functions access unit weapons and damage.
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
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.
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.
Tells the game object to fire at the given target.
damage amount
Applies damage to the game object.
These functions send commands to units or query their command state.
Returns true if the game object can be commanded. Returns false otherwise.
Returns true if the game object is a producer that can build at the moment. Returns false otherwise. The concept here is that the builder either A: Does not need to deploy or B: Does need to deploy but is deployed.
Returns true if the game object is a producer and currently busy. Returns false otherwise. An undeployed builder that needs to deploy will always indicate false. A deployed (if needed) producer with a buildClass set is considered busy. The buildClass may be cleared after the CreateObject call.
Returns true if the game object has reached the end of the named path. Returns false otherwise.
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.
Returns the target of the current command for the game object. Returns nil if it has none.
Gets the independence of a unit.
Sets the independence of a unit. 1 (the default) lets the unit take initiative (e.g. attack nearby enemies), while 0 prevents that.
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.
Order priority, >0 removes user control
Order GameObject to Attack target GameObject.
Order priority, >0 removes user control
Order GameObject to Goto target Vector, Matrix, GameObject, or Path. @function GameObject:Goto
Order priority, >0 removes user control
Order GameObject to Mine target Path.
Order priority, >0 removes user control
Order GameObject to Follow target GameObject.
true if following, false otherwise
Is the GameObject following the target GameObject?
Order priority, >0 removes user control
Order GameObject to Defend area.
Order priority, >0 removes user control
Order GameObject to Defend2 target GameObject.
Order priority, >0 removes user control
Order GameObject to Stop.
Target Path name
Order priority, >0 removes user control
Order GameObject to Patrol target path.
Order priority, >0 removes user control
Order GameObject to Retreat.
Order priority, >0 removes user control
Order GameObject to GetIn target GameObject.
Order priority, >0 removes user control
Order GameObject to Pickup target GameObject.
Order priority, >0 removes user control
Order GameObject to Pickup target path name.
Object Definition
Order priority, >0 removes user control
Order GameObject to Build target config. Oddly this function does not include a location for the action, might want to use the far more powerful orders system.
Object Definition
Target GameObject instance, vector, matrix, or path name
Order priority, >0 removes user control
Order GameObject to BuildAt target GameObject.
Order priority, >0 removes user control
Order GameObject to Formation follow target GameObject.
Order priority, >0 removes user control
Order GameObject to Hunt area.
Order priority, >0 removes user control
Order GameObject to Recycle.
These functions query Tug and Cargo.
Returns true if the GameObject is a tug carrying cargo.
Returns the GameObject of the cargo if the GameObject is a tug carrying cargo. Returns nil otherwise.
Returns the GameObject of the tug carrying the object. Returns nil if not carried.
These functions control the pilot of a vehicle.
Commands the vehicle's pilot to eject.
Commands the vehicle's pilot to hop out.
Kills the vehicle's pilot as if sniped.
Removes the vehicle's pilot cleanly.
Returns the vehicle that the pilot GameObject most recently hopped out of.
These functions get and set health values on a game object.
health ratio
Returns the fractional health of the game object between 0 and 1.
if friend1:GetHealth() < 0.5 then
friend1:Retreat("retreat_path");
end
current health or nil
Returns the current health value of the game object.
max health or nil
Returns the maximum health value of the game object.
health amount
Sets the current health of the game object.
health amount
Sets the max health of the GameObject to the NewHealth value.
health amount
Adds the health to the GameObject.
GiveMaxHealth
These functions get and set ammo values on a game object.
ammo ratio
Returns the fractional ammo of the game object between 0 and 1.
current ammo or nil
Returns the current ammo value of the game object.
max ammo or nil
Returns the maximum ammo value of the game object.
ammo amount
Sets the current ammo of the game object.
ammo amount
Sets the maximum ammo of the game object.
ammo amount
Adds to the current ammo of the game object.
Sets the unit's current ammo to maximum.
LuaMission currently has limited network support, but can detect if the mission is being run in multiplayer and if the local machine is hosting.
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!
Returns true if the game is local to the machine the script is running on. Returns false otherwise.
Returns true if the game object is remote to the machine the script is running on. Returns false otherwise.
Returns true if the game object is initialized, meaning it has been created and is either local or remote.
These functions control the Portal building introduced in The Red Odyssey expansion.
Sets the specified Portal direction to "out", indicated by a blue visual effect while active.
Sets the specified Portal direction to "in", indicated by an orange visual effect while active.
Activates the specified Portal, starting the visual effect.
Returns true if the specified Portal direction is "in". Returns false otherwise.
Returns true if the specified Portal is active. Returns false otherwise. Important: note the capitalization!
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.
These functions control the cloaking state of craft capable of cloaking.
Makes the specified unit cloak if it can. Note: unlike SetCommand(h, AiCommand.CLOAK), this does not change the unit's current command.
Makes the specified unit de-cloak if it can. Note: unlike SetCommand(h, AiCommand.DECLOAK), this does not change the unit's current command.
Instantly sets the unit as cloaked (with no fade out).
Instant sets the unit as uncloaked (with no fade in).
Returns true if the unit is cloaked. Returns false otherwise
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.
Hides a game object.
Un-hides a game object.
Object in question
Is this object an instance of GameObject?
Object in question
Extract the GameObject from this object that implements GameObject.
Create new GameObject Intance.
Sequence number of the object
Create a new GameObject instance. This works via a lookup table so it can fail easily.
Object Definition File (without ".odf")
index
Multiplayer: Objects built by the host are always synchronized, objects built by clients will always be desynchronized initially, but can be synchronized by calling SetLocal().
Creates a GameObject with the given odf name, team number, and location.
Label
Get GameObject by Label.
These function get and set a unit's target.
Returns the local player's target. Returns nil if it has none.
These functions find and return the game object of the requested type closest to a reference point.
The path name.
The point on the path (optional).
Returns the game object closest to a position vector, transform matrix, another object, or point on a named path.
The path name.
The point on the path (optional).
Returns the craft closest to a position vector, transform matrix, another object, or point on a named path.
The path name.
The point on the path (optional).
Returns the building closest to a position vector, transform matrix, another object, or point on a named path.
The path name.
The point on the path (optional).
Returns the enemy closest to a position vector, transform matrix, another object, or point on a named path.
The path name.
The point on the path (optional).
Returns the friend closest to a position vector, transform matrix, another object, or point on a named path.
The path name.
The point on the path (optional).
Returns the friend closest to the given reference point. Returns nil if none exists.
These functions return iterator functions for use with Lua's "for
Position vector, ransform matrix, Object, or path name.
If the target is a path this is the path point index, defaults to 0.
Iterator of GameObject values
Enumerates game objects within the given distance a target.
Iterator of GameObject values
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 of GameObject values
Enumerates all craft.
Iterator of GameObject values
Enumerates all game objects currently selected by the local player.
Iterator of GameObject values
Enumerates all game objects marked as objectives.
These functions look up game objects in team slots.
Get the game object in the specified team slot.
See: ~ScriptUtils.TeamSlot~
Get Player GameObject of team. @todo depricate functions like this and move them to a team manager, because of the issue noted on scriptutils for GetTeamSlot.
Get Recycler GameObject of team.
Get Factory GameObject of team.
Get Armory GameObject of team.
Get Factory GameObject of team.
===================================================
_hook -> table: _hook
- John "Nielk1" Klein
BZ98R LUA Extended API Hook.
Event hook for event observer pattern.
local hook = require("_hook");
hook.Add("InitialSetup", "Custom_InitialSetup", function(turn)
end);
hook.Add("Update", "Custom_Update", function(turn)
end);
hook.AddSaveLoad("Custom_SaveLoad",
function()
return MissionData;
end,
function(savedData)
MissionData = savedData;
end);
-- 10% of the time players will just respawn instead of eject, this overrides all other event hooks
hook.Add("PlayerEjected", function(DeadObject)
if object:IsPlayer() and GetRandomFloat(10) > 9 then
return hook.AbortResult(EjectKillRetCodes.DoRespawnSafest);
end
end, 9999)
Identifier for this hook observer.
Higher numbers are higher priority.
Function to be executed when the event is triggered.
Flag to abort the hook chain.
Return values passed from hook function.
Type of the object, used for type checking. "HookResult"
Table of all hooks.
Object in question
Is this object an instance of HookResult?
Return values passed from hook function
Create an Abort HookResult @function _hook.AbortResult
Return values passed from hook function
Create an basic HookResult
This wraps a return value similarly to _hook.AbortResult
and
can be used optionally to wrap return values. This is primarily used internally
to wrap the prior return value to be passed as the next Parameter in
_hook.CallAllPassReturn
based event triggers as event
handler return values are auto-unwrapped by the event handler if wrapping is
detected but process fine if unwrapped.
@function _hook.WrapResult
See:
Event to be hooked
Identifier for this hook observer
Function to be executed
Higher numbers are higher priority
Add a hook to listen to the specified event. @function _hook.Add
Event to be hooked
Identifier for this hook observer
Removes the hook with the given identifier. @function _hook.Remove
Identifier for this hook observer
Function to be executed for Save
Function to be executed for Load
Function to be executed after all Load hooks are called
Add a hook to listen to the Save and Load event. @function _hook.AddSaveLoad
Identifier for this hook observer
Removes the Save and Load hooks with the given identifier. @function _hook.RemoveSaveLoad
Calls hooks associated with Save. @function _hook.CallSave
Calls hooks associated with Load. @function _hook.CallLoad
Event to be hooked
Parameters passed to every hooked function
true if stopped early, else nil
Calls hooks associated with the hook name ignoring any return values. @todo Consider redoing the return value as nothing uses it right now. @function _hook.CallAllNoReturn
Event to be hooked
Parameters passed to every hooked function
nil
if no hooks are called, a HookResult
if the chain is aborted, or the return values from the last hook function.
Calls hooks associated with the hook name passing each return to the next. Hooked functions may return multiple values. The return value is always passed to the next hook wrapped in an EventResult. If the value is generated by one of the hook library's event functions it will be parsed and passed along without wrapping. This allows for the hook chain to be broken early through the use of the AbortResult function. The best action here is to nil check and test your last Parameter with hook.isresult before processing it. @function _hook.CallAllPassReturn
Event to be hooked
Does this event have any hooks? For simple event calls this is not needed, but it's useful before loops triggering many instances of the same event. @function _hook.HasHooks
===================================================
_logger -> table: _logger
- John "Nielk1" Klein
BZ98R LUA Extended API Debug.
System for handling debugging and logging.
TYPE: UNK_LogLevel
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----Log Levels
TYPE: UNK_LogFormat
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----Log Format
TYPE: UNK_InterceptPrint
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----Print Intercept Mode
Patterns to suppress in log messages
TYPE: UNK_DebugSettings
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----@todo make this readonly (at least through this window)
Print log line Ignores wrapping setting for normal print. Will strip colors if not supported.
Section name
Key name
Default value if the key is not found or is a boolean false
Value to return if the key is found and is a boolean true
Lookup table to convert enum value, a failed lookup will be considered a failure
Print Intercept Mode
Log Levels
No logging
Error messages, used for critical issues
Warning messages, used for non-critical issues
Normal print messages, used most often in intercept
Debug messages
Trace messages
Log Format
Raw format
Wrapped format
===================================================
_navmanager -> table: _navmanager
- John "Nielk1" Klein
BZ98R LUA Extended API NavManager.
Manage navs
local navmanager = require("_navmanager");
navmanager.SetCompactionStrategy(navmanager.CompactionStrategy.ImportantFirstChronologicalToGap);
Nav GameObjects swapped. The old nav will be deleted after this event is called. This event allows for scripts to replace their nav references or copy over custom data.
Adds custom data to GameObject for this module.
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----A table containing custom data for this module.
ODF of the nav to build, if nil uses the default nav ODF
Team number of the nav to build
Position vector, Transform matrix, or Object.
path point index, defaults to 0.
Build an important nav and add it to the collection. Important navs will push non-important navs out of the way in the list.
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----What to do when empty slots exist and excess navs exist @table _navmanager.CompactionStrategy
The strategy to use. See @{_navmanager.CompactionStrategy} for options.
Set the compaction strategy for navs. @function _navmanager.SetCompactionStrategy
current compaction strategy. See @{_navmanager.CompactionStrategy} for options.
Get the current compaction strategy for navs.
Team number to enumerate
If true "Overflow Navs" will be included in the enumeration after the initial 10.
function yielding index and nav object
Enumerates all navs for a team. At least 10 indexes will be iterated, even if there are no navs in those slots. Navs not in the nav list, known internally as "Overflow Navs", will be returned with indexes above 10.
for i, nav in navmanager.AllNavGameObjects(1, true) do
print("Nav " .. i .. ": " .. tostring(nav));
end
local active_navs = utility.IteratorToArray(navmanager.AllNavGameObjects(1));
===================================================
_objective
- John "Nielk1" Klein
BZ98R LUA Extended API Objective Manager.
Note that this module cannot manage manually created objectives.
Unique name for objective, usually a filename ending with otf from which data is loaded
defaults to 8 seconds
Override text from the target objective file.
Sort position of the objective. Defaults to the next available ID.
If true, the objective will not be removed when the objectives are cleared. Defaults to false.
Updates the objective message with the given name. If no objective exists with that name, it does nothing.
Clear all objectives except for persistant ones.
Unique name for objective, usually a filename ending with otf from which data is loaded
defaults to 8 seconds
Override text from the target objective file.
Sort position of the objective. Defaults to the next available ID.
If true, the objective will not be removed when the objectives are cleared. Defaults to false.
Adds an objective message with the given name and properties.
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.
Unique name for objective, usually a filename ending with otf from which data is loaded
Sort position of the objective.
Set the objective position of the given name. If no objective exists with that name, it does nothing.
Unique name for objective, usually a filename ending with otf from which data is loaded
Sort position of the objective.
Get the objective position of the given name. If no objective exists with that name, it does nothing.
Unique name for objective, usually a filename ending with otf from which data is loaded
Unique name for objective, usually a filename ending with otf from which data is loaded
defaults to 8 seconds
Override text from the target objective file.
Sort position of the objective. Defaults to the removed objective's position or next available ID.
If true, the objective will not be removed when the objectives are cleared. Defaults to false.
Replaces the objective message with the given name. If no objective exists with that name, it does nothing.
===================================================
_optional -> table: _optional
- John "Nielk1" Klein
BZ98R LUA Extended API Optional loader.
Load a lua module optionally.
local optional = require("_optional");
local missingSuccess, missingMod = optional("_missing");
missingMod = missingSuccess and missingMod or nil;
local missing2Success, missingMod2 = require("_optional")("_missing2");
missingMod2 = missing2Success and missingMod2 or nil;
===================================================
_paramdb -> table: _paramdb
- John "Nielk1" Klein
BZ98R LUA Extended API ODF Handler.
Tracks objects by class and odf.
TYPE: UNK_ParameterDB
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----ODF ParameterDB
Time of last access
ODF file name
ODF file name
ODF file name
ODF file name
cost
ODF file name
cost
ODF file name
@todo This might not need to exist since it doesn't have special class code
ODF file name
Section name
Key name
Default value if the key is not found
Get a general string without handling of class defaults.
ODF file name
Section name
Key name
Default value if the key is not found
Get a general integer without handling of class defaults.
ODF file name
Section name
Key name
Default value if the key is not found
Get a general float without handling of class defaults.
ODF file name
Section name
Key name
Default value if the key is not found
Get a general boolean without handling of class defaults.
ODF file name
Section name
Key name
Default value if the key is not found or is a boolean false
Value to return if the key is found and is a boolean true
Lookup table to convert enum value, a failed lookup will be considered a failure
===================================================
_paths -> table: _paths
- John "Nielk1" Klein
BZ98R LUA Extended API Paths.
Object in question
Is this object a table?
Path name
Iterate the vectors along the path. Return LUA style 1 based indexes for the path points.
===================================================
_patrol -> table: _patrol
- John "Nielk1" Klein
- Janne Trollebø
BZ98R LUA Extended API Patrol Engine.
Patrol Engine
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----Creates a new PatrolEngine instance.
===================================================
_producer -> table: _producer
- John "Nielk1" Klein
BZ98R LUA Extended API Producer.
Queues the building of objects by producers.
The event data to be fired with the creation event.
Called when a producer as completed building an object.
Object to build.
Location to build the object if from an armory or constructor.
Event data to be fired with the creation event.
A table mapping teams (0–15) to ProductionQueue lists. This should be scanned every update if any producers are not busy to look for work for said producer. Consider this a priority queue, even though right now it's just a normal queue. Note that price is not a good reason to skip something, instead it should inject a block event into that build queue unless it's deemed impossible to get that much scrap.
The ODF of the object to be built.
The location where the object should be built, or "0 0 0" if not specified.
The producer that will build the object.
TYPE: UNK_any
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----The event data to be fired with the creation event.
TYPE: UNK_ProducerData
TYPE: UNK_ProducerData?
TYPE: nil
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----TYPE: UNK_GameObject
TYPE: UNK_GameObject?
TYPE: nil
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----GameObject An object containing all functions and data related to a game object.
===================================================
_requirefix
- John "Nielk1" Klein
BZ98R LUA Extended API Require Fix.
Repairs lua loader to look in mod paths for DLL or LUA modules with names longer than 15 characters.
require("_requirefix").addmod("12345").addmod("67890");
require("_requirefix").addmod("12345");
require("_requirefix").addmod("67890");
===================================================
_statemachine -> table: _statemachine
- John "Nielk1" Klein
BZ98R LUA Extended API StateMachineIter.
State Machine and State Machine Iterator for serial event sequences across game turns.
local statemachine = require("_statemachine");
statemachine.Create("TestMachine",
{
["state_a"] = function(state)
print("test " .. state.test1);
state:switch("state_b");
end,
["state_b"] = statemachine.SleepSeconds(10,"state_c"),
["state_c"] = function(state)
print("test " .. state.test2);
state:switch("state_d");
end,
["state_d"] = statemachine.SleepSeconds(15,"state_e"),
["state_e"] = function(state)
print("test " .. state.test3);
state:switch("state_f");
end
});
-- ordered state machine that supports state:next()
statemachine.Create("OrderedTestMachine",
{
-- named state function
{ "state_a", function(state)
print("test " .. state.test1);
state:switch("state_b");
end },
-- named magic state function (SleepSeconds)
-- note nil next_state means next state by index
{ "state_b", statemachine.SleepSeconds(10) },
-- named state function with automatic name
{ nil, function(state)
print("test " .. state.test2);
state:switch("state_d");
end },
-- named state function with automatic name
{ function(state)
print("test " .. state.test2);
state:switch("state_d");
end },
-- magic state function (SleepSeconds)
statemachine.SleepSeconds(15,"nonexistent_state"),
-- stsate function with automatic name
function(state)
print("test " .. state.test3);
state:next();
end
});
hook.Add("InitialSetup", "Custom_InitialSetup", function(turn)
MissionData.TestSMI1 = statemachine.Start("TestMachine","state_a",{test1='d',test2="e",test3="f"});
MissionData.TestSMI2 = statemachine.Start("OrderedTestMachine","state_a",{test1='d',test2="e",test3="f"});
end);
hook.Add("Update", "Custom_Update", function(turn)
MissionData.TestSMI1:run();
MissionData.TestSMI2:run();
end);
An object containing all functions and data related to an StateMachineIter.
Current state, string name or integer index if state machine is ordered
StateMachineIter template name
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----StateMachineIter index to name mapping, only if the StateMachineIter is ordered
Timer's value, nil for not set
Target time if sleeping, nil if not set
Time to wait before running next state, kept to allow altering target_time if set_wait_time changes
TYPE: nil
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----Table of values embeded in the StateMachineIter
GameObject.__index = GameObject; -- failed table lookups on the instances should fallback to the class table, to get methods
Arguments to pass to the state function
True if the state function was called, false if the state function was not found, a wrapper instance if the state function was called and returned a wrapper
The return value of the state function, if it was called. If the result was wrapped it's unwraped and returned here
Run StateMachineIter.
Next StateMachineIter State. This only works if the StateMachineIter is ordered.
State to switch to (will also accept state index if the StateMachineIter is ordered)
Switch StateMachineIter State.
How many seconds to wait
If true the timer will still return true when the time has passed, but will "lap" instead of "stop" and keep counting.
If true the timer returns true when it starts, requires lap to be true.
True if the time is up
Check if a set period of time has passed. This first time this is called the target time is latched in until true is returned. Ensure you call state:SecondsHavePassed() or state:SecondsHavePassed(nil) to clear the timer if it did not return true and you need to move on.
Save event function.
@param self StateMachineIter instance @return template string StateMachineIter template name @return target_call integer? Timer's value, nil for not set @return target_time number? TargetTurn's value, nil for not set @return set_wait_time number? Time to wait before running next state, kept to allow altering target_time if set_wait_time changes @return state_key string|integer|nil Current state, string name or integer index if state machine is ordered @return addonData table Addon data, if any
StateMachineIter template name
Timer's value, nil for not set
TargetTurn's value, nil for not set
Time to wait before running next state, kept to allow altering target_time if set_wait_time changes
Current state, string name or integer index if state machine is ordered
Addon data, if any
Load event function.
@param template string StateMachineIter template name @param target_call integer? Timer's value, nil for not set @param target_time number? TargetTurn's value, nil for not set @param set_wait_time number? Time to wait before running next state, kept to allow altering target_time if set_wait_time changes @param state_key string|integer|nil Current state, string name or integer index if state machine is ordered @param addonData table Addon data, if any
TypeLoad event function.
If true the machine should be considered aborted, allowing for cleanup
If true the machine will attempt to run the next state immediately
Simple construct for a state function with a name
name
State function
A truncated version without the name, name is constructed at runtime from index
State function
A simple ordered set of states
State function
A simple name-only set of states
State function
Game time in seconds, used for state machine timing
Table of StateMachineIter instances, key is the template name and value is the StateMachineIter instance
Table of flags for each StateMachineIter template, key is the template name and value is the flags table
Return values passed from hook function
Create an Abort HookResult
Object in question
Is this object an instance of StateMachineIter?
Name of the StateMachineIter Template (string)
State descriptor and/or state descriptor collections, can be a table of named state functions or an array of state descriptors.
Creates an StateMachineIter Template with the given indentifier.
State descriptors are tables with the first element being the state name and the second element being the state function.
If the second element is nil, the first element is considered the state function and the state name is generated automatically.
If the state descriptor is instead a function it is treated as a nil state and the state name is generated automatically.
The first paramater of the state function is the StateMachineIter itself where the current state may be accessed via self.state_key
.
Name of the StateMachineIter Template
Initial state, if nil the first state will be used if the StateMachineIter is ordered, can be an integer is the StateMachineIter is ordered
Initial data
Starts an StateMachineIter based on the StateMachineIter Template with the given indentifier.
How many calls to wait
Next state when timer hits zero
Function to check if the state should be exited early, return false, true, or next state name
Wait a set period of time on this state.
How many seconds to wait
Next state when timer hits zero, nil is auto-next for an ordered machine
Function to check if the state should be exited early, return false, true, or next state name
Wait a set period of time on this state.
Early exit function for state machine iterators, if a string or integer is returned it is the next state
===================================================
_stateset -> table: _stateset
- John "Nielk1" Klein
BZ98R LUA Extended API StateSetRunner.
Simplistic system to run multiple functions or "states" in a single call. The main use case of this is to hold multiple toggelable objectives. If you want to do something more complex, use the hook module instead. Like most similar constructs State Set Runners have internal data storage and can be saved and loaded.
local stateset = require("_stateset");
stateset.Create("TestSet")
:Add("state_a", function(runner, a, b)
print("test " .. runner.test1 .. " " .. tostring(a) .. " " .. tostring(b));
end)
:Add("state_a", function(runner, a, b)
print("test " .. runner.test2 .. " " .. tostring(a) .. " " .. tostring(b));
end, true);
hook.Add("InitialSetup", "Custom_InitialSetup", function(turn)
MissionData.TestSet = statemachine.Start("TestSet",{test1='d',test2="e");
MissionData.TestSet:on("state_a"); -- state true
MissionData.TestSet:on("state_b"); -- state 1
MissionData.TestSet:on("state_b"); -- state 2
MissionData.TestSet:off("state_b"); -- state 1, still on as this is a permit based state
end);
hook.Add("Update", "Custom_Update", function(turn)
MissionData.TestSMI:run(1, 2);
end);
Name of the StateSet template
TYPE: UNK_StateSet
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----Name of the state
Function to be called when the state is active, should return true if the state did something.
If true, the state is permit based
Add a state to the StateSet. If the state is basic either active or inactive based on last on/off call. If the state is permit based it is active if the on count is greater than 0.
An object containing all functions and data related to an StateSetRunner.
Name of the StateSet template the runner is using
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----Table of active states, key is the state name and value is the state activation flag or permit count
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----Custom context data stored in the StateSetRunner
Arguments to pass to the state function
if at least one state was found and executed and returned true
Run StateSetRunner.
Name of the state
Set state on.
Name of the state
If true, the state is set off regardless of the current permits
Set state off.
Save event function.
@param self StateSetRunner instance @return ...
Load event function.
@param template @param active_states @param addonData
Name of the StateSet template the runner is using
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----Table of active states, key is the state name and value is the state activation flag or permit count
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----Custom context data stored in the StateSetRunner
Optional table of StateMachineIter instances used by this StateSetRunner
if at least one state was found and executed and returned true
Run StateSetRunner.
Name of the state
Set state on.
Name of the state
If true, the state is set off regardless of the current permits
Set state off.
An object containing all functions and data related to an StateSetRunner.
Save event function.
@param self StateSetRunner instance @return ...
Load event function.
@param template @param active_states @param addonData
Table of StateSet instances, key is the template name and value is the StateSet instance
Name of the StateMachineIter Template
Initial state, if nil the first state will be used if the StateMachineIter is ordered, can be an integer is the StateMachineIter is ordered
Initial data
Wrap a state machine definition so it can be used in a StateSet.
The StateMachineIter's instance is stored in the machines
table of the StateSetRunner instance, key is the state name.
Object in question
Is this object an instance of StateSetRunner?
Name of the StateSetRunner Template
Creates an StateSetRunner Template with the given indentifier.
Name of the StateSetRunner Template
Initial data
Starts an StateSetRunner based on the StateSetRunner Template with the given indentifier.
===================================================
_table_show
- Julio Manuel Fernandez-Diaz
BZ98R LUA Extended API table to string. Converts table to string representation.
January 12, 2007 (For Lua 5.1)
Modified slightly by RiciLake to avoid the unnecessary table traversal in tablecount().
Modified slightly by John "Nielk1" Klein for Lua Language Server.
Convert table to string representation.
Heavily based on "Saving tables with cycles", PIL2, p. 113.
Formats tables with cycles recursively to any depth. The output is returned as a string. References to other tables are shown as values. Self references are indicated.
The string returned is "Lua code", which can be procesed (in the case in which indent is composed by spaces or "--").
Userdata and function keys and values are shown as strings, which logically are exactly not equivalent to the original code.
print(table.show(t, "t")) -- a typical use
===================================================
_tracker -> table: _tracker
- John "Nielk1" Klein
BZ98R LUA Extended API Tracker.
Tracks objects by class and odf.
local tracker = require("_tracker");
-- if no filters are set all objects will be tracked
tracker.setFilterTeam(1, true);
tracker.setFilterClass("TANK", true);
ClassSig name to count.
Team number to count for.
Count object by ClassSig @todo add protections
ClassName name to count.
Team number to count for.
Count object by ClassName @todo add protections
Odf name to count.
Team number to count for.
Count object by class @todo add protections
Team number to track.
Enable or disable tracking for the team. Defaults to true.
Enable tracking for a team. Note that items that no longer fit the filter will remain in the tracker. Note that on the next update if needed an AllObjects scan will be performed to update the tracker for new filtered items.
Enable or disable tracking for the class. Defaults to true.
Enable tracking for a class. Note that items that no longer fit the filter will remain in the tracker. Note that on the next update if needed an AllObjects scan will be performed to update the tracker for new filtered items. Note that the odf and class filters are independent, so if you set a class filter to true and an odf filter to false, the class will be tracked but the odf will not.
Odf name to track.
Enable or disable tracking for the odf. Defaults to true.
Enable tracking for an odf. Note that items that no longer fit the filter will remain in the tracker. Note that on the next update if needed an AllObjects scan will be performed to update the tracker for new filtered items. Note that the odf and class filters are independent, so if you set a class filter to true and an odf filter to false, the class will be tracked but the odf will not.
===================================================
_utility -> table: _utility
- John "Nielk1" Klein
BZ98R LUA Extended API Utility.
TYPE: UNK_any
SPECIAL: inner_type
GLYPH: bi bi-question-circle
----The item to be chosen.
The weight of the item.
TeamSlotRanges
Get the ClassLabel string for any ClassSig or ClassLabel.
Get the ClassSig string for any ClassLabel or ClassSig.
Object in question
Is this object a function?
Object in question
Is this object a table?
Object in question
Is this object a string?
Object in question
Is this object a boolean?
Object in question
Is this object a number?
Object in question
Is this object an integer?
Object in question
Is this object a Handle?
Object in question
Is this object a Vector?
Object in question
Is this object a Matrix?
The items to choose from.
The chosen item.
Chooses a random item from a list of items.
Chooses a random item from a list of weighted items.
The iterator to convert
The resulting array or table
Convert an iterator to an array or table. If the iterator returns only values, returns an array. If the iterator returns key-value pairs, returns a table.
TeamSlotStrings
TeamSlotIntegers
ClassLabels
compatability
compatability
compatability
ClassSigs
TeamSlotRange
===================================================
_version -> table: _version
- John "Nielk1" Klein
BZ98R LUA Extended API Version Utility.
The game version, e.g. "2.2.315"
The Lua version, e.g. "Lua 5.1"
The version of this LUA Extended API, e.g. "0.1.1"
The BZCP version, if available, e.g. "0.3"
The BZCP shim version, if available, e.g. 1
function iterating over all versions for easy output
Iterate all versions in a simple format. This function returns an iterator that yields key, label, and version for each version token.
local version = require("_version");
print("Versions:")
for _,l,v in version.All() do
if v then
print(" " .. l .. ": " .. tostring(v));
else
print(" " .. l .. ": ????");
end
end
The first version string
The second version string
depending on the comparison result
Compare two version strings.
This function compares two version strings in the format d
, d.d
, d.d.d
, d.d.d.d
, d.d.d.da
, and d.d.d.dad
where d is a digit and a is an alphanumeric character.
It returns -1 if version1 is less than version2, 1 if version1 is greater than version2, and 0 if they are equal.
===================================================
_waves -> table: _waves
- John "Nielk1" Klein
- Janne Trollebø
BZ98R LUA Extended API Wave Spawner.
Wave Spawner
The name of the wave spawner.
Called when a wave spawner has spawned a wave.
The name of the wave spawner. "WaveSpawner:Spawned" event fired
The frequency of waves.
The variance of wave frequency.
The time to wait before the next wave.
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----OLD: A list of factions from which a random will be selected.
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----OLD: A list of locations where waves can spawn, considered if the name is not the same as a faction name, or it is the same as a selected faction.
TYPE: table
SPECIAL: inner_type
GLYPH: bi bi-table
----OLD: Array of weighted formation tables
The number of waves left to spawn.
Checks if the WaveSpawner is alive. (Has waves left to spawn)
Saves the WaveSpawner state.
Loads the WaveSpawner state.
Array of strings, each string is a row, numbers are unit indices in 'units'
List of unit ODFs, indexed by number in formation
Distance between units (optional, default 10)
Spawns units in a specified formation at a location, facing a direction.
Creates a new WaveSpawner instance.