Desynced Lua API

Modules

Module: Action

The action module contains functions that send (player input) actions

Source: /Source/Desynced/Lua/Module/DSActionModule.cpp

SendForLocalFaction (Action Function)

Send an action from the local player faction
A faction action can be registered with
function FactionAction.ACTIONID(faction, arg)

Example:

SendForEntity (Action Function)

Send an action for an entity owned by the local player faction
An entity action can be registered with
function EntityAction.ACTIONID(entity, arg)

Example:

SendForSelectedEntities (Action Function)

Send a grouped entity action for all selected entities
Will automatically filter out construction sites and entities not owned by the local player faction

Example:

SendForEntities (Action Function)

Send a grouped entity action for a list of entities
Will automatically filter out construction sites and entities not owned by the local player faction

Example:

SendForConstruction (Action Function)

Send an action for a construction entity owned by the local player faction
A construction action can be registered with
function ConstructionAction.ACTIONID(entity, arg)

Example:

SendFromPlayer (Action Function)

Send an action from the player
A player action can be registered with
function PlayerAction.ACTIONID(player_id, faction, arg)

Example:

RunUI (Action Function)

Run code in UI context for the player that initiated the currently executing action
Must be called while executing an action and will execute for the one player that sent the action (to limit to other players use faction:RunUI or UI.Run)

Example:

SetPlayerReady (Action Function)

Set player ready during the startup of a scenario using DelayedPlayerFactionSpawn mode

Example:

IsReplayPlayback (Action Function)

Returns if a replay is being played back

Example:

GetReplayProgress (Action Function)

Returns the playback progress of the replay

Example:

GetReplayDuration (Action Function)

Returns the total duration of the replay

Example:

SetReplaySpeed (Action Function)

Set replay playback speed

Example:

SetReplayViewFaction (Action Function)

Set replay viewed faction

Example:

RestartReplay (Action Function)

Restart replay

Example:

ReplayPlayFromHere (Action Function)

While playing a replay, stop the replay and continue playing from here

Example:

Module: Debug

The debug module contains debug functions

Source: /Source/Desynced/Lua/Module/DSDebugModule.cpp

Assert (Debug Function)

Assert a condition during automated tests and data validation

Example:

EndTest (Debug Function)

Ending an automated test scenario

Example:

PrintCallStack (Debug Function)

Print the current call stack

Example:

GetStats (Debug Function)

Get lua internal memory stats

Example:

GetMapStateHash (Debug Function)

Get a hash of the entire map state

Example:

SetMemoryTracking (Debug Function)

Start or stop tracking of all LUA memory allocations
Will log all new allocations that have not been freed between starting and stopping.

Example:

Benchmark (Debug Function)

Time some code

Example:

CrashProgram (Debug Function)

Crash the program (only works in mod development mode)

Example:

Reload (Debug Function)

Reload Lua code (only works in mod development mode and only while not playing multiplayer)

Example:

AllowDebuggerInMultiplayer (Debug Function)

Enable the LUA debugger server even while playing multiplayer

Example:

Module: Game

The game module contains global functions

Source: /Source/Desynced/Lua/Module/DSGameModule.cpp

NewGame (Game Function)

Start a new game

Example:

RestartGame (Game Function)

Restart the current scenario with the same game settings

Example:

EndGame (Game Function)

End the current game and return to the main menu

Example:

QuitGame (Game Function)

Quit the game to desktop

Example:

OfflinePause (Game Function)

Pauses the game (is only effective while playing without multiplayer)
If called multiple times with true, needs to be called equal amounts with false.

Example:

GetModPackage (Game Function)

Get a loaded mod package

Example:

GetModPackages (Game Function)

Get all currently active mod packages

Example:

GetScenarioModPackage (Game Function)

Get the mod package of the currently running scenario

Example:

GetInstalledMods (Game Function)

Get meta data of all installed mods

Example:

GetInstalledModPackages (Game Function)

Get meta data of all packages from an installed mod

Example:

GetInstalledModPackage (Game Function)

Get meta data of one package and its mod

Example:

SetModEnabled (Game Function)

Set a mods enabled state
Will be applied when the next map starts.

Example:

RefreshInstalledMods (Game Function)

Refresh the list of installed mods and call mod change callbacks
UIOnModAdded with parameters id, name for newly added mods
UIOnModRemoved with parameters id, name for removed mods

Example:

GetNativeModManagerName (Game Function)

Get the name of the mod management system of this platform

Example:

OpenNativeModManager (Game Function)

Open the native the mod management system of this platform (if available)

Example:

GetCommandLineArguments (Game Function)

Get command line arguments

Example:

SaveGame (Game Function)

Save save game

Example:

LoadGame (Game Function)

Load save game

Example:

ReplayGame (Game Function)

Play save game replay

Example:

DeleteGame (Game Function)

Delete save game

Example:

RenameGame (Game Function)

Rename save game

Example:

GetSaveGameList (Game Function)

Get the list of all save games

Example:

GetSaveGameModPackages (Game Function)

Get list of mod packages that were in use when the save game was created.
Besides the basic fields (id, name, mod_id, mod_name, mod_version_code) the info table can contain the following flags:
- is_scenario: Set on the package that is the scenario
- error_missing: Set if the mod or package is now missing
- error_dependencies: Set if the mod now has missing dependencies
- error_version: Set if the save was made with a newer mod version than installed
- now_disabled: Set if the save was made with an addon that is now disabled or has any of the errors above
- now_enabled: Set if the save was made with an addon that has since been enabled
The tables in the resulting array can optionally have error flags 'error_missing' or 'error_version' set.

Example:

IsSaveGameOldVersion (Game Function)

Check if save was made with older version of the game with which a new save won't be forward compatible with.
This checks both mod versions as well as the game internal save version number.

Example:

HaveAnySaveGame (Game Function)

Get if any save game exists

Example:

GetAutoSaveTime (Game Function)

Get auto save time setting

Example:

SetAutoSaveTime (Game Function)

Set auto save time setting

Example:

GetMouseLock (Game Function)

Get lock mouse option

Example:

SetMouseLock (Game Function)

Set lock mouse option

Example:

GetDragScrolling (Game Function)

Get drag scrolling option

Example:

SetDragScrolling (Game Function)

Set drag scrolling option

Example:

GetEdgeScrolling (Game Function)

Get edge scrolling option

Example:

SetEdgeScrolling (Game Function)

Set edge scrolling option

Example:

GetScrollSpeed (Game Function)

Get scroll speed setting

Example:

SetScrollSpeed (Game Function)

Set scroll speed setting

Example:

GetGameDuration (Game Function)

Get the play time

Example:

GetTimeSinceSave (Game Function)

Get the time that passed since the map was last saved

Example:

GetVersionString (Game Function)

Get the game version

Example:

GetLocalPlayerFaction (Game Function)

Get the local player faction

Example:

GetLocalPlayerExtra (Game Function)

Get the local player extra data
If called without argument from a mod other than 'Main', will return a mod specific child table parent.mods[mod_id]
If called with an empty string or nil, will always return entire parent table

Example:

GetProfile (Game Function)

Get the local profile table
If called without argument from a mod other than 'Main', will return a mod specific child table parent.mods[mod_id]
If called with an empty string or nil, will always return entire parent table

Example:

SetColorMapping (Game Function)

Change the color mapping mode

Example:

GetMappedColor (Game Function)

Convert a color according to the color mapping

Example:

CreateOnlineSession (Game Function)

Create an online session

Example:

FindOnlineSessions (Game Function)

Create an online session

Example:

JoinOnlineSession (Game Function)

Join an online session

Example:

EndOnlineSession (Game Function)

End online session (stop server or go back to title on client)

Example:

OnlineHaveLobbies (Game Function)

Returns if online lobbies are available and sessions can be created with visibility PUBLIC/FRIENDS/INVITE

Example:

CanInviteFriend (Game Function)

Returns if friend inviting is available

Example:

ShowFriendInviteUI (Game Function)

Show the friend invite UI to invite them to the current session

Example:

GetNetMode (Game Function)

Get the current network mode

Example:

GetAllPlayers (Game Function)

Get a table of all connected multiplayer players

Example:

GetPlayerById (Game Function)

Get a connected player by id

Example:

GetLocalPlayer (Game Function)

Get player details of the local player

Example:

GetLocalPlayerId (Game Function)

Get player id of the local player

Example:

GetPlayerName (Game Function)

Get the name of a connected player

Example:

IsHostPlayer (Game Function)

Check if a given player id belongs to the host player

Example:

IsLocalPlayer (Game Function)

Check if a given player id belongs to the local player

Example:

KickPlayer (Game Function)

Kick a player from the server (only available to the host of a locally running session)

Example:

GetPlayerCount (Game Function)

Get the number of connected players
Will be 1 in single player, and 0 on a dedicated server without anyone connected

Example:

GetMaxPlayerCount (Game Function)

Get the maximum number of multiplayer players (or 1 if offline)

Example:

GetMultiplayerSession (Game Function)

Get information about the current multiplayer session (returns nil if there is no session)

Example:

GetHostSessionSettings (Game Function)

Get the session settings used to start hosting the session. Only the host can use this.

Example:

ModifyHostSessionSettings (Game Function)

Modify host session settings. Only the host can use this.
Not all fields that can be passed to CreateOnlineSession are supported.

Example:

GetEntitySelectedPlayerId (Game Function)

Get which player has a given entity selected

Example:

GetFullscreenMode (Game Function)

Get the display fullscreen mode

Example:

SetFullscreenMode (Game Function)

Change the display fullscreen mode

Example:

GetScreenResolution (Game Function)

Get active screen resolution

Example:

SetScreenResolution (Game Function)

Set screen resolution

Example:

GetScreenResolutions (Game Function)

Get a list screen resolutions appropriate for the current fullscreen mode

Example:

ApplyScreenModeRequired (Game Function)

Apply resolution and fullscreen mode settings

Example:

ApplyScreenModeNeedConfirm (Game Function)

Apply resolution and fullscreen mode settings

Example:

ConfirmScreenMode (Game Function)

Confirm changed resolution and fullscreen mode settings

Example:

RevertScreenMode (Game Function)

Revert resolution and fullscreen mode to last confirmed settings

Example:

GetVideoSettings (Game Function)

Read video settings table
- vsync: VSync enabled state (BOOLEAN)
- frame_rate_limit: Frame rate limit (0 means unlimited) (NUMBER)
- hdr_output: HDR output state (BOOLEAN)
- overall_quality: Overall video quality level (0 - 3) (NUMBER)
- view_distance_quality: View distance quality (0 - 3) (NUMBER)
- effect_quality: Effect and Volumetric fog quality (0 - 3) (NUMBER)
- shadow_quality: Shadow quality (0 = disabled, 3 = max) (NUMBER)
- anti_alias_quality: Anti-aliasing quality (0 = disabled, 3 = max) (NUMBER)
- bloom_quality: Bloom quality (0 = disabled, 5 = max) (NUMBER)
- depth_of_field_quality: Depth of field quality level (0 = disabled, 4 = max) (NUMBER)
- depth_of_field_strength: Depth of field strength (NUMBER)
- gamma: Gamma value (NUMBER)
- safe_mode: Only available if safe mode has been activated after a game crash (BOOLEAN)

Example:

GetSupportedUpscalingModes (Game Function)

Get supported Upscaling modes and features

Example:

SetVideoSettings (Game Function)

Modify video settings

Example:

GetVolume (Game Function)

Get the volume of a mix type

Example:

SetVolume (Game Function)

Set the volume of a mix type

Example:

GetUnfocusedVolume (Game Function)

Get the volume of the game while unfocused

Example:

SetUnfocusedVolume (Game Function)

Set the volume of the game while unfocused

Example:

GetNewsText (Game Function)

Load the news text table from the online source

Example:

OpenWebsite (Game Function)

Open Website to a special URL

Example:

ExploreFolder (Game Function)

Open OS file browser to a special folder

Example:

SendFeedback (Game Function)

Send feedback to the developers

Example:

UnlockAchievement (Game Function)

Unlock an achievement (only available on unmodded/unmodified game)

Example:

