Skip to content
Tomasz Bachmiński edited this page May 10, 2019 · 18 revisions

Table of Contents


modApi

modApi:deltaTime

Returns time between frames in milliseconds. For 60 FPS, this is 16ms. For 30 FPS, this is 33ms.


modApi:elapsedTime

Returns the amount of time that has passed since the game has been launched, in milliseconds.


modApi:scheduleHook

Argument name Type Description
msTime number Time in which the function is to be invoked, in milliseconds. Measured from the moment this function is called
fn function Argumentless function which will be invoked when the amount of time specified in the first argument has elapsed.

Schedules a function to be invoked at a later time. This can be used to perform delayed operations, mostly related to UI or mod management, or as a way to work around some hooks' limitations.

Keep in mind that these hooks are not retained when the player exits the game, so hooks scheduled to happen in a long time (like a minute) may end up never being executed if the player quits the game in the meantime.

Example:

LOG("This message is printed right away!")

modApi:scheduleHook(1000, function()
	LOG("This message is printed a second later!")
end)

modApi:conditionalHook

Argument name Type Description
conditionFn function Argumentless predicate function evaluated once every frame
fn function Argumentless function which will be invoked when the function specified by conditionFn argument returns true.
remove boolean Whether the hook should be removed once it is triggered. Defaults to true if omitted.

Registers a conditional hook which will be executed once the condition function associated with it returns true. By default, the hook is removed once it is triggered.

Example:

-- This hook gets fired when a Combat Mech is selected
modApi:conditionalHook(
	function()
		return Pawn and Pawn:GetType() == "PunchMech"
	end,
	function()
		LOG("Punch mech selected")
	end
)

modApi:runLater

Argument name Type Description
fn function Argumentless function which will be invoked on game's next update step.

Executes the function on the game's next update step. Only works during missions.

Calling this during game loop (either in a function called from missionUpdate, missionUpdateHook, or as a result of previous runLater) will correctly schedule the function to be invoked during the next update step (not the current one).

Example:

local pawn = Board:GetPawn(Point(0, 0))

local d = SpaceDamage(Point(0, 0))
d.iFire = EFFECT_CREATE
Board:DamageSpace(d)