Module: Input

The Input module contains Input functions

Source: /Source/Desynced/Lua/Module/DSInputModule.cpp

IsShiftDown (Input Function)

Check if the shift key is pressed (either left or right shift key)

Example:

IsControlDown (Input Function)

Check if the control key is pressed (either left or right control key)

Example:

IsAltDown (Input Function)

Check if the alt key is pressed (either left or right alt key)

Example:

IsKeyDown (Input Function)

Check if a specific key is pressed
This does not work while a modal UI view is open

Example:

BindAction (Input Function)

Bind a callback function to a named input action

Example:

BindAxis (Input Function)

Bind a callback function to a named input axis

Example:

RemoveActionBinding (Input Function)

Remove bound callback functions from a named input action

Example:

RemoveAxisBinding (Input Function)

Remove all bound callback functions from a named input axis

Example:

AddActionMapping (Input Function)

Map a physical input key to a named input action

Example:

AddAxisMapping (Input Function)

Map a physical input key to a named input axis

Example:

RemoveActionMapping (Input Function)

Remove previously mapped physical inputs from a named input action

Example:

IsBoundToAction (Input Function)

Check if a key is bound to an action

Example:

IsBoundToAxis (Input Function)

Check if a key is bound to an axis

Example:

RemoveAxisMapping (Input Function)

Remove previously mapped physical inputs from a named input axis

Example:

GetBindingNames (Input Function)

Get a table with all key names of a category

Example:

GetUnknownKeyBindingName (Input Function)

Get the name of an unknown key binding name not returned with GetBindingNames

Example:

SetInputProcessor (Input Function)

Set custom input processor which can pre-process all input events
If the passed lua function returns boolean true the event will be forwarded to the games regular input handling
is_down is relevant for button events (keyboard, mouse buttons, gamepad buttons)
axis is a numerical value for analog inputs (gamepad analog inputs, mouse screen position)
mouse_delta is a numerical value of the change for mouse inputs (mouse position, mouse wheel)

Example:

ClearInputProcessor (Input Function)

Clear the active custom input processor

Example:

Module: Map

The map module contains global functions affecting the game state

Source: /Source/Desynced/Lua/Module/DSMapModule.cpp

SetGameSpeed (Map Function)

Modify simulation speed

Example:

GetGameSpeed (Map Function)

Get simulation speed

Example:

IsSimulation (Map Function)

Check if LUA is currently running in simulation context

Example:

IsFrontEnd (Map Function)

Check if the active map is the front-end menu

Example:

GetSettings (Map Function)

Get current map settings (read only)

Example:

ModifySettings (Map Function)

Set or modify a map setting
Settings that affect world generation or sun simulation shouldn't be changed after the game has started, otherwise the game will break or get out of sync.

Example:

GetSeed (Map Function)

Get map seed (same as GetSettings().seed)

Example:

GetSave (Map Function)

Get save table (can only be modified in simulation context)
If called without argument from a mod that doesn't contain the currently active scenario, will return a mod specific child table parent.mods[mod_id]
If called with an empty string or nil, will always return entire parent table

Example:

Run (Map Function)

Call bound MapMsg functions

Example:

GetTick (Map Function)

Get the current simulation tick number

Example:

GetExecutedActionCount (Map Function)

Get the number of player actions that have been executed

Example:

CreateEntity (Map Function)

Create a new entity from a frame definition

Example:

RecreateEntity (Map Function)

Recreate an entity with a new frame definition but keep any references to it

Example:

DropItemAt (Map Function)

Drop an item at a specific location.
Will combine with existing dropped items if one exists and has space.
If this function is called while entities are being processed, the item will be dropped deferred (Map.Defer should still be used when this function is called multiple times).

Example:

GetFaction (Map Function)

Get a faction

Example:

CreateFaction (Map Function)

Create a new faction (or get it if it already exists)

Example:

GetFactions (Map Function)

Get all factions

Example:

GetFactionCount (Map Function)

Get the number of spawned factions

Example:

GetPlayerFactions (Map Function)

Get all player controlled factions

Example:

GetPlayerFactionCount (Map Function)

Get the number of spawned player factions

Example:

SetPlayerFaction (Map Function)

Switches a players faction

Example:

GetTotalDays (Map Function)

Get the number of days progressed

Example:

GetYear (Map Function)

Get the current year

Example:

GetYearSeason (Map Function)

Get the current season value between 0-1, 0.5 being summer, 0/1 being winter

Example:

GetSunlightIntensity (Map Function)

Get the current sunlight intensity

Example:

GetSunlightAmount (Map Function)

Get the current amount of sunlight (square root of sunlight intensity)

Example:

GetSunlightDirection (Map Function)

Get the direction of the sunlight as a normalized vector

Example:

GetSunriseAndSunset (Map Function)

Get the day time of sunrise and sunset

Example:

GetUndiscoveredLocation (Map Function)

Get the location of the Nth next unspawned chunk
The returned tile position is at the center of the unspawned 60x60 chunk

Example:

GetLocationInRange (Map Function)

Get the location of a tile at a given distance from a starting point
This function matches the behavior of GetEntitiesOnLine.

Example:

GetClosestLocation (Map Function)

Get the closest tile location of an area towards another area
Useful when starting area potentially is larger than 1x1.

Example:

SpawnChunks (Map Function)

Make sure chunks exist at the given location
If this function is called while entities are being processed, new chunks will spawn deferred.

Example:

GetBlightness (Map Function)

Get blightness for a tile or area

Example:

GetBlightnessDelta (Map Function)

Get blightness delta against the blight threshold for a tile or area (same as Map.GetBlightness(..) - Map.GetSettings().blight_threshold)

Example:

GetElevation (Map Function)

Get elevation for a tile or area

Example:

GetRichness (Map Function)

Get richness for a tile or area

Example:

GetVariation (Map Function)

Get variation for a tile or area

Example:

GetHeight (Map Function)

Get height for a tile or area

Example:

GetPlateauDelta (Map Function)

Get the height against the plateau height for a tile or area (same as Map.GetHeight(..) - Map.GetPlateauHeight())

Example:

GetPlateauHeight (Map Function)

Get plateau height

Example:

GetWaterHeight (Map Function)

Get water height

Example:

GetTileData (Map Function)

Get table with full tile data for a given location

Example:

Defer (Map Function)

Defer function until after components have been processed
For example, it is not possible to create new entities during processing, creation needs to be deferred.

Example:

Delay (Map Function)

Delay function for a given number of ticks
A delay function can be registered with
function Delay.FUNCTIONNAME(arg)

Example:

StartTerraforming (Map Function)

Start terraforming

Example:

StopTerraforming (Map Function)

End terraforming

Example:

GetEntityAt (Map Function)

Get an entity at a specific location
If there are multiple entities, it will return the first entity in the following order: blocking, non-blocking, foundation

Example:

GetFoundationEntityAt (Map Function)

Get a foundation entity at a specific location (faster than the function above)

Example:

GetEntitiesAt (Map Function)

Get all entities at a specific location

Example:

GetEntitiesInRange (Map Function)

Get all entities in a range around a specific location or area
If an entity is used to specify the area, the result will not contain that entity.

Example:

GetEntitiesOnLine (Map Function)

Get all entities on a line between two points or from a starting point until a given distance
If an entity is used to specify the starting area, the result will not contain that entity.
But an entity used for the ending area will be contained in the result.
The line of search will always be thin (just 1 tile) even if a passed area is wider.

Example:

FindClosestEntity (Map Function)

Search for the closest entity in a range
If an entity is used to specify the area, the callback will not be called for that entity.

Example:

GetEntityFromKey (Map Function)

Get an entity from a key (obtained from entity.key)

Example:

CountTiles (Map Function)

Count tiles in and around an area
To count number of owned entities, an entity needs to be specified as the area

Example:

GetComponents (Map Function)

Get all component instances of a given type
This is slow so please use it sparingly, preferably only for one-time global operations like version updates.

Example:

ThrowItemEffect (Map Function)

Show a item throw effect

Example:

Module: Tool

The tool module contains utility functions

Source: /Source/Desynced/Lua/Module/DSToolModule.cpp

Hash (Tool Function)

Create a checksum of a value

Example:

Copy (Tool Function)

Create a deep copy of a value, most often used with tables

Example:

TruncateString (Tool Function)

Truncate a string potentially containing Unicode characters

Example:

CompareStringNoCase (Tool Function)

Compare two strings potentially containing Unicode characters case insensitive

Example:

ContainsStringNoCase (Tool Function)

Check if a string exists inside another string case insensitive, where the strings potentially contain Unicode characters

Example:

TableToString (Tool Function)

Convert a lua table to a string

Example:

StringToTable (Tool Function)

Convert a string back to a lua table

Example:

SetClipboard (Tool Function)

Store a LUA table into the OS clipboard
The passed table should not be modified afterwards because Tool.GetClipboard will return the same table reference until the clipboard is modified.

Example:

GetClipboard (Tool Function)

Retrieve a LUA table from the OS clipboard
The returned table should not be modified because the same table reference will get returned again until the clipboard is modified.

Example:

GetTableDelta (Tool Function)

Encode the difference how to get from one lua table to another
This is useful if a table is slightly modified over time and a modification history is to be kept (i.e. for a undo/redo system)
The function must be first called without src_table_str to generate the encoded string of dst_table which then can be used on a secondary call.

Example:

ApplyTableDelta (Tool Function)

Apply an encoded difference string to revert a table back to the source table after using GetTableDelta

Example:

GetDateStr (Tool Function)

Format a date and time value as a string
Will use current time if no timestamp gets passed.

Example:

GetTimeDurationStr (Tool Function)

Format a time duration to a string (HH:MM:SS)

Example:

NewRegisterObject (Tool Function)

Create an empty or copied register object

Example:

ParseEntityStates (Tool Function)

Parse binary entity state bit-flags into a readable table

Example:

EncodeEntityStates (Tool Function)

Encode readable table into binary entity state bit-flags

Example:

EncodeTrustLevels (Tool Function)

Encode readable table into binary trust level bit-flags

Example:

Module: Twitch

The twitch module contains functions that interact with Twitch.

Source: /Source/Desynced/Lua/Module/DSTwitchModule.cpp

Login (Twitch Function)

Start the auth process on Twitch unless already logged in
Once logged in the authentication data is stored to disk and login is not needed until logged out

Example:

Logout (Twitch Function)

Clear any stored authentication parameters if logged in

Example:

IsLoggedIn (Twitch Function)

Check if the user is logged in on Twitch

Example:

GetUserData (Twitch Function)

Request user information of the logged in user
If the user data has already been requested before the callback will be called immediately.

Example:

GetCustomRewards (Twitch Function)

Request the list of custom rewards
If the reward list has already been requested before the callback will be called immediately with the cached data.

Example:

StartRewards (Twitch Function)

Start listening for reward redemptions
User must be logged in before this is called (IsLoggedIn must return true)
When a reward is redeemed, UIMsg.TwitchOnRewardRedeemed(reward_id, user_display_name, redemption_user_input) will get called

Example:

StopRewards (Twitch Function)

Stop listening for reward redemptions

Example:

StartChat (Twitch Function)

Start listening for chat messages
When a message is posted, UIMsg.TwitchOnChatMessage(username, message) will get called

Example:

StopChat (Twitch Function)

Stop listening for chat messages

Example:

Module: UI

The UI module contains UI related functions

Source: /Source/Desynced/Lua/Module/DSUIModule.cpp

Register (UI Function)

Register a layout definition tag

Example:

IsRegistered (UI Function)

Check if a layout tag has been registered

Example:

New (UI Function)

Instantiate a new widget

Example:

AddLayout (UI Function)

Add widget to screen canvas

Example:

FindWidgetWithTag (UI Function)

Find a widget with a given tag that is on screen

Example:

FindWidgetsWithTag (UI Function)

Find all widgets with a given tag which are on screen

Example:

FindWidgetWithProperty (UI Function)

Find a widget with a given property that is on screen

Example:

FindWidgetsWithProperty (UI Function)

Find all widgets with a given property which are on screen

Example:

GetRegisteredLayoutString (UI Function)

Get the layout string of a registered layout tag
When running a dedicated server, this function will always return an empty string.

Example:

SetRegisteredLayoutString (UI Function)

Overwrite the layout string of a registered layout tag
Will not apply to layout tags already on screen.
When running a dedicated server, this function will do nothing.

Example:

GetRegisteredLayoutClass (UI Function)

Get the class table of a registered layout tag
When running a dedicated server, this function will do always return an empty table.

Example:

SetRegisteredLayoutClass (UI Function)

Overwrite the class table of a registered layout tag
Can only be done for layout tags which are not on screen.
When running a dedicated server, this function will do nothing.

Example:

GetWidgetsUnderCursor (UI Function)

Find all widgets below the mouse cursor or at a position
The most top widget will be the first in the result.
If the position is outside of the current view, only widgets that fill out the view will be returned (current view can be a popup or the entire game window).

Example:

GetWidgetWithTagUnderCursor (UI Function)

Find a widgets with a given tag below the mouse cursor or at a position

Example:

GetWidgetWithPropertyUnderCursor (UI Function)

Find a widgets with a given property below the mouse cursor or at a position

Example:

GetRootWidgets (UI Function)

Get all widgets that have been attached to the screen canvas with UI.AddLayout.

Example:

MakeModOptionsWidget (UI Function)

Instantiate the options widget of a mod

Example:

GetMapSettingsArray (UI Function)

Get all custom map settings tables of the active or a specific scenario

Example:

GetScreenSize (UI Function)

Get the size of the screen scaled in UI coordinates

Example:

MenuPopup (UI Function)

Pop up a context menu or window
If there isn't enough space in the direction it will flip to the other side
If there isn't enough space in the crosswise direction it will shift horizontally (if UP/DOWN) or vertically (if LEFT/RIGHT)

Example:

StartDrag (UI Function)

Force start a drag and drop operation without the user necessarily having to drag anything

Example:

CloseMenuPopup (UI Function)

Close the context menu opened with MenuPopup

Example:

CloseTooltip (UI Function)

Close the current tooltip

Example:

RefreshTooltip (UI Function)

Refresh the current tooltip

Example:

Delay (UI Function)

Run code after a given delay (similar to widget tweens)

Example:

PlaySound (UI Function)

Play a UI sound effect, music, voice or ambience

Example:

StopMusic (UI Function)

Stop the playing music

Example:

StopVoice (UI Function)

Stop the playing voice

Example:

StopAmbienceSound (UI Function)

Stop the playing ambience sound effect

Example:

SetUIHidden (UI Function)

Hide the entire UI

Example:

IsUIHidden (UI Function)

Check if UI has been hidden with SetUIHidden

Example:

EntityLocationOnScreen (UI Function)

Query the UI coordinate of an entity in the game camera view

Example:

Run (UI Function)

Run code in UI context or call bound UIMsg functions
When called from simulation context the function will execute for all connected players (to limit to specific players use faction:RunUI or Action.RunUI)
When called from UI context the function will only execute for the local player

Example:

GetLanguages (UI Function)

Get a table of languages

Example:

GetLanguageCode (UI Function)

Get the current language code

Example:

SetLanguageCode (UI Function)

Change the active language

Example:

GetScale (UI Function)

Get the UI scale factor

Example:

SetScale (UI Function)

Set the UI scale factor

Example:

GetMousePosition (UI Function)

Gets position of mouse cursor
If a widget gets passed that hasn't had its layout calculated yet, the function will return nil

Example:

IsMouseOverUI (UI Function)

Check if the mouse cursor is over a UI widget

Example:

SendChatGlobal (UI Function)

Send chat function call to every player (including locally)
A chat function can be registered with
function Chat.FUNCTIONNAME(arg, sender_player_id, scope)

Example:

SendChatPlayer (UI Function)

Send chat function call to a specific player

Example:

SendChatFaction (UI Function)

Send chat function call to all players of the local or a specific faction

Example:

SendChatAlliance (UI Function)

Send chat function call to all players that share visibility with the local or a specific faction

Example:

Module: View

The view module contains global functions that don't affect the state of the simulation but aren't directly related to UI

Source: /Source/Desynced/Lua/Module/DSViewModule.cpp

GetHoveredTilePosition (View Function)

Get the location of the currently hovered tile

Example:

GetHoveredEntity (View Function)

Get the entity currently hovered

Example:

ResetCamera (View Function)

Reset the camera to the faction home location

Example:

MoveCamera (View Function)

Move the camera to a given location

Example:

JumpCameraToEntities (View Function)

Focus the camera on one or more entities

Example:

GetCameraZoom (View Function)

Get Local camera zoom distance

Example:

FollowEntity (View Function)

Sets the entity for the camera to follow

Example:

GetFollowEntity (View Function)

Get the entity currently followed by the camera

Example:

SetVisualizations (View Function)

Enable or disable visualization modes
Pass a table settings, any settings not present in the table will be set to disabled.
{
global = { stores = true, gotos = true, transport_routes = true, power_transmitters = true, portals = true, orders = true, paths = true },
selected = { stores = true, gotos = true, transport_routes = true, power_transmitters = true, portals = true, orders = true, paths = true },
}

Example:

GetSelectedEntities (View Function)

Get the currently selected entities

Example:

GetSelectedEntity (View Function)

Get the currently selected entity (will be just the first if multiple are selected)

Example:

IsSelectedEntity (View Function)

Check if an entity is selected

Example:

SelectEntities (View Function)

Set the selected entity(s)

Example:

SelectPreviousEntities (View Function)

Switch entity selection to previously selected entities

Example:

HighlightEntity (View Function)

Highlight an entity

Example:

StartCursorChooseLocation (View Function)

Switch to a cursor mode to select a location on the map

Example:

StartCursorChooseEntity (View Function)

Switch to a cursor mode to select an entity on the map

Example:

StartCursorConstruction (View Function)

Show entity construction location selection on map

Example:

StopCursor (View Function)

Cancel cursor mode started with the functions above

Example:

RotateConstructionSite (View Function)

RotateConstructionSite

Example:

SetPostProcess (View Function)

Set a fullscreen effect parameter

Example:

PlayEffect (View Function)

Play effect at a location

Example:

SetEffectParam (View Function)

Set a parameter on an effect started with View.PlayEffect

Example:

StopEffect (View Function)

Stop an effect started with View.PlayEffect

Example:

InConstructionMode (View Function)

Checks if the player is currently in construction mode

Example:

GetVisibleEntities (View Function)

Get all entities currently on screen
The filter_trust argument is a bit-flag integer which can be generated by Tool.EncodeTrustLevels
The 5th element returned for each entity 'trust' contains special entries 'faction' and 'world' besides 'ally'/'neutral'/'enemy'

Example:

SetCamera3DPosition (View Function)

Set the full 3D camera position and target location directly

Example:

GetCamera3DPosition (View Function)

Get the 3D camera position and target location

Example:

PanCamera3DPosition (View Function)

Directly shift the camera in 3D space (relative to the current camera rotation)

Example:

TiltCamera3DRotation (View Function)

Directly rotate the camera in place

Example:

LockCamera (View Function)

Fully lock the camera in its current state until UnlockCamera is called
Direct modification of the camera with SetCamera3DPosition, PanCamera3DPosition or TiltCamera3DRotation is available even while locked.

Example:

UnlockCamera (View Function)

Unlock the camera again after having LockCamera called

Example:

IsRunningHeadless (View Function)

Check if the game is running without rendering (headless)

Example:

Meta Tables

Meta Table: Component

A component object represents a component equipped by an entity.

Source: /Source/Desynced/Lua/Meta/DSComponentLuaMeta.cpp

Component Functions

Destroy (Component Function)

destroys a component

Example:

PrepareRemoval (Component Function)

Prepare a component for removal by clearing out all item slots and reserves related to this component
If the component is hidden, the function will return false.
Contained items will be moved to other inventory slots or (if the entity is movable or has a crane) dropped.
The function returns true if all items could be moved away or dropped (or there are no items contained).

Example:

GetRegister (Component Function)

Get a register of this component

Example:

GetRegisterNum (Component Function)

Get the number part of a register of this component

Example:

GetRegisterId (Component Function)

Get the id part of a register of this component

Example:

GetRegisterDef (Component Function)

Get the definition table of the id stored in a register of this component

Example:

GetRegisterEntity (Component Function)

Get the entity part of a register of this component

Example:

GetRegisterCoord (Component Function)

Get the coordinate part of a register of this component

Example:

RegistersEqual (Component Function)

Compare two registers of this component

Example:

SetRegister (Component Function)

Set a register of this component

Example:

SetRegisterNum (Component Function)

Set the number part of a register of this component

Example:

SetRegisterId (Component Function)

Set the id part of a register of this component (will overwrites the entity/coordinate part)

Example:

SetRegisterEntity (Component Function)

Set the entity part of a register of this component (will overwrite the id/coordinate part)

Example:

SetRegisterCoord (Component Function)

Set the coordinate part of a register of this component (will overwrite the id/entity part)

Example:

FlagRegisterError (Component Function)

Flag the error state on a register of this component
Will stay flagged until the register value changes.

Example:

RegisterIsLink (Component Function)

Check if a register of this component is linked from another register

Example:

RegisterIsEmpty (Component Function)

Check if a register of this component is empty

Example:

RegisterIsError (Component Function)

Check if a register of this component is in error state

Example:

RegisterHasConnection (Component Function)

Check if two registers have a connection via link(s)

Example:

LinkRegisterFromRegister (Component Function)

Link a register from another register

Example:

UnlinkRegisterFromRegister (Component Function)

Unlink a register from another register

Example:

GetRegisterLinkSource (Component Function)

Get the source index of the first relevant register link
If no entity or component is specified, information of the first link containing any value will be returned.
Otherwise it will look up a specific link and return only the register index.

Example:

GetRegisterLinkTarget (Component Function)

Get the target index of the first relevant register link

Example:

HaveRegisterQueue (Component Function)

Check if a register of this entity has a queue (2 or more elements)

Example:

RegisterQueueLength (Component Function)

Count the number of queued elements

Example:

RegisterQueueGet (Component Function)

Get an element of the register queue.
Querying the first element will return the same as GetRegister unless the register is linked.

Example:

RegisterQueueGetAll (Component Function)

Get the entire queue as an array

Example:

RegisterQueueSet (Component Function)

Overwrite a queued element.
Can write the first element while keeping the queue (unlike SetRegister which clears the queue).
Can write to an index past the end of the queue (same as RegisterQueueInsert).

Example:

RegisterQueueInsert (Component Function)

Insert a queued element at a given position or the end.
Can write to an index past the end of the queue (same as RegisterQueueSet).

Example:

RegisterQueueRemove (Component Function)

Remove a queued element

Example:

GetSlot (Component Function)

Get an item slot of this component

Example:

ClearActivationChangeFlags (Component Function)

Clear activation change flags that would trigger the on_update callback in the next tick.
If the on_update callback causes modification to the same item slots that triggers its activation,
unless this function is called, it will be activated again in the next tick due to its own change.
Changes to registers made with the component:SetRegister function during on_update are automatically cleared.
Be aware this does not work for the activation modes 'OnAnyItemSlotChange'.

Example:

PrepareProduceProcess (Component Function)

Set up a process that consumes ingredients and generates output items

Example:

PrepareGenerateProcess (Component Function)

Set up a process that generates output items

Example:

PrepareConsumeProcess (Component Function)

Set up a process that consumes ingredients

Example:

FulfillProcess (Component Function)

Finish a prepared process (add generated items and remove consumed ingredients)

Example:

CancelProcess (Component Function)

Cancel ongoing process and related orders from this component

Example:

GetProcessConsumeSlot (Component Function)

If there is a prepared process, get an item slot from which items are consumed from.

Example:

GetProcessOutputSlot (Component Function)

If there is a prepared process, get an item slot from which items are output to.

Example:

OrderItem (Component Function)