LOG(pawn:IsFire()) -- prints false, the tile's Fire status was
                   -- not applied to the pawn yet (this happens
                   -- during the game's update step)

modApi:runLater(function()
	LOG(pawn:IsFire()) -- prints true, the game already went
	                   -- through its update step and applied
	                   -- the Fire status to the pawn
end)

modApi:splitString

Argument name Type Description
input string The string to be split
separator string The string to split by. Defaults to whitespace if omitted

Splits the input string around the provided separator string, and returns a table holding the split string. Does not include empty strings.


modApi:splitStringEmpty

Argument name Type Description
input string The string to be split
separator string The string to split by. Defaults to whitespace if omitted

Splits the input string around the provided separator string, and returns a table holding the split string. Includes empty strings.


modApi:trimString

Argument name Type Description
input string The string to be trimmed

Trims leading and trailing whitespace from the string.

Example:

LOG(modApi:trimString("   some text !   ")) -- prints 'some text !'

modApi:stringStartsWith

Argument name Type Description
input string The string to test
prefix string The prefix string that the input string should be starting with

Returns true if the input string starts with the prefix string.

Example:

local string = "PunchMech"
if modApi:stringStartsWith(string, "Punch") then
	LOG("It does")
end

modApi:stringEndsWith

Argument name Type Description
input string The string to test
suffix string The suffix string that the input string should be ending with

Returns true if the input string ends with the suffix string.

Example:

local string = "PunchMech"
if modApi:stringEndsWith(string, "Mech") then
	LOG("It does")
end

modApi:isVersion

Argument name Type Description
version string Version to test
comparedTo string Version to compare the first argument to. Defaults to mod loader's version if omitted.

Returns true if version argument is less than or equal to comparedTo. False otherwise.

Example:

if modApi:isVersion("2.1.1") then
	LOG("Mod loader is version 2.1.1 or higher.")
end

-- ...

someModVersion = "1.2"
if modApi:isVersion("1.1", someModVersion) then
	LOG("someMod is version 1.1 or higher, we can use stuff added in this version")
else
	LOG("Whoops, someMod is lower version than 1.1, we need to use some compatibility fall-back plan, or we just fail to load.")
end

modApi:addGenerationOption

Argument name Type Description
id string Identifier for the option
name string Name of the option that will be shown to the player
tip string Tooltip text shown when hovering over this option. Can be nil.
data table Table describing the option. Defaults to a checkbox option if omitted.

Adds a new configuration option to the mod that is currently being initialized by the mod loader.

Example:

local function init(self)
	modApi:addGenerationOption(
		"someCheckbox",
		"Some Checkbox Option",
		"This is a checkbox option that can be switched on and off. It is unchecked by default.",
		{ enabled = false }
	)

	modApi:addGenerationOption(
		"someCheckbox2",
		"Another Checkbox Option",
		"This is a checkbox option that can be switched on and off. It is checked by default.",
		{}
	)

	modApi:addGenerationOption(
		"someDropdown",
		"Some Dropdown Option",
		"This is a dropdown in which the user can select one of multiple values.",
		{
			-- Internal values of the options
			values = { 1, 2, "a string", true },

			-- Names of the options that will be shown to the player.
			-- Defaults to a string representation of the entry from `values` table
			-- if there's no entry in the `strings` table at the corresponding index.
			strings = { "Option 1", "Option 2", "Option 3", "Option 4" },

			-- The value that is selected by default.
			-- Defaults to the first entry in the `values` table if omitted.
			value = "a string"
		}
	)
end

local function load(self, options, version)
	if options["someCheckbox"].enabled then
		LOG("Some Checkbox Option is checked")
	end

	if options["someCheckbox2"].enabled then
		LOG("Another Checkbox Option is checked")
	end

	LOG("Selected multivalue option: " .. options["someDropdown"].value)
end

modApi:writeAsset

Argument name Type Description
resource string Path inside resource.dat where your asset should be placed. Use forward slahes (/).
content string String content to be written to the file

Writes a file with the specified content to the resource.dat archive, either creating a new file or overwriting one if it already exists. All calls to this function must be inside your mod's init function.


modApi:readAsset

Argument name Type Description
resource string Path inside resource.dat where your asset should be placed. Use forward slahes (/).

Reads the specified file from the resource.dat archive, and returns its contents as a string. Throws an error if the file could not be found. All calls to this function must be inside your mod's init function.

Example:

modApi:readAsset("img/units/player/mech_punch.png")

modApi:appendAsset

Argument name Type Description
resource string Path inside resource.dat where your asset should be placed. Use forward slahes (/).
filePath string Path to the asset in local filesystem. A common practice is to prepend self.resourcePath (which is the root directory of your mod) to the path.

Adds an asset (image or font) to the game (by putting it into resources/resource.dat file). All calls to this function must be inside your mod's init function.

Example:

modApi:appendAsset("img/weapons/Whip.png",self.resourcePath.."/weapons/Whip.png")

modApi:copyAsset

Argument name Type Description
src string Path inside resource.dat, specifying the file to be copied. Use forward slahes (/).
dst string Path inside resource.dat, specifying the destination the file will be copied to.

Copies an existing asset within the resource.dat archive to another path within the resource.dat archive. Can overwrite existing files. All calls to this function must be inside your mod's init function.

Example:

-- replaces reactor core image with The Button
modApi:copyAsset("img/weapons/support_destruct.png", "img/weapons/reactor_core.png")

modApi:addSquad

Argument name Type Description
squad table A table with 4 values - text identifier of the squad, followed by three mech text identifiers. Each mech mentioned must exist as a global variable, created similarly to game's mechs in pawns.lua file.
name string Name of the squad displayed to user.
desc string Description of the squad displayed to user.
icon string Icon used in custom squad selection UI.

Adds a new squad to the game.

Example:

modApi:addSquad(
    { "Chess Squad", "AUTO_King", "AUTO_Knight", "AUTO_Rook" },
    "Chess Squad",
    "Chess piece themed mechs.",
    self.resourcePath.."/icon.png"
)

modApi:overwriteText

Argument name Type Description
id string Identifier of the text to be replaced
text string New text

modApi:addWeapon_Texts

Argument name Type Description
tbl table Table with as many key-value string pairs as you need.

Registers strings related to weapons with the game.

Weapons you create in mods are stored in global variables, and you use names of those variables to equip pawns. For every weapon, the game requires some strings to be defined, or can misbehave, or even crash. If a weapon is stored in vartable WeaponName, the game expects strings WeaponName_Name and WeaponName_Description to be registered. If a weapon has one upgrade, WeaponName_Upgrade1 and WeaponName_A_UpgradeDescription must be registered, and with two upgrades, the game requires two more strings: WeaponName_Upgrade2 and WeaponName_B_UpgradeDescription. The description for each string is in the table below.

String Description
WeaponName_Name Name of the weapon displayed to user.
WeaponName_Description Description of the weapon displayed to user.
WeaponName_Upgrade1 Short description of the first upgrade. Make it less than about 12 characters, or it won't fit
WeaponName_A_UpgradeDescription Long description of the first upgrade.
WeaponName_Upgrade2 Short description of the second upgrade. Same restrictions apply.
WeaponName_B_UpgradeDescription Long description of the second upgrade.

Example:

modApi:addWeapon_Texts({
	AUTO_Rook_Cannon_Name = "Cross Cannons",
	AUTO_Rook_Cannon_Description = "Fires a projectile in all 4 directions, damaging and pushing on impact.",
	AUTO_Rook_Cannon_Upgrade1 = "Directional",
	AUTO_Rook_Cannon_A_UpgradeDescription = "Fire in three directions instead of four, with increased damage in one direction. Pushes self in the remaining direction.",
	AUTO_Rook_Cannon_Upgrade2 = "+1 Damage",
	AUTO_Rook_Cannon_B_UpgradeDescription = "Increases damage dealt by 1.",
	
	AUTO_Knight_Move_Name = "Knight Smite",
	AUTO_Knight_Move_Description = "Jumps to a location, killing any unit unfortunate enough to be there.",
})

A possibly more convenient way to use this function is to put all your weapon strings into a single file, text_weapons.lua:

return {
	AUTO_Rook_Cannon_Name = "Cross Cannons",
	AUTO_Rook_Cannon_Description = "Fires a projectile in all 4 directions, damaging and pushing on impact.",
	AUTO_Rook_Cannon_Upgrade1 = "Directional",
	AUTO_Rook_Cannon_A_UpgradeDescription = "Fire in three directions instead of four, with increased damage in one direction. Pushes self in the remaining direction.",
	AUTO_Rook_Cannon_Upgrade2 = "+1 Damage",
	AUTO_Rook_Cannon_B_UpgradeDescription = "Increases damage dealt by 1.",
	
	AUTO_Knight_Move_Name = "Knight Smite",
	AUTO_Knight_Move_Description = "Jumps to a location, killing any unit unfortunate enough to be there.",
}

And then add them to the game using:

modApi:addWeapon_Texts(require(self.scriptPath.."text_weapons"))

modApi:addPopEvent

Argument name Type Description
event string Event id, text identifier specifying which exactly event is being extended. Possible values for event are: "Opening", "Closing", "Closing_Dead", "Closing_Perfect", "Closing_Bad", "Threatened", "Killed", "Shielded", "Frozen"
msg string Text displayed to user. Inside the string, #squad and #corp can be used to refer to current squad name and coropration name respectively.

Registers PopEvent, the text shown near cities when certain actions happen ("The mechs are here, we're saved!", "Get away from the windows!").


modApi:setPopEventOdds

Argument name Type Description
event string Event id
msg number A number from 0 to 100 indicating the probability of the PopEvent happening.

Sets the probability of the PopEvent occuring.


modApi:addOnPopEvent

Argument name Type Description
fn function Function to be called when the event occurs.

Registers the function to be called when a PopEvent occurs. This function is called with 5 arguments, once for each text in the PopEvent.

Arguments to the function are:

Argument name Type Description
text string The text to be displayed to user.
texts table List of all texts registered for that event (and the first argumkent is one of them).
i number index of text in texts list.
event string Event id.
count number How many texts the game is expecting.

The function should modify (or leave as it is) and return its first argument - the text displayed to user.

Example:

function modApi:addOnPopEvent(function(text, texts, i, event, count)
    return text.."!!!"
end)

modApi:addMap

Argument name Type Description
mapPath string Path to the map file.

Copies the specified map to the game's maps/ directory. Cannot overwrite default (vanilla) maps. Call in your mod's init() function.

This function ignores the file's parent directories, and only takes the filename into consideration. some/long/path/to/mymap.map and path/mymap.map will both be copied to maps/mymap.map.

Example:

local function init(self)
	modApi:addMap(self.resourcePath .. "maps/somemap.map")
end

modApi:loadIntoEnv

Argument name Type Description
path string Path to the file to load.
envTable table The environment the file will be loaded to. Will hold all global variables the file defines. Can be omitted, defaulting to an empty table.

Loads the specified file, loading any global variable definitions into the specified table instead of the global namespace (_G). The file can still access variables defined in _G, but not write to them by default (unless specifically doing _G.foo = bar).

Return value of the loaded file is ignored by this function.

Example:

local env = modApi:loadIntoEnv("some/file.lua")
GlobalVar = env.var1       -- this variable will be accessible globally
local localVar = env.var2  -- this variable will not

modApi:loadSettings

Reloads the settings file to have access to selected settings from in-game lua scripts. Generally you shouldn't have to call this, the mod loader reloads the file on its own and stores the result in global Settings table.

If you need to be notified when settings change, see settingsChangedHook.

Example:

local settings = modApi:loadSettings()

modApi:loadProfile

Reloads profile data of the currently selected profile. Generally you shouldn't have to call this, the mod loader reloads the profile data on its own and stores the result in global Profile table.

Example:

local profile = modApi:loadProfile()

modApi:writeProfileData

Argument name Type Description
id string Key the data will be saved as in the modded profile table
obj object A lua object to store in the modded profile table

Stores the specified object under the specified key in modcontent.lua file in the currently selected profile's directory.

Example:

local diff = GetDifficulty()
modApi:writeProfileData("CustomDifficulty", level)

modApi:readProfileData

Argument name Type Description
id string Key of the data to be retrieved from the modded profile table

Reads the object under the specified key from modcontent.lua file in the currently selected profile's directory.

Example:

local diff = modApi:readProfileData("CustomDifficulty")

modApi:writeModData

Argument name Type Description
id string Key the data will be saved as in the modded settings table
obj object A lua object to store in the modded settings table

Stores the specified object under the specified key in modcontent.lua file in game's savedata directory.

Example:

local diff = GetDifficulty()
modApi:writeModData("CustomDifficulty", level)

modApi:readModData

Argument name Type Description
id string Key the data will be saved as in the modded settings table

Reads the object under the specified key from modcontent.lua file in game's savedata directory.

Example:

local diff = modApi:readModData("CustomDifficulty")
Clone this wiki locally