Order an item through this component
The order will stay active while this component works or sleeps but gets canceled when the component becomes inactive or when CancelProcess is called.
Will return nil on invalid item or amount or if not enough free space available in the slot.
Multiple orders can be created covering the entire inventory.
If priority IS NOT "ManualOrder", no new orders will be created if the inventory already contains the requested amount (and nil will be returned).
If priority IS "ManualOrder", a single component can be ordered and auto equipped even when there is no free item slot is available.

Example:

RotateComponent (Component Function)

Turns component to look at a target entity or location

Example:

RequestStateMove (Component Function)

Request the entity to move on behalf of this component (if movement is needed)
The function will also return true if out of range and the entity has no movement.
The function will also return true if the owner or target_entity is not placed on the map and not docked.

Example:

SetStateSleep (Component Function)

Request the component to sleep

Example:

SetStateStartWork (Component Function)

Request the component to work for a duration
If the component is required to prevent the entity from moving while working, RequestStateMove needs to be called first.

Example:

NotifyWorkFailed (Component Function)

Notify other components waiting for this with CC_OTHER_COMP_FAIL_WORK

Example:

SetStateContinueWork (Component Function)

Continue work that was started with SetStateStartWork

Example:

WaitForFirstRegisterChange (Component Function)

Get called back the next time the first register of this component changes

Example:

WaitForComponentRegisterChange (Component Function)

Get called back the next time any register of this component changes

Example:

WaitForFirstItemSlotChange (Component Function)

Get called back the next time the first item slot of this component changes

Example:

WaitForComponentItemSlotChange (Component Function)

Get called back the next time any item slot of this component changes

Example:

WaitForLowPower (Component Function)

Get called back the next time the entity has low power

Example:

WaitForPowerStoredEmpty (Component Function)

Get called back the next time the battery charge is empty

Example:

WaitForOtherCompFinish (Component Function)

Get called back when another component finishes work
It is not possible to wait on multiple components simultaneously

Example:

Activate (Component Function)

Activate a component (trigger on_update)
This is most useful for components that have the activation mode set to 'Manual', but it can also be used for other components.
Usage of Activate cannot be mixed with the WaitFor* functions.
Cannot be called from inside the on_update function (check with is_updating).

Example:

Shutdown (Component Function)

Deactivate a component (stop triggering on_update)
This will abort what has been started with a SetState, RequestState or WaitFor call.
Cannot be called from inside the on_update function (check with is_updating).

Example:

CauseToString (Component Function)

Convert a numerical cause variable received in on_update to a string (for debugging purpose)

Example:

FindClosestTriggeringEntity (Component Function)

Search for the closest entity of all matching entities inside this components trigger_radius

Example:

PlayEffect (Component Function)

Spawn particle/sound effect on this component
Avoid calling this in the on_add callback, instead use effect property on component definition instead for automatically spawning effects.

Example:

PlayWorkEffect (Component Function)

Play effect for working component
Similar to PlayEffect but only starts the effect if not already playing an effect and if power is available. Will also stop playing effects if power is not available.
This is best used together with SetStateStartWork and passing true to its refresh flag argument.

Example:

StopEffects (Component Function)

Stop all looping effects playing on this component

Example:

SetWorkAnimationSpeed (Component Function)

Sets animation speed multiplied by the components current power efficiency

Example:

Component Variables

owner (Component Variable)

The owner of this component
Value: Owner entity (entity)
Access: read only

Example:

faction (Component Variable)

The faction of the owner of this component
Value: Faction object (faction)
Access: read only

Example:

exists (Component Variable)

Check if this component and its owning entity still exists or if it was unequipped or destroyed
Value: Exist state (boolean)
Access: read only

Example:

key (Component Variable)

A unique numerical identifier of this component
Value: key (integer)
Access: read only

Example:

id (Component Variable)

The id of this component
Value: Component id (component-id-string)
Access: read only

Example:

base_id (Component Variable)

The base id of this component
Value: Component base id (base_id if set otherwise regular id) (component-id-string)
Access: read only

Example:

def (Component Variable)

The definition table of this component
Value: Component definition (table)
Access: read only

Example:

visual_id (Component Variable)

The visual id of this component
Value: visual id (visual-id-string)
Access: read only

Example:

visual_def (Component Variable)

The visual definition table of this component
Value: visual definition table (table)
Access: read only

Example:

socket_index (Component Variable)

The socket index this component is attached to
Value: Socket index (or 0 if hidden) (integer)
Access: read only

Example:

slot_index (Component Variable)

Gets the index of the first item slot of this component in the entities slot array
Value: Register index (integer)
Access: read only

Example:

slot_count (Component Variable)

Check the number of item slots a component has
Value: Number of slots (integer)
Access: read only

Example:

slots (Component Variable)

Get an array with all item slots of this component
It is not possible to overwrite or add items to this array
Value: Item slot array table (table)
Access: read only

Example:

register_index (Component Variable)

Gets the index of the first register of this component in the entities register array
Value: Register index (integer)
Access: read only

Example:

register_count (Component Variable)

Check or change the number of registers a component has
Value: Number of registers (integer)
Access: read & write

Example:

is_empty (Component Variable)

Returns if the component has no items stored in it
Value: Empty state (boolean)
Access: read only

Example:

is_hidden (Component Variable)

Returns if the component is a hidden component (does not occupy a socket)
Value: Hidden state (boolean)
Access: read only

Example:

is_active (Component Variable)

Returns if the component is active (waiting on completing SetState, RequestState or WaitFor calls)
Value: Active state (boolean)
Access: read only

Example:

is_working (Component Variable)

Returns if the component is still working on something started with SetStateStartWork
Value: Working state (boolean)
Access: read only

Example:

is_sleeping (Component Variable)

Returns if the component is currently active but sleeping (waiting on completing SetStateSleep)
Value: Sleeping state (boolean)
Access: read only

Example:

is_updating (Component Variable)

Returns if the component currently executing the on_update callback
Value: Updating state (boolean)
Access: read only

Example:

has_move_control (Component Variable)

Returns if the component has successfully gained movement control over its owner
Value: Movement control state (boolean)
Access: read only

Example:

has_prepared_process (Component Variable)

Returns if the component has prepared a produce/generate/consume process
Value: Has started process state (boolean)
Access: read only

Example:

progress_percent (Component Variable)

The progress of work that has been completed
Value: Work progress (between 0 and 100, or -1 if not working) (integer)
Access: read only

Example:

interpolated_progress (Component Variable)

The progress of work that has been completed interpolated to the rendered frame rate (only accessible by UI)
Value: Work progress (between 0.0 and 1.0, or -1 if not working) (number)
Access: read only

Example:

ticker (Component Variable)

The work ticker
This number can be returned rounded up to the next tick if the component is working but not at 100% efficiency.
Value: Work ticker (how many ticks elapsed since work or sleep start, or 0 if inactive) (integer)
Access: read only

Example:

ticker_target (Component Variable)

The work ticker target
Value: Total work ticks (total ticks until work or sleep finishes, or 0 if inactive) (integer)
Access: read only

Example:

has_extra_data (Component Variable)

Check if extra_data has been created for this component
Value: Result (boolean)
Access: read only

Example:

extra_data (Component Variable)

Access to the extra data table of this component instance
Reading it will always return a valid table when (will be created if not set yet)
Writing nil to it will free the table from memory
Value: Extra data table (table)
Access: read & write

Example:

stored_power (Component Variable)

The amount of power currently stored in this battery component
Cannot exceed power_storage value in the component definition
This does nothing if the entity is docked (returns nil)
The number can be very small without ever jumping to 0.
Value: Currently stored power amount (integer)
Access: read & write

Example:

extra_power (Component Variable)

The dynamic additional power supplied/consumed by this component
Added on top of the base value in the component definition
This does nothing if the entity is docked (returns nil)
Value: Amount of power supplied (positive value) or consumed (negative value) (integer)
Access: read & write

Example:

extra_transfer_range (Component Variable)

The dynamic additional power range of this component
Added on top of the base value in the component definition
This does nothing if the entity is docked (returns nil)
Value: Extra power range in tiles (integer)
Access: read & write

Example:

power_relay_target (Component Variable)

The relay target of this power relay component
This does nothing if the entity is docked (returns nil)
Value: Relay target entity (entity)
Access: read & write

Example:

power_details (Component Variable)

Get a table with power details about this component
Building this table is slow so avoid reading it multiple times.
Some of the returned numbers (stored, change, transmitted) can be very small without ever jumping to 0.
Value: Details table (or nil if component has no power data) (table)
Access: read only

Example:

animation_speed (Component Variable)

Set Material animation speed if supported by the visual
Value: Speed (number)
Access: read & write

Example:

light_color (Component Variable)

Set light color (RGB) and intensity (A) if supported by the visual
Value: RGBA light color value (color)
Access: read & write

Example:

has_active_effects (Component Variable)

Check if there are any looping effects playing on this component
Value: Result (boolean)
Access: read only

Example:

triggering_entities (Component Variable)

Get an array with all matching entities inside this components trigger_radius
Value: Entity array (table)
Access: read only

Example:

Component Operators

ToString Operator (Component Operator)

Example:

Equality Operator (Component Operator)

Example:

Meta Table: Entity

An entity object represents a single entity that can be placed in the world.

Source: /Source/Desynced/Lua/Meta/DSEntityLuaMeta.cpp

Entity Functions

Place (Entity Function)

Place this entity on the map (or teleport it if it is already placed)
Unless the last parameter is false, automatically selects a close location if the passed coordinates are occupied
If rotation argument is not passed, it will keep the previous rotation

Example:

Unplace (Entity Function)

Remove this entity from the map

Example:

Destroy (Entity Function)

Destroy this entity
Can automatically drop all components and inventory items held by it, as well as additional items

Example:

AddComponent (Entity Function)

Create and add a new component

Example:

GetComponent (Entity Function)

Get an existing component at a specific socket index

Example:

SwapSockets (Entity Function)

Swap the content of two sockets
One or both sockets must contain a component which must fit into the other socket

Example:

GetHiddenComponent (Entity Function)

Get an existing hidden component

Example:

CountComponents (Entity Function)

Count the components of the same type on an entity

Example:

FindComponent (Entity Function)

Find an existing component

Example:

GetFreeSocket (Entity Function)

Check if a free socket of large enough size is available to equip a component

Example:

CheckSocketSize (Entity Function)

Test if a component fits into a socket (regardless if there is already something equipped in the socket)

Example:

GetRegisterLinks (Entity Function)

Get a list of links on the entity

Example:

GetRegister (Entity Function)

Get a register of this entity

Example:

GetRegisterNum (Entity Function)

Get the number part of a register of this entity

Example:

GetRegisterId (Entity Function)

Get the id part of a register of this entity

Example:

GetRegisterDef (Entity Function)

Get the definition table of the id stored in a register of this entity

Example:

GetRegisterEntity (Entity Function)

Get the entity part of a register of this entity

Example:

GetRegisterCoord (Entity Function)

Get the coordinate part of a register of this entity

Example:

RegistersEqual (Entity Function)

Compare two registers of this entity

Example:

SetRegister (Entity Function)

Set a register of this entity

Example:

SetRegisterNum (Entity Function)

Set the number part of a register of this entity

Example:

SetRegisterId (Entity Function)

Set the id part of a register of this entity (will overwrites the entity/coordinate part)

Example:

SetRegisterEntity (Entity Function)

Set the entity part of a register of this entity (will overwrite the id/coordinate part)

Example:

SetRegisterCoord (Entity Function)

Set the coordinate part of a register of this entity (will overwrite the id/entity part)

Example:

FlagRegisterError (Entity Function)

Flag the error state on a register of this entity
Will stay flagged until the register value changes.

Example:

RegisterIsLink (Entity Function)

Check if a register of this entity is linked from another register

Example:

RegisterIsEmpty (Entity Function)

Check if a register of this entity is empty

Example:

RegisterIsError (Entity Function)

Check if a register of this entity is in error state

Example:

RegisterHasConnection (Entity Function)

Check if two registers have a connection via link(s)

Example:

LinkRegisterFromRegister (Entity Function)

Link a register from another register

Example:

UnlinkRegisterFromRegister (Entity Function)

Unlink a register from another register

Example:

GetRegisterLinkSource (Entity Function)

Get the source index of the first relevant register link
If no entity or component is specified, information of the first link containing any value will be returned.
Otherwise it will look up a specific link and return only the register index.

Example:

GetRegisterLinkTarget (Entity Function)

Get the target index of the first relevant register link

Example:

HaveRegisterQueue (Entity Function)

Check if a register of this entity has a queue (2 or more elements)

Example:

RegisterQueueLength (Entity Function)

Count the number of queued elements

Example:

RegisterQueueGet (Entity Function)

Get an element of the register queue
Querying the first element will return the same as GetRegister unless the register is linked.

Example:

RegisterQueueGetAll (Entity Function)

Get the entire queue as an array

Example:

RegisterQueueSet (Entity Function)

Overwrite a queued element.
Can write the first element while keeping the queue (unlike SetRegister which clears the queue).
Can write to an index past the end of the queue (same as RegisterQueueInsert).

Example:

RegisterQueueInsert (Entity Function)

Insert a queued element at a given position or the end.
Can write to an index past the end of the queue (same as RegisterQueueSet).

Example:

RegisterQueueRemove (Entity Function)

Remove a queued element

Example:

AddItem (Entity Function)

Add an item to the inventory

Example:

CountItem (Entity Function)

Count (unreserved) stacks of an item across all item slots

Example:

HaveFreeSpace (Entity Function)

Check if there is any free space to add the item in any item slots

Example:

CountFreeSpace (Entity Function)

Count how much free space for an item in any item slots

Example:

GetFreeSlot (Entity Function)

Find an item slot with enough free space to store a given amount

Example:

GetSlot (Entity Function)

Get a single item slot at a specific slot index

Example:

FindSlot (Entity Function)

Find an item slot with a specific item

Example:

AddSlots (Entity Function)

Add inventory slots

Example:

AutoMergeSlots (Entity Function)

Automatically merge stacks of the same item across the inventory

Example:

IsWaitingForOrder (Entity Function)

Check if the entity is waiting for an order of a specific item

Example:

TransferFrom (Entity Function)

Transfer an item from the inventory of another entity

Example:

DropItem (Entity Function)

Drop an item to the ground
If a drop target coordinate is given further away than 1 tile and the entity has movement, the entity will move to the location before dropping.

Example:

DropComponent (Entity Function)

Drop an equipped component to the ground
If a drop target coordinate is given, it will only used as a direction where to drop. It is not possible to drop away further than 1 tile.

Example:

OrderItem (Entity Function)

Order an item
The order will stay active until fulfilled, CancelOrder gets called or the entity is destroyed.
Will return nil on invalid item or amount or if not enough free space available in the slot.
Multiple orders can be created covering the entire inventory.
If priority IS NOT "ManualOrder", no new orders will be created if the inventory already contains the requested amount (and nil will be returned).
If priority IS "ManualOrder", a single component can be ordered and auto equipped even when there is no free item slot is available.

Example:

GetLocationXY (Entity Function)

Get the location of this entity. Same as location but returns 2 integers instead of a table.

Example:

EstimateLocationInTicks (Entity Function)

Estimate the location of this entity in the future, only different from location when moving.

Example:

MoveTo (Entity Function)

Start moving the entity to a given location

Example:

MoveAway (Entity Function)

Start moving the entity somewhere outside of a given area.
This will do nothing if the entity is already outside the area.

Example:

Cancel (Entity Function)

Stop movement and abort what is currently controlling the entities movement.
Movement can be controlled via manual movement, or automated by order/component/context/home.
Components that don't request movement control will continue working autonomously.

Example:

LookAt (Entity Function)

Rotate the entity to look towards a given location

Example:

IsTouching (Entity Function)

Check if the entity is touching another entity or a location

Example:

IsInRangeOf (Entity Function)

Check if the entity is in range of another entity or a location

Example:

GetRangeTo (Entity Function)

Measure the range in tiles to another entity or a location

Example:

GetRangeSquaredTo (Entity Function)

Get the squared distance to another entity or a location

Example:

IssueDumpingOrders (Entity Function)

Request Inventory to be dumped into nearest storage

Example:

DockInto (Entity Function)

Dock this entity into an item slot of another entity

Example:

Undock (Entity Function)

Undock this entity

Example:

RemoveEntityInstance (Entity Function)

removes an instance from the entity

Example:

PlayEffect (Entity Function)

Spawn particle/sound effect on this entity

Example:

StopEffects (Entity Function)

Stop all looping particle/sound effects

Example:

StopEffect (Entity Function)

Stop a specific looping particle/sound effect

Example:

Activate (Entity Function)

Activate event of the visuals frame blueprint

Example:

Deactivate (Entity Function)

Deactivate event of the visuals frame blueprint

Example:

GetSizeAtRotation (Entity Function)

Get the size this entity would have at a given rotation

Example:

SetVisual (Entity Function)

Sets a new visual and rotation for an entity
This will fail and return false if the new visual in the new rotation occupies different tiles or has different component sockets.

Example:

MatchFilter (Entity Function)

Check if this entity matches an entity filter

Example:

ExistsOnFaction (Entity Function)

Check if this entity still exists and is owned by a given faction

Example:

AddHealth (Entity Function)

Add health (cannot exceed max_health)
This does nothing if the entity is at 0 health (because it is in the process of being destroyed)

Example:

RemoveHealth (Entity Function)

Remove health while handling any damage reduction by shield components
This does nothing if the entity is at 0 health (because it is in the process of being destroyed)

Example:

Entity Variables

key (Entity Variable)

A unique numerical identifier of this entity
Value: key (integer)
Access: read only

Example:

id (Entity Variable)

The frame id of this entity
Value: frame id (frame-id-string)
Access: read only

Example:

def (Entity Variable)

The frame definition table of this entity
Value: frame definition table (table)
Access: read only

Example:

visual_id (Entity Variable)

The visual id of this entity
Value: visual id (visual-id-string)
Access: read only

Example:

visual_def (Entity Variable)

The visual definition table of this entity
Value: visual definition table (table)
Access: read only

Example:

components (Entity Variable)

Get an array with all components of this entity (hidden and visible)
It is not possible to overwrite or add items to this array
Value: Component array table (table)
Access: read only

Example:

slots (Entity Variable)

Get an array with all item slots of this entity
It is not possible to overwrite or add items to this array
Value: Item slot array table (table)
Access: read only

Example:

has_extra_data (Entity Variable)

Check if extra_data has been created for this entity
Value: Result (boolean)
Access: read only

Example:

extra_data (Entity Variable)

Access to the extra data table of this entity
Reading it will always return a valid table when (will be created if not set yet)
Writing nil to it will free the table from memory
Value: Extra data table (table)
Access: read & write

Example:

faction (Entity Variable)

The faction of this entity
Value: Faction object (faction)
Access: read & write

Example:

visibility_range (Entity Variable)

The visibility range of this entity
Must be between 0 and 255
Value: Visibility range (integer)
Access: read & write

Example:

component_boost (Entity Variable)

The component efficiency boost of this entity in percent
Must be between 0 and 2550, can only be set to increments of 10 (default 100).
Value: Component efficiency percent (integer)
Access: read & write

Example:

move_boost (Entity Variable)

The move speed boost of this entity in percent
Must be between 0 and 2550, can only be set to increments of 10 (default 100).
Value: Move speed boost percent (integer)
Access: read & write

Example:

max_health (Entity Variable)

The maximum health of this entity
Must be between 1 and 65535
Value: Maximum health (integer)
Access: read & write

Example:

health (Entity Variable)

The health of this entity
For adding/removing health it is preferred to use the AddHealth/RemoveHealth functions
Changing the amount does nothing if the entity is at 0 health (because it is in the process of being destroyed)
Value: Health (integer)
Access: read & write

Example:

is_damaged (Entity Variable)

Check if the entity is not at max health
Value: Damaged state (boolean)
Access: read only

Example:

exists (Entity Variable)

Check if this entity still exists or if it was destroyed
Value: Exist state (boolean)
Access: read only

Example:

efficiency (Entity Variable)

The power efficiency of this entity
Value: Efficiency from 0 to 100 (or nil if entity has no power data) (integer)
Access: read only

Example:

power_grid_index (Entity Variable)

The index of the power grid this entity is in
Value: Grid index (or nil if entity is not inside a power grid) (integer)
Access: read only

Example:

has_power (Entity Variable)

Check if power is available
This can be true even if other power variables (i.e. efficiency or power_details) return nil when the entity is placed inside a power grid.
For docked entities it will check the availability for the outer garage entity placed on the map.
Value: Power availability (boolean)
Access: read only

Example:

extra_power (Entity Variable)

The dynamic extra power supplied/consumed by this entity
Value: Amount of power supplied (positive value) or consumed (negative value) (integer)
Access: read & write

Example:

extra_transfer_range (Entity Variable)

The dynamic extra power range of this entity
Value: Extra power range in tiles (integer)
Access: read & write

Example:

power_range (Entity Variable)

The power range of this entity
Value: power range (integer)
Access: read only

Example:

power_details (Entity Variable)

Get a table with power details about this entity
Building this table is slow so avoid reading it multiple times.
Value: Details table (or nil if entity has no power data) (table)
Access: read only

Example:

battery_percent (Entity Variable)

Get a percent number how full all equipped batteries are
Value: Percentage 0 to 100 (integer)
Access: read only

Example:

battery_stored (Entity Variable)

Get the summed up number of stored power in all equipped batteries
Value: Stored power amount (integer)
Access: read only

Example:

battery_total (Entity Variable)

Get the summed up total capacity of all equipped batteries
Value: Stored power amount (integer)
Access: read only

Example:

animation_speed (Entity Variable)

Material animation speed if supported by the visual
Value: animation speed (integer)
Access: read & write

Example:

light_color (Entity Variable)

Set light color (RGB) and intensity (A) if supported by the visual
Value: RGBA light color value (color)
Access: read & write

Example:

location (Entity Variable)

The location of this entity
For entities larger than 1x1 this is different than placed_location as it designates the location in the center of an entity.
Will return the last used location for entities not placed on map.
Value: Location (coordinate)
Access: read only

Example:

placed_location (Entity Variable)

The location where this entity is placed
For entities larger than 1x1 this is different than location as it designates the placed location (top left corner) of an entity.
Will return the last used location for entities not placed on map.
Value: Placed Location (coordinate)
Access: read only

Example:

location_hash (Entity Variable)

A hashed number representing the location of this entity
Can be used to easier check if an entity has been moved.
Value: Location hash (integer)
Access: read only

Example:

size (Entity Variable)

The tile size of this entity
Value: Size (coordinate)
Access: read only

Example:

area (Entity Variable)

The position and size of this entity as an array table
Value: Area ({ x, y, width, height } (area, coordinate or entity)
Access: read only

Example:

rotation (Entity Variable)

The rotation of this entity
Value: Rotation (0 to 3) (integer)
Access: read only

Example:

move_goal (Entity Variable)

Get the goal coordinate of the current movement path
Value: Goal coordinate (or nil if not moving) (coordinate)
Access: read only

Example:

is_moving (Entity Variable)

Check if the entity is moving
Value: Movement state (boolean)
Access: read only

Example:

has_movement (Entity Variable)

Check if this entity has movement
Value: True if the entity has movement (boolean)
Access: read only

Example:

is_placed (Entity Variable)

Check if this entity is placed on the map
Value: Placed on the map state (when true, is_docked is always false) (boolean)
Access: read only

Example:

is_on_map (Entity Variable)

Check if this entity is on the map
Value: On the map state (has either is_placed or is_docked_on_map) (boolean)
Access: read only

Example:

is_docked (Entity Variable)

Check if this entity is docked
Value: Docked state (when true, is_placed is always false) (boolean)
Access: read only

Example:

is_docked_on_map (Entity Variable)

Check if this entity is docked into something that either has is_placed or is_docked_on_map
Value: Docked on the map state (when true, is_docked is always true and is_placed is always false) (boolean)
Access: read only

Example:

docked_garage (Entity Variable)

The garage this entity is docked in
Value: Garage entity (nil if not docked) (entity)
Access: read only

Example:

reserved_redock_entity (Entity Variable)

The garage entity this entity was autonomously undocked from
Value: Entity for redocking (nil if not autonomously undocked) (entity)
Access: read only

Example:

disconnected (Entity Variable)

Disconnected from logistics network state of this entity
Value: Disconnected state (boolean)
Access: read & write

Example:

powered_down (Entity Variable)

Controls the power down state of an entity.
Value: Power down state (boolean)
Access: read & write

Example:

stealth (Entity Variable)

Controls the stealth effect of an entity.
Value: Stealth state (boolean)
Access: read & write

Example:

lootable (Entity Variable)

The lootable flag of this entity sets if all factions are able to take out items in its inventory
Value: Lootable flag (boolean)
Access: read & write

Example:

has_blight_shield (Entity Variable)

The 'has blight shield' flag of this entity sets if the entity can go into the blight
Note: If the entity belongs to a faction with has_blight_shield set this will always return true.
Value: Flag value (boolean)
Access: read & write

Example:

has_landing_pad (Entity Variable)

The 'has landing pad' flag of this entity sets if orders of this entity can interact with flyers
Value: Flag value (boolean)
Access: read & write

Example:

logistics_channel_1 (Entity Variable)

The 'logistics channel 1' flag of this entity sets if the entity is connected to this channel of the logistics network (default on)
Value: Flag value (boolean)
Access: read & write

Example:

logistics_channel_2 (Entity Variable)

The 'logistics channel 2' flag of this entity sets if the entity is connected to this channel of the logistics network (default off)
Value: Flag value (boolean)
Access: read & write

Example:

logistics_channel_3 (Entity Variable)

The 'logistics channel 3' flag of this entity sets if the entity is connected to this channel of the logistics network (default off)
Value: Flag value (boolean)
Access: read & write

Example:

logistics_channel_4 (Entity Variable)

The 'logistics channel 4' flag of this entity sets if the entity is connected to this channel of the logistics network (default off)
Value: Flag value (boolean)
Access: read & write

Example:

logistics_supplier (Entity Variable)

The 'logistics supplier' flag of this entity sets if the entity is connected to the logistics network as a supplier (default on)
Value: Flag value (boolean)
Access: read & write

Example:

logistics_requester (Entity Variable)

The 'logistics supplier' flag of this entity sets if the entity is connected to the logistics network as a requester (default on)
Value: Flag value (boolean)
Access: read & write

Example:

logistics_carrier (Entity Variable)

The 'logistics carrier' flag of this entity sets if the entity is connected to the logistics network as a carrier (default on)
Value: Flag value (boolean)
Access: read & write

Example:

logistics_crane_only (Entity Variable)

The 'logistics crane only' flag of this entity sets if the carrier of an order from or to this entity must be a building with a crane (default off)
Value: Flag value (boolean)
Access: read & write

Example:

logistics_flying_only (Entity Variable)

The 'logistics flying only' flag of this entity sets if the carrier of an order from or to this entity must be a flying unit (default off)
Value: Flag value (boolean)
Access: read & write

Example:

logistics_can_construction (Entity Variable)

The 'logistics can_construction' flag of this entity sets if the carrier of an order can service a construction entity (default on)
Value: Flag value (boolean)
Access: read & write

Example:

logistics_transport_route (Entity Variable)

The 'logistics transport route' flag of this entity sets if the unit will always pick up at GOTO and deliver everything to STORE (default off)
Value: Flag value (boolean)
Access: read & write

Example:

logistics_high_priority (Entity Variable)

The 'logistics high priority' flag of this entity sets if orders requested by this entity are flagged as high priority (default off)
Value: Flag value (boolean)
Access: read & write

Example:

has_crane (Entity Variable)

The 'has crane' flag of this entity is set if crane_range has been set to a value larger than 0
Value: Flag value (boolean)
Access: read only

Example:

crane_range (Entity Variable)

Set this to a value larger than 0 to enable the crane functionality on an entity
Value: Crane range (0 = disabled, 255 = maximum) (integer)
Access: read & write

Example:

is_construction (Entity Variable)

Check if this entity is a construction site
Value: Construction site (boolean)
Access: read only

Example:

state_idle (Entity Variable)

The 'idle' state of this entity is set when an entity does not have its movement controlled for a while
Value: State value (boolean)
Access: read only

Example:

state_path_blocked (Entity Variable)

The 'path blocked' state of this entity is set when movement fails to complete a path
Value: State value (boolean)
Access: read only

Example:

state_inefficient (Entity Variable)

The 'inefficient' state of this entity is set when running not at 100% efficiency
Value: State value (boolean)
Access: read only

Example:

state_unpowered (Entity Variable)

The 'unpowered' state of this entity is set when out of power (but not shut down)
Value: State value (boolean)
Access: read only

Example:

state_emergency (Entity Variable)

The 'emergency' state of this entity is set when health is below 75%
Value: State value (boolean)
Access: read only

Example:

state_broken (Entity Variable)

The 'broken' state of this entity is set when health is below 25%
Value: State value (boolean)
Access: read only

Example:

state_custom_1 (Entity Variable)

The custom state 1 flag of this entity (to be used freely by lua)
Value: State value (boolean)
Access: read & write

Example:

state_custom_2 (Entity Variable)

The custom state 2 flag of this entity (to be used freely by lua)
Value: State value (boolean)
Access: read & write

Example:

state_custom_3 (Entity Variable)

The custom state 3 flag of this entity (to be used freely by lua)
Value: State value (boolean)
Access: read & write

Example:

state_custom_4 (Entity Variable)

The custom state 4 flag of this entity (to be used freely by lua)
Value: State value (boolean)
Access: read & write

Example:

idle_mode (Entity Variable)

Get the current idle mode describing what currently controls the bots movement
Value: Mode (IDLE/STORE/MOVE/ORDER/COMPONENT/DROP/INTERACT/RETURN) ("IDLE" | "STORE" | "MOVE" | "ORDER" | "COMPONENT" | "DROP" | "INTERACT" | "RETURN")
Access: read only

Example:

controlling_component (Entity Variable)

Get the component in control of the bots movement (or nil if none)
Value: Component in control (component)
Access: read only

Example:

active_order (Entity Variable)

Get currently executing order (or nil if none)
Value: Order info (or nil) (table)
Access: read only

Example:

has_component_list (Entity Variable)

Check if the entity has a component list and can have components
Value: Result (boolean)
Access: read only

Example:

component_count (Entity Variable)

Gets the number of components
Value: number of components (0 if the entity has no component list) (integer)
Access: read only

Example:

socket_count (Entity Variable)

Gets the number of sockets available on the visual of this entity
Value: number of sockets (integer)
Access: read only

Example:

slot_count (Entity Variable)

Gets the number of item slots
Value: number item slots (0 if the entity has no inventory) (integer)
Access: read only

Example:

register_count (Entity Variable)

Gets the number of all registers (frame and component registers)
Value: number of registers (0 if the entity has no registry) (integer)
Access: read only

Example:

frame_register_count (Entity Variable)

Check or change the number of frame registers (can't be less than FRAMEREG_COUNT)
Value: Number of frame registers (or nil if the entity has no registry) (integer)
Access: read & write

Example:

most_relevant_state (Entity Variable)

Gets most relevant state
Value: most relevant state name ("None" | "Idle" | "PoweredDown" | "PathBlocked" | "Unpowered" | "Emergency" | "Broken" | "LuaCustom1" | "LuaCustom2" | "LuaCustom3" | "LuaCustom4")
Access: read only

Example:

all_states (Entity Variable)

Gets all states affecting an entity (broken, path blocked, powered down, etc.)
Value: an array of all state names affecting the unit (table)
Access: read only

Example:

render_instances (Entity Variable)

Get number of render instances associated with this entity
Value: Count (integer)
Access: read only

Example:

has_active_effects (Entity Variable)

Check if there are any looping effects playing on this entity
Value: Result (boolean)
Access: read only

Example:

idle_ticks (Entity Variable)

Return the number of ticks this entity has been idle for
Value: Idle tick count (integer)
Access: read only

Example:

triggered_components (Entity Variable)

Get an array with all components currently triggered by this entity being in their trigger_radius
Value: Component array (table)
Access: read only

Example:

interpolated_location (Entity Variable)

The location of the entity, interpolated to the rendered frame while moving (only accessible by UI)
The Z coordinate will be the height of the ground under the entity
Value: Interpolated 3D location (x, y and z as floating point numbers) (3d coordinate)
Access: read only

Example:

interpolated_center (Entity Variable)

The center position of the entity, interpolated to the rendered frame while moving (only accessible by UI)
The Z coordinate will be adjusted to be in the center of the entity
Value: Interpolated 3D position (x, y and z as floating point numbers) (3d coordinate)
Access: read only

Example:

interpolated_rotation (Entity Variable)

The rotation of the entity in degrees, interpolated to the rendered frame while moving (only accessible by UI)
Value: Interpolated rotation in degrees (number)
Access: read only

Example:

interpolated_direction (Entity Variable)

The forward direction of the entity, interpolated to the rendered frame while moving (only accessible by UI)
Value: Interpolated 3D direction (x, y and z as floating point numbers) (3d coordinate)
Access: read only

Example:

Entity Operators

ToString Operator (Entity Operator)

Example:

Equality Operator (Entity Operator)

Example:

Meta Table: EventListener

A global event listener used for various APIs

Source: /Source/Desynced/Lua/Meta/DSEventListenerLuaMeta.cpp

EventListener Functions

Bind (EventListener Function)

Bind a function to this listener, usually done with a function assignment like
function LISTENER.FUNCTIONNAME(arg1, arg2) ... end
Only use this if you want to explicitly unbind the function later.

Example:

Unbind (EventListener Function)

Unbind a specific function from this listener
Depending on the type of this listener unbinding functions might not be supported.

Example:

UnbindAll (EventListener Function)

Unbind all functions bound to a given name
Depending on the type of this listener unbinding functions might not be supported.

Example:

EventListener Operators

Index Operator (EventListener Operator)

Depending on context or the type of this listener calling a bound function might not be supported.

Example:

NewIndex Operator (EventListener Operator)

Bind a function to this listener, usually done with a function assignment like
function LISTENER.FUNCTIONNAME(arg1, arg2) ... end

Example:

Meta Table: Faction

A faction object represents a player or world owned faction.

Source: /Source/Desynced/Lua/Meta/DSFactionLuaMeta.cpp

Faction Functions

Unlock (Faction Function)

Unlock something

Example:

IsUnlocked (Faction Function)

Check if something was unlocked

Example:

IsResearchable (Faction Function)

Check if a tech is available for research

Example:

HavePickedUpItem (Faction Function)

Check if an item was picked up

Example:

GetPowerGrids (Faction Function)

Get stats on all power grids of this faction

Example:

GetPowerGrid (Faction Function)

Get stats on all power grids of this faction

Example:

GetPowerGridIndexAt (Faction Function)

Check if a tile or area is in a power grid of this faction
If the checking area is larger than one tile, will only return the first power grid found.

Example:

GetPowerHistory (Faction Function)

Get the history of power
If the requested number of elements is larger than history buffer, the arrays will be filled with zeros
If the requested number of elements is 1, the function will return the numbers directly instead of an array

Example:

GetItemHistory (Faction Function)

Get the history of an item held by the faction
If the requested number of elements is larger than history buffer, the arrays will be filled with zeros
If the requested number of elements is 1, the function will return the numbers directly instead of an array

Example:

GetItemAmount (Faction Function)

Get the total amount currently available of an item

Example:

GetItemAvailability (Faction Function)

Get a table of all entities that hold a specific item

Example:

GetItemTotals (Faction Function)

Get the total amount of generated (mined/produced) and consumed (as ingredients) for an item

Example:

ModifyItemTotals (Faction Function)

Modify the total amount of generated (mined/produced) and consumed (as ingredients) for an item

Example:

GetActiveOrders (Faction Function)

Get a list of all active orders

Example:

GetNumActiveOrders (Faction Function)

Get the count of all active orders

Example:

CancelOrder (Faction Function)

Cancel an existing order

Example:

OrderTransfer (Faction Function)

Create order to move items from one entity to another
Either source or target entity must be owned by this faction

Example:

CanPlace (Faction Function)

Check if a specific frame/visual combination can be placed by this faction at a given location
If the construction flag is set, the check will return true if checking a location over entities with movement that can move out of the way.
If 'return blocking buildings' is true, the check will not fail on blocking buildings of the same faction but instead the function will return a second value with a table array containing the blocked buildings.

Example:

GetPlaceableLocation (Faction Function)

Return the closest location where CanPlace would return true

Example:

RevealArea (Faction Function)

Reveal visibility of an area

Example:

HideArea (Faction Function)

Hide visibility of an area

Example:

IsVisible (Faction Function)

Check if a tile or area is currently visible to this faction

Example:

IsDiscovered (Faction Function)

Check if a tile or area has been revealed by this faction

Example:

IsSeen (Faction Function)

Check if an entity is visible to this faction (true for everything in visible are as well as certain entities in discovered tiles)

Example:

FindClosestHiddenTile (Faction Function)

Finds closest non visible tile

Example:

RunUI (Faction Function)

Run code in UI context or call bound UIMsg functions
When called from simulation context the function will execute for all players in this faction (to limit to other players use UI.Run or Action.RunUI)
When called from UI context the function will only execute for the local player if it is in this faction

Example:

OrderEntitiesToMoveAway (Faction Function)

Order movable entities to move away from a given area

Example:

UpdateEntityInRegisters (Faction Function)

Faction wide change all references in registers of one entity to point towards another
Will also update the home_entity if that is set to the old entity

Example:

Respawn (Faction Function)

Respawn the faction

Example:

AddMood (Faction Function)

Add some amount to one of the faction moods

Example:

GetComponents (Faction Function)

Get all components of a given type equipped by entities of this faction

Example:

GetEntitiesWithComponent (Faction Function)

Get all entities of this faction that have a given component equipped

Example:

GetEntitiesWithRegister (Faction Function)

Get all entities of this faction that have a specific frame register set, optionally filtered by id or entity

Example:

GetEntitiesWithId (Faction Function)

Get all entities of this faction with a given frame id
Cannot be used with foundation type frame ids

Example:

GetEntityWithId (Faction Function)

Check if this faction owns an entity with a given frame id, will return the first found entity or nil
Cannot be used with foundation type frame ids

Example:

GetVisibleEntities (Faction Function)

Get all entities owned by this faction that are on screen (excludes foundation entities)
If true gets passed, the 5th element will be either nil, a register value or an array with 3 elements per register (reg, x, y)
The states value is a bit-flag integer which can be passed to Tool.ParseEntityStates
The filter_state argument is a bit-flag integer which can be generated by Tool.EncodeEntityStates

Example:

SetTrust (Faction Function)

Set the trust level towards another faction
The trust level from/to the world faction and self can't be changed

Example:

GetTrust (Faction Function)

Get the trust level towards another faction

Example:

ResetTrust (Faction Function)

Reset any customized faction trust levels of this faction
Will make all factions bidirectionally revert to default trust level in regards to this faction

Example:

GetSharedVisibilityCount (Faction Function)

Check if this faction is sharing visibility with anyone and with how many other factions visibility is shared with

Example:

IsSharingVisibilityWith (Faction Function)

Check if this faction is sharing visibility with another factions

Example:

ShareVisibility (Faction Function)

Share visibility with another faction

Example:

UnshareVisibility (Faction Function)

Unshare visibility with other factions

Example:

Faction Variables

is_world_faction (Faction Variable)

Check if this faction is the world faction
Value: True if world faction (boolean)
Access: read only

Example:

is_player_controlled (Faction Variable)

Check if this faction was created to be controlled by players
Value: True if created for a player (boolean)
Access: read only

Example:

has_logged_in_player (Faction Variable)

Check if this faction has a logged in player
Value: True if a player is currently logged in to this faction (boolean)
Access: read only

Example:

default_trust (Faction Variable)

The default trust level towards other factions
Value: Default trust level, one of 'ENEMY', 'NEUTRAL' or 'ALLY' ("ENEMY" | "NEUTRAL" | "ALLY")
Access: read & write

Example:

entities (Faction Variable)

Get entities owned by this faction (excludes foundation entities)
Value: Table with a list of all entities (table)
Access: read only

Example:

num_entities (Faction Variable)

Get the number of entities owned by this faction (excludes foundation entities)
Value: number of entities (integer)
Access: read only

Example:

num_operating_entities (Faction Variable)

Get the number of operating entities placed by this faction
Value: number of operating entities (integer)
Access: read only

Example:

num_unlocked_techs (Faction Variable)

Get the number of unlocked techs
Value: number of unlocked techs (integer)
Access: read only

Example:

foundation_entities (Faction Variable)

Get foundation entities owned by this faction
Value: Table with a list of foundation entities (table)
Access: read only

Example:

all_items (Faction Variable)

Get all resources available to this faction
Value: item_id => count (table)
Access: read only

Example:

has_extra_data (Faction Variable)

Check if extra_data has been created for this faction
Value: Result (boolean)
Access: read only

Example:

extra_data (Faction Variable)

Access to the extra data table of this faction
Reading it will always return a valid table when (will be created if not set yet)
Writing nil to it will free the table from memory
Value: Extra data table (table)
Access: read & write

Example:

has_blight_shield (Faction Variable)

The 'has blight shield' flag of this faction sets if its entities can go into the blight
Value: Flag value (boolean)
Access: read & write

Example:

id (Faction Variable)

The id of this faction
Value: Faction id (faction-id-string)
Access: read only

Example:

component_boost (Faction Variable)

The component efficiency boost of this faction in percent (default 100).
Value: Component efficiency percent (integer)
Access: read & write

Example:

index (Faction Variable)

The index of this faction in the faction array of the map
Value: Faction id (faction-id-string)
Access: read only

Example:

name (Faction Variable)

The name of this faction
If not explicitly set, returns the name of the first player controlling this faction.
If not set and no player is controlling the faction, returns just the id.
Value: Name (string)
Access: read & write

Example:

seed (Faction Variable)

This returns a completely random number for this faction assigned at spawn time independent of the map seed
Value: Faction seed (integer)
Access: read only

Example:

unlocks (Faction Variable)

Get list of unlocked things
Value: List of unlocked ids (table)
Access: read only

Example:

unlocked_techs (Faction Variable)

Get list of unlocked techs
Value: tech id list (table)
Access: read only

Example:

unlocked_items (Faction Variable)

Get list of unlocked items (does not include frames or components)
Value: item id list (table)
Access: read only

Example:

unlocked_frames (Faction Variable)

Get list of unlocked frames
Value: frame id list (table)
Access: read only

Example:

unlocked_components (Faction Variable)

Get list of unlocked components
Value: component id list (table)
Access: read only

Example:

unlocked_values (Faction Variable)

Get list of unlocked values
Value: value id list (table)
Access: read only

Example:

unlocked_codex (Faction Variable)

Get list of unlocked codex entries
Value: codex id list (table)
Access: read only

Example:

researchable_techs (Faction Variable)

Get list of all techs available for research
Value: tech id list (table)
Access: read only

Example:

items_picked_up (Faction Variable)

Get list of all picked up items
Value: item id list (table)
Access: read only

Example:

discovered_tiles (Faction Variable)

Get the total number of visibility tiles this faction has revealed
Value: Discovered tiles count (integer)
Access: read only

Example:

moods (Faction Variable)

Get table of faction moods
Value: faction mood table (table)
Access: read only

Example:

color (Faction Variable)

The faction color
Can only be modified before the first entity is created for this faction
Value: Faction color (color)
Access: read & write

Example:

home_location (Faction Variable)

Faction home/start location
If home_entity is set and exists, it will override what is returned when getting the location
Value: Location (coordinate)
Access: read & write

Example:

home_entity (Faction Variable)

Faction home/start entity
Setting a home entity will also set the home location to that entities location
Value: Home entity (entity)
Access: read & write

Example:

Faction Operators

ToString Operator (Faction Operator)

Example:

Equality Operator (Faction Operator)

Example:

Meta Table: ItemSlot

An item slot object represents one slot of the inventory of an entity.

Source: /Source/Desynced/Lua/Meta/DSItemSlotLuaMeta.cpp

ItemSlot Functions

SetItemAndStack (ItemSlot Function)

Sets the content of an empty slot

Example:

AddStack (ItemSlot Function)

Add amounts in this slot (must have an item in it).
If the new amount is higher than stack + unreserved_space it will fail with an error.

Example:

RemoveStack (ItemSlot Function)

Add or remove amounts in this slot (must have an item in it).
If the new amount is lower than reserved_stack it will fail with an error.
If the new amount is zero, the item will be cleared from the slot
and the stack can't be modified again until the item is put in again.
This cannot be used to remove stack of something with extra_data (use Clear)

Example:

Clear (ItemSlot Function)

Clear the content in this slot

Example:

SetLockedItem (ItemSlot Function)

Sets the item and locks an otherwise empty slot

Example:

Swap (ItemSlot Function)

Swap the entire contents (including reservations) of two slots of the same slot type on the same inventory

Example:

Move (ItemSlot Function)

Move as much as possible (including reservations) into another slot on the same inventory

Example:

GetReserveInfo (ItemSlot Function)

Gets all the reserve information relative to this slot

Example:

CancelOrders (ItemSlot Function)

Cancel all orders related to this item slot

Example:

OrderItem (ItemSlot Function)

Order an item into this slot
The order will stay active until fulfilled, CancelOrder gets called, the slot is removed or the entity is destroyed.
Additionally if a component is specified, the order gets canceled when the component becomes inactive or when component:CancelProcess is called.
If an order already exists on the same item slot and no source slot is specified, it will be modified to the new amount requested.
If modifying an order and amount is less than already ordered (or 0), existing order(s) will get adjusted to the new amount (or aborted).
Will return nil on invalid item or amount or if not enough free space available in the slot.

Example:

GetUnreservedSpaceFor (ItemSlot Function)

The amount of free space actually available to be filled with a specific item (slot can be empty)

Example:

CountGenerateAmount (ItemSlot Function)

Get how many items a component with a prepared process is generating into this slot

Example:

CountConsumeAmount (ItemSlot Function)

Get how many items a component with a prepared process is consuming from this slot

Example:

ItemSlot Variables

id (ItemSlot Variable)

The item id in this slot
Value: Item id (or nil if no item in slot) (item-id-string)
Access: read only

Example:

def (ItemSlot Variable)

The definition table of the item in this slot
Value: Item definition (or nil if no item in slot) (table)
Access: read only

Example:

stack (ItemSlot Variable)

The amount of items in this slot
Modification is only possible for slots with an item in it.
On modification, if the new amount is lower than reserved_stack or
higher than stack + unreserved_space it will fail with an error.
If the new amount is zero, the item will be cleared from the slot
and the stack can't be modified again until the item is put in again.
Value: Amount (is 0 if no item in slot) (integer)
Access: read & write

Example:

max_stack (ItemSlot Variable)

Get the maximum stack count of the item in this slot
Value: Amount (is 0 if no item in slot) (integer)
Access: read only

Example:

reserved_stack (ItemSlot Variable)

The amount of reserved items for ingredients or outgoing orders
Value: Reserved amount (integer)
Access: read only

Example:

unreserved_stack (ItemSlot Variable)

The amount of items not reserved for ingredients or outgoing orders
Value: Unreserved amount (integer)
Access: read only

Example:

reserved_space (ItemSlot Variable)

The amount of free space reserved for generation or incoming orders
Value: Reserved free space count (integer)
Access: read only

Example:

unreserved_space (ItemSlot Variable)

The amount of free space actually available to be filled (slot must have an item in it)
Value: Unreserved free space count (integer)
Access: read only

Example:

has_order (ItemSlot Variable)

Check if there exists any order related to this slot
Value: Check result (boolean)
Access: read only

Example:

owner (ItemSlot Variable)

The entity that owns this slot
Value: Entity (entity)
Access: read only

Example:

exists (ItemSlot Variable)

Check if this item slot and its owning entity still exists or if it was unequipped or destroyed
Value: Exist state (boolean)
Access: read only

Example:

entity (ItemSlot Variable)

The entity docked in this slot
It can only be set to a valid entity if there is nothing in it currently.
To undock an already docked entity onto the map use entity:Undock().
To remove a docked entity without placing it onto the map set entity to nil.
Value: Entity (is nil if no entity in slot) (entity)
Access: read & write

Example:

reserved_entity (ItemSlot Variable)

An entity that has been undocked but is reserved to come back (usually tethered entity)
Value: Entity (is nil if no entity is reserved to come back to this slot) (entity)
Access: read only

Example:

component (ItemSlot Variable)

The component that holds this slot
Value: Component object or nil if none (component)
Access: read only

Example:

type (ItemSlot Variable)

The type of slot
Value: Slot type (string)
Access: read only

Example:

has_extra_data (ItemSlot Variable)

Check if extra_data has been created for this item slot
Value: Result (boolean)
Access: read only

Example:

extra_data (ItemSlot Variable)

Access to the extra data table of the item in this slot
Extra data can only be set for unstackable items
Reading it will always return a valid table when (will be created if not set yet)
Writing nil to it will free the table from memory
Value: Extra data table (table)
Access: read & write

Example:

locked (ItemSlot Variable)

Is this item slot locked from changing item def?
Value: Locked (boolean)
Access: read & write

Example:

ItemSlot Operators

ToString Operator (ItemSlot Operator)

Example:

Equality Operator (ItemSlot Operator)

Example:

Meta Table: ModPackage

A mod package object represents a loaded mod package currently active in the game.

Startup sequence (each step is performed on all active mod packages in dependency order where packages with no dependencies are called first):

  1. Run the entry lua file of all active mod packages
  2. When starting a new game, run the function package:setup_scenario(settings). This function can modify the settings table. This step is skipped when loading a save or joining a multiplayer game.
  3. Load all files set in package:includes and call either package:init_ui() or package:init(). The function init_ui is not called when there is no local player (i.e. on a dedicated servre). Packages with init_ui are allowed to write to local variables defined outside of the function scope.
  4. Call package:post_init()
  5. When starting a new game, run the function package:on_world_spawn()
  6. For the local player or any newly joining multiplayer players, run the function package:get_new_player_faction_id(faction_id) which can return a faction id to be used for that player (only called on server!). The passed faction_id will be nil on the first package this is called on.
  7. When a new player faction is spawned or respawned, run the function package:on_player_faction_spawn(faction, is_respawn, player_faction_num)

Source: /Source/Desynced/Lua/Meta/DSModPackageLuaMeta.cpp

ModPackage Variables

id (ModPackage Variable)

Get the package id
Value: Id value (string)
Access: read only

Example:

name (ModPackage Variable)

Get the package name
Value: Name value (string)
Access: read only

Example:

description (ModPackage Variable)

Get the package description
Value: Name value (string)
Access: read only

Example:

entry (ModPackage Variable)

Get the package entry file
Value: Entry value (string)
Access: read only

Example:

type (ModPackage Variable)

Get the package type
Value: Type (string)
Access: read only

Example:

dependencies (ModPackage Variable)

Get the dependencies list
Value: Dependency array (table)
Access: read only

Example:

modes (ModPackage Variable)

Get the multiplayer game modes list
Value: Modes array (table)
Access: read only

Example:

mod_id (ModPackage Variable)

Get the mod id
Value: id value (string)
Access: read only

Example:

mod_name (ModPackage Variable)

Get the mod name
Value: name value (string)
Access: read only

Example:

mod_version_name (ModPackage Variable)

Get the mod version name
Value: version value (string)
Access: read only

Example:

mod_version_code (ModPackage Variable)

Get the mod version code
Value: version value (string)
Access: read only

Example:

mod_author (ModPackage Variable)

Get the mod author
Value: author value (string)
Access: read only

Example:

mod_homepage (ModPackage Variable)

Get the mod homepage
Value: homepage value (string)
Access: read only

Example:

mod_description (ModPackage Variable)

Get the mod description
Value: description value (string)
Access: read only

Example:

includes (ModPackage Variable)

Load a lua file or all lua files in a sub directory of this mod
Value: List of included lua file paths (table)
Access: read & write

Example:

Meta Table: Register

A register object represents the content of a register of an entity.
Unlike many other objects, it is not a reference to a game object but a copy.
Therefore after modification, the value needs to be written back with SetRegister.

Source: /Source/Desynced/Lua/Meta/DSRegisterLuaMeta.cpp

Register Functions

Clear (Register Function)

Clear contents

Example:

Init (Register Function)

Copy contents from another register or table

Example:

Register Variables

num (Register Variable)

The number stored in this register
Value: Number (integer)
Access: read & write

Example:

id (Register Variable)

The generic id stored in this register
Value: Id (id-string)
Access: read & write

Example:

def (Register Variable)

The definition table of the id stored in this register
Value: Definition table (or nil if none or unknown id) (table)
Access: read only

Example:

value_id (Register Variable)

The id stored in this register if it is referring to a value definition.
Can be a key from data.values, data.items, data.frames or data.components.
Value: Value id (value-id-string)
Access: read & write

Example:

item_id (Register Variable)

The id stored in this register if it is referring to an item definition.
Can be a key from data.items, data.frames or data.components.
Value: Item id (item-id-string)
Access: read & write

Example:

frame_id (Register Variable)

The id stored in this register if it is referring to a frame definition.
If this doesn't return nil, it will be a key from data.frames.
Value: Frame id (frame-id-string)
Access: read & write

Example:

component_id (Register Variable)

The id stored in this register if it is referring to a component definition.
If this doesn't return nil, it will be a key from data.components.
Value: Component id (component-id-string)
Access: read & write

Example:

tech_id (Register Variable)

The id stored in this register if it is referring to a tech definition.
If this doesn't return nil, it will be a key from data.techs.
Value: Tech id (tech-id-string)
Access: read & write

Example:

entity (Register Variable)

The entity stored in this register
This will return nil if there is a destroyed entity referenced in this register.
Value: Entity (entity)
Access: read & write

Example:

coord (Register Variable)

The coordinate stored in this register or nil if no coordinate is stored
Value: Coordinate (coordinate)
Access: read & write

Example:

coord_x (Register Variable)

The X coordinate stored in this register or nil if no coordinate is stored
Value: X coordinate (integer)
Access: read & write

Example:

coord_y (Register Variable)

The Y coordinate stored in this register or nil if no coordinate is stored
Value: Y coordinate (integer)
Access: read & write

Example:

raw_entity (Register Variable)

The raw entity value stored in this register
This will return the value as is stored, even if there is a destroyed entity referenced in this register.
Value: Entity (entity)
Access: read only

Example:

is_link (Register Variable)

Check if a register is linked from another register
Value: link state (boolean)
Access: read only

Example:

is_empty (Register Variable)

Check if a register is empty (or contains a reference to a destroyed entity while having number set to 0)
Value: Result (boolean)
Access: read only

Example:

raw_is_empty (Register Variable)

Check if a register is fully empty (true even if entity references a destroyed entity)
Value: Result (boolean)
Access: read only

Example:

is_error (Register Variable)

Check if a register is in error state
Value: Error (boolean)
Access: read only

Example:

Register Operators

ToString Operator (Register Operator)

Example:

Equality Operator (Register Operator)

Example:

Addition Operator (Register Operator)

Add two register values. While the left side of the operator always needs to be a register object, the right side can be a register, a table or an integer number.
If either side (or both) have a 2-dimensional coordinate, the result will also be a coordinate, otherwise it will be a number.

Example:

Subtraction Operator (Register Operator)

Subtract two register values. While the left side of the operator always needs to be a register object, the right side can be a register, a table or an integer number.
If either side (or both) have a 2-dimensional coordinate, the result will also be a coordinate, otherwise it will be a number.

Example:

Multiplication Operator (Register Operator)

Multiply two register values. While the left side of the operator always needs to be a register object, the right side can be a register, a table or an integer number.
If either side (or both) have a 2-dimensional coordinate, the result will also be a coordinate, otherwise it will be a number.

Example:

Division Operator (Register Operator)

Integer division of two register values. While the left side of the operator always needs to be a register object, the right side can be a register, a table or an integer number.
If either side (or both) have a 2-dimensional coordinate, the result will also be a coordinate, otherwise it will be a number.

Example:

Modulo Operator (Register Operator)

Modulo of two register values. While the left side of the operator always needs to be a register object, the right side can be a register, a table or an integer number.
If either side (or both) have a 2-dimensional coordinate, the result will also be a coordinate, otherwise it will be a number.

Example:

Meta Table: Widget

A widget object represents a UI object that is part of a layout tree.

Source: /Source/Desynced/Lua/Meta/DSWidgetLuaMeta.cpp

Widget Functions

IsValid (Widget Function)

Check if widget has not been removed yet

Example:

IsVisible (Widget Function)

Check if widget is visible on screen (self and no parent is hidden)

Example:

Add (Widget Function)

Add a widget to a panel widget

Example:

SetContent (Widget Function)

Set the content of a single-child panel widget

Example:

Clear (Widget Function)

Clear all widgets in a panel widget

Example:

GetChild (Widget Function)

Get a child widget

Example:

SortChildren (Widget Function)

Sort all child widgets

Example:

RemoveFromParent (Widget Function)

Remove a widget from its parent

Example:

SendEvent (Widget Function)

Invoke an event function
Similar to calling the function directly but will correctly pass the parent as self if invoking a function higher up the layout tree.

Example:

GetDesiredSize (Widget Function)

Get the desired size of a widget

Example:

SetPosition (Widget Function)

Set the position of a widget placed a canvas panel widget

Example:

GetViewportPosition (Widget Function)

Gets the viewport relative position (and size) of the widget
If a widget gets passed that hasn't had its layout calculated yet, the function will return nil

Example:

SetIgnoreHitTest (Widget Function)

Set this widget (and any children) to not interact with the mouse cursor (clicking or dragging over)

Example:

TweenTo (Widget Function)

Animate a numerical property

Example:

TweenFromTo (Widget Function)

Animate a numerical property

Example:

StopTween (Widget Function)

Stop an active tween

Example:

GetTweenTarget (Widget Function)

Get the target value of an active tween

Example:

FindAbove (Widget Function)

Find property in any widget above in the layout tree

Example:

Widget Variables

parent (Widget Variable)

Get the parent of a widget
Value: Parent widget (or nil if none) (widget)
Access: read only

Example:

root (Widget Variable)

Get the root (top-most parent) of a widget
Value: Root widget (can be self if there is no parent) (widget)
Access: read only

Example:

children (Widget Variable)

Get or set an array of child widgets
Value: Array of child widgets (table)
Access: read & write

Example:

child_count (Widget Variable)

Get number of child widgets
Cannot be set to a number larger than already exists
Value: Number of child widgets (integer)
Access: read & write

Example:

has_children (Widget Variable)

Check if child widgets exist
Value: True if there are any child widgets (boolean)
Access: read only

Example:

child_index (Widget Variable)

Get or set the child index of this widget in relation to its parent
Value: Child index (integer)
Access: read & write

Example:

next_sibling (Widget Variable)

Get the next sibling in the list of child widgets of the parent
Value: Next sibling (or nil if none) (widget)
Access: read only

Example:

previous_sibling (Widget Variable)

Get the previous sibling in the list of child widgets of the parent
Value: Previous sibling (or nil if none) (widget)
Access: read only

Example:

class (Widget Variable)

Get the table passed to UI.Register
Value: Class table (or nil if none) (table)
Access: read only

Example:

Widget Operators

Index Operator (Widget Operator)

Read properties of this widget

Example:

NewIndex Operator (Widget Operator)

Modify or add new properties of this widget

Example:

ToString Operator (Widget Operator)

Example:

Length Operator (Widget Operator)

Get number of child widgets (same as child_count)

Example:

Equality Operator (Widget Operator)

Example:

EULA    |    Privacy Policy    |    Presskit


© 2018-2025 Stage Games • All rights reserved