Desynced Lua API
Modules
Module: Action
The action module contains functions that send (player input) actions
Source: /Source/Desynced/Lua/Module/DSActionModule.cpp
- Functions
SendForLocalFaction (Action Function)
Send an action from the local player faction
A faction action can be registered with
function FactionAction.ACTIONID(faction, arg)
- Argument 1: Action id (string)
- Argument 2: Additional action data (can be nil) (table)
Example:
Action.SendForLocalFaction("text")Action.SendForLocalFaction("text", { ... })
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)
- Argument 1: Action id (string)
- Argument 2: Entity the action is for (must be owned by the local player) (entity)
- Argument 3: Additional action data (can be nil) (table)
Example:
Action.SendForEntity("text", other_entity)Action.SendForEntity("text", other_entity, { ... })
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
- Argument 1: Action id (string)
- Argument 2: Additional action data (can be nil) (table)
Example:
Action.SendForSelectedEntities("text")Action.SendForSelectedEntities("text", { ... })
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
- Argument 1: Action id (string)
- Argument 2: Array of entities the action is for (table)
- Argument 3: Additional action data (can be nil) (table)
Example:
Action.SendForEntities("text", { ... })Action.SendForEntities("text", { ... }, { ... })
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)
- Argument 1: Action id (string)
- Argument 2: Entity the action is for (must be under construction and owned by the local player) (entity)
- Argument 3: Additional action data (can be nil) (table)
Example:
Action.SendForConstruction("text", other_entity)Action.SendForConstruction("text", other_entity, { ... })
SendFromPlayer (Action Function)
Send an action from the player
A player action can be registered with
function PlayerAction.ACTIONID(player_id, faction, arg)
- Argument 1: Action id (string)
- Argument 2: Additional action data (can be nil) (table)
Example:
Action.SendFromPlayer("text")Action.SendFromPlayer("text", { ... })
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)
- Argument 1: LUA function to execute in UI context (function)
- Argument 2: Passed values (OPTIONAL, can pass multiple values) (anything)
--- or --- - Argument 1: Message name registered in UIMsg (string)
- Argument 2: Passed values (OPTIONAL, can pass multiple values) (anything)
Example:
Action.RunUI(function() ... end)Action.RunUI(function() ... end, ...)Action.RunUI("text")Action.RunUI("text", ...)
SetPlayerReady (Action Function)
Set player ready during the startup of a scenario using DelayedPlayerFactionSpawn mode
- Argument 1: Ready state (OPTIONAL, default true) (boolean)
Example:
Action.SetPlayerReady()Action.SetPlayerReady(true)
IsReplayPlayback (Action Function)
Returns if a replay is being played back
- Return Value: Replay state (boolean)
Example:
local flag = Action.IsReplayPlayback()
GetReplayProgress (Action Function)
Returns the playback progress of the replay
- Argument 1: Return the time in in-game days instead of ticks (OPTIONAL, default false) (boolean)
- Return Value: Ticks or days since replay start (number)
Example:
local num = Action.GetReplayProgress()local num = Action.GetReplayProgress(true)
GetReplayDuration (Action Function)
Returns the total duration of the replay
- Argument 1: Return the time in in-game days instead of ticks (OPTIONAL, default false) (boolean)
- Return Value: Duration in ticks or days (number)
Example:
local num = Action.GetReplayDuration()local num = Action.GetReplayDuration(true)
SetReplaySpeed (Action Function)
Set replay playback speed
- Argument 1: Replay speed (number)
Example:
Action.SetReplaySpeed(1)
SetReplayViewFaction (Action Function)
Set replay viewed faction
- Argument 1: Faction id to view (string)
Example:
Action.SetReplayViewFaction("text")
RestartReplay (Action Function)
Restart replay
Example:
Action.RestartReplay()
ReplayPlayFromHere (Action Function)
While playing a replay, stop the replay and continue playing from here
Example:
Action.ReplayPlayFromHere()
Module: Debug
The debug module contains debug functions
Source: /Source/Desynced/Lua/Module/DSDebugModule.cpp
- Functions
Assert (Debug Function)
Assert a condition during automated tests and data validation
- Argument 1: Condition (anything)
- Argument 2: Message (multiple values are just concatenated) (anything)
- Return Value: Condition result (converted to logical boolean if input was not a boolean) (boolean)
Example:
local flag = Debug.Assert(...)local flag = Debug.Assert(..., ...)
EndTest (Debug Function)
Ending an automated test scenario
Example:
Debug.EndTest()
PrintCallStack (Debug Function)
Print the current call stack
Example:
Debug.PrintCallStack()
GetStats (Debug Function)
Get lua internal memory stats
- Return Value: Stats (table)
Example:
local tbl = Debug.GetStats()
GetMapStateHash (Debug Function)
Get a hash of the entire map state
- Return Value: Map hash number (integer)
- Return Value: All hash number (integer)
Example:
local num, num = Debug.GetMapStateHash()
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.
- Argument 1: State (boolean)
Example:
Debug.SetMemoryTracking(true)
Benchmark (Debug Function)
Time some code
- Return Value: Number of milliseconds (returned every second call) (number)
Example:
local num = Debug.Benchmark()
CrashProgram (Debug Function)
Crash the program (only works in mod development mode)
Example:
Debug.CrashProgram()
Reload (Debug Function)
Reload Lua code (only works in mod development mode and only while not playing multiplayer)
Example:
Debug.Reload()
AllowDebuggerInMultiplayer (Debug Function)
Enable the LUA debugger server even while playing multiplayer
Example:
Debug.AllowDebuggerInMultiplayer()
Module: Game
The game module contains global functions
Source: /Source/Desynced/Lua/Module/DSGameModule.cpp
- Functions
- NewGame
- RestartGame
- EndGame
- QuitGame
- OfflinePause
- GetModPackage
- GetModPackages
- GetScenarioModPackage
- GetInstalledMods
- GetInstalledModPackages
- GetInstalledModPackage
- SetModEnabled
- RefreshInstalledMods
- GetNativeModManagerName
- OpenNativeModManager
- GetCommandLineArguments
- SaveGame
- LoadGame
- ReplayGame
- DeleteGame
- RenameGame
- GetSaveGameList
- GetSaveGameModPackages
- IsSaveGameOldVersion
- HaveAnySaveGame
- GetAutoSaveTime
- SetAutoSaveTime
- GetMouseLock
- SetMouseLock
- GetDragScrolling
- SetDragScrolling
- GetEdgeScrolling
- SetEdgeScrolling
- GetScrollSpeed
- SetScrollSpeed
- GetGameDuration
- GetTimeSinceSave
- GetVersionString
- GetLocalPlayerFaction
- GetLocalPlayerExtra
- GetProfile
- SetColorMapping
- GetMappedColor
- CreateOnlineSession
- FindOnlineSessions
- JoinOnlineSession
- EndOnlineSession
- OnlineHaveLobbies
- CanInviteFriend
- ShowFriendInviteUI
- GetNetMode
- GetAllPlayers
- GetPlayerById
- GetLocalPlayer
- GetLocalPlayerId
- GetPlayerName
- IsHostPlayer
- IsLocalPlayer
- KickPlayer
- GetPlayerCount
- GetMaxPlayerCount
- GetMultiplayerSession
- GetHostSessionSettings
- ModifyHostSessionSettings
- GetEntitySelectedPlayerId
- GetFullscreenMode
- SetFullscreenMode
- GetScreenResolution
- SetScreenResolution
- GetScreenResolutions
- ApplyScreenModeRequired
- ApplyScreenModeNeedConfirm
- ConfirmScreenMode
- RevertScreenMode
- GetVideoSettings
- GetSupportedUpscalingModes
- SetVideoSettings
- GetVolume
- SetVolume
- GetUnfocusedVolume
- SetUnfocusedVolume
- GetNewsText
- OpenWebsite
- ExploreFolder
- SendFeedback
- UnlockAchievement
NewGame (Game Function)
Start a new game
- Argument 1: New game settings (scenario, seed, etc.) (table)
- Argument 2: If replay recording is to be disabled (OPTIONAL, default false) (boolean)
- Argument 3: Session settings when starting a multiplayer server (OPTIONAL, default nil) (table)
Example:
Game.NewGame({ ... })Game.NewGame({ ... }, true, { ... })
RestartGame (Game Function)
Restart the current scenario with the same game settings
Example:
Game.RestartGame()
EndGame (Game Function)
End the current game and return to the main menu
Example:
Game.EndGame()
QuitGame (Game Function)
Quit the game to desktop
Example:
Game.QuitGame()
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.
- Argument 1: Pause state (boolean)
Example:
Game.OfflinePause(true)
GetModPackage (Game Function)
Get a loaded mod package
- Argument 1: Mod package path ("Mod/Package") (string)
- Return Value: Module package (or nil on error) (modpackage)
Example:
local some_package = Game.GetModPackage("text")
GetModPackages (Game Function)
Get all currently active mod packages
- Return Value: Table of all active mod packages (table)
Example:
local tbl = Game.GetModPackages()
GetScenarioModPackage (Game Function)
Get the mod package of the currently running scenario
- Return Value: Module package (modpackage)
Example:
local some_package = Game.GetScenarioModPackage()
GetInstalledMods (Game Function)
Get meta data of all installed mods
- Return Value: Array of tables with mod meta data (table)
Example:
local tbl = Game.GetInstalledMods()
GetInstalledModPackages (Game Function)
Get meta data of all packages from an installed mod
- Argument 1: Mod id (string)
- Return Value: Array of tables with package meta data (table)
Example:
local tbl = Game.GetInstalledModPackages("text")
GetInstalledModPackage (Game Function)
Get meta data of one package and its mod
- Argument 1: Mod package path ("Mod/Package") (string)
- Return Value: Array of tables with package meta data (table)
- Return Value: Array of tables with mod meta data (or nil if package doesn't exist) (table)
Example:
local tbl, tbl = Game.GetInstalledModPackage("text")
SetModEnabled (Game Function)
Set a mods enabled state
Will be applied when the next map starts.
- Argument 1: Mod id (string)
- Argument 2: Mod enable state (boolean)
- Return Value: Name of missing dependency if mod could not be enabled (or nil if all dependencies of at least one package are available) (string)
Example:
local str = Game.SetModEnabled("text", true)
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:
Game.RefreshInstalledMods()
GetNativeModManagerName (Game Function)
Get the name of the mod management system of this platform
- Return Value: System name (or nil if none available) (string)
Example:
local str = Game.GetNativeModManagerName()
OpenNativeModManager (Game Function)
Open the native the mod management system of this platform (if available)
Example:
Game.OpenNativeModManager()
GetCommandLineArguments (Game Function)
Get command line arguments
- Return Value: Command line arguments (string)
Example:
local str = Game.GetCommandLineArguments()
SaveGame (Game Function)
Save save game
- Argument 1: Save title (string)
- Argument 2: Slot name (OPTIONAL, pass nil to save into a new slot) (string)
- Return Value: Written slot name (or nil if save operation failed) (string)
Example:
local str = Game.SaveGame("text")local str = Game.SaveGame("text", "text")
LoadGame (Game Function)
Load save game
- Argument 1: Slot name (string)
- Argument 2: Session settings when starting a multiplayer server (OPTIONAL, default nil) (table)
- Argument 3: Reset mods to the currently active ones (OPTIONAL, default false) (boolean)
Example:
Game.LoadGame("text")Game.LoadGame("text", { ... }, true)
ReplayGame (Game Function)
Play save game replay
- Argument 1: Slot name (string)
Example:
Game.ReplayGame("text")
DeleteGame (Game Function)
Delete save game
- Argument 1: Slot name (string)
- Return Value: Result (boolean)
Example:
local flag = Game.DeleteGame("text")
RenameGame (Game Function)
Rename save game
- Argument 1: Slot name (string)
- Argument 2: New save title (string)
- Return Value: Written slot name (or nil if rename operation failed) (string)
Example:
local str = Game.RenameGame("text", "text")
GetSaveGameList (Game Function)
Get the list of all save games
- Return Value: Save game list table (table)
Example:
local tbl = Game.GetSaveGameList()
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.
- Argument 1: Slot name (string)
- Return Value: Array of mod package info tables (table)
Example:
local tbl = Game.GetSaveGameModPackages("text")
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.
- Argument 1: Slot name (string)
- Return Value: True if save was made with an older version (boolean)
Example:
local flag = Game.IsSaveGameOldVersion("text")
HaveAnySaveGame (Game Function)
Get if any save game exists
- Return Value: True if any save game exists (boolean)
Example:
local flag = Game.HaveAnySaveGame()
GetAutoSaveTime (Game Function)
Get auto save time setting
- Return Value: Auto save minutes (or 0 if disabled) (integer)
Example:
local num = Game.GetAutoSaveTime()
SetAutoSaveTime (Game Function)
Set auto save time setting
- Argument 1: Auto save minutes (or 0 to disable) (integer)
Example:
Game.SetAutoSaveTime(1)
GetMouseLock (Game Function)
Get lock mouse option
- Return Value: Option (boolean)
Example:
local flag = Game.GetMouseLock()
SetMouseLock (Game Function)
Set lock mouse option
- Argument 1: Option (boolean)
Example:
Game.SetMouseLock(true)
GetDragScrolling (Game Function)
Get drag scrolling option
- Return Value: Option (boolean)
Example:
local flag = Game.GetDragScrolling()
SetDragScrolling (Game Function)
Set drag scrolling option
- Argument 1: Option (boolean)
Example:
Game.SetDragScrolling(true)
GetEdgeScrolling (Game Function)
Get edge scrolling option
- Return Value: Option (boolean)
Example:
local flag = Game.GetEdgeScrolling()
SetEdgeScrolling (Game Function)
Set edge scrolling option
- Argument 1: Option (boolean)
Example:
Game.SetEdgeScrolling(true)
GetScrollSpeed (Game Function)
Get scroll speed setting
- Return Value: Speed (number)
Example:
local num = Game.GetScrollSpeed()
SetScrollSpeed (Game Function)
Set scroll speed setting
- Argument 1: Speed (number)
Example:
Game.SetScrollSpeed(1)
GetGameDuration (Game Function)
Get the play time
- Return Value: Total number of seconds of play time (number)
Example:
local num = Game.GetGameDuration()
GetTimeSinceSave (Game Function)
Get the time that passed since the map was last saved
- Return Value: Seconds since the map was last saved (number)
Example:
local num = Game.GetTimeSinceSave()
GetVersionString (Game Function)
Get the game version
- Return Value: Game version (string)
Example:
local str = Game.GetVersionString()
GetLocalPlayerFaction (Game Function)
Get the local player faction
- Return Value: Local player faction (or nil if there is none) (faction)
Example:
local some_faction = Game.GetLocalPlayerFaction()
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
- Argument 1: Mod id (OPTIONAL) (string)
- Return Value: Local player extra data table (table)
Example:
local tbl = Game.GetLocalPlayerExtra()local tbl = Game.GetLocalPlayerExtra("text")
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
- Argument 1: Mod id (OPTIONAL) (string)
- Return Value: Profile table (table)
Example:
local tbl = Game.GetProfile()local tbl = Game.GetProfile("text")
SetColorMapping (Game Function)
Change the color mapping mode
- Argument 1: Mode (string)
Example:
Game.SetColorMapping("text")
GetMappedColor (Game Function)
Convert a color according to the color mapping
- Argument 1: Input color (color)
- Return Value: Mapped color (color)
Example:
local col = Game.GetMappedColor({ 1, 0, 0 })
CreateOnlineSession (Game Function)
Create an online session
- Argument 1: Session settings (table)
- Argument 2: LUA function callback when complete (with 1 argument boolean success) (function)
Example:
Game.CreateOnlineSession({ ... }, function() ... end)
FindOnlineSessions (Game Function)
Create an online session
- Argument 1: LUA function callback when complete (with 2 arguments boolean success and table session list) (function)
- Argument 2: True to search for servers on LAN, false to search lobbies on online service if available (OPTIONAL, default false) (boolean)
Example:
Game.FindOnlineSessions(function() ... end)Game.FindOnlineSessions(function() ... end, true)
JoinOnlineSession (Game Function)
Join an online session
- Argument 1: Session number (in result list of FindOnlineSessions) to join. You can pass 0 or nil to join the most recent invited session. (integer)
- Argument 2: Server password (OPTIONAL) (string)
- Argument 3: LUA function callback when complete (with 1 argument boolean success) (OPTIONAL) (function)
--- or --- - Argument 1: Server hostname (with optional :port suffix) to join with direct IP connection (string)
- Argument 2: Server password (OPTIONAL) (string)
- Argument 3: LUA function callback when complete (with 1 argument boolean success) (OPTIONAL) (function)
Example:
Game.JoinOnlineSession(1)Game.JoinOnlineSession(1, "text", function() ... end)Game.JoinOnlineSession("text")Game.JoinOnlineSession("text", "text", function() ... end)
EndOnlineSession (Game Function)
End online session (stop server or go back to title on client)
Example:
Game.EndOnlineSession()
OnlineHaveLobbies (Game Function)
Returns if online lobbies are available and sessions can be created with visibility PUBLIC/FRIENDS/INVITE
- Return Value: Availability (boolean)
Example:
local flag = Game.OnlineHaveLobbies()
CanInviteFriend (Game Function)
Returns if friend inviting is available
- Return Value: Availability (true if available on platform and currently in a multiplayer session) (boolean)
Example:
local flag = Game.CanInviteFriend()
ShowFriendInviteUI (Game Function)
Show the friend invite UI to invite them to the current session
Example:
Game.ShowFriendInviteUI()
GetNetMode (Game Function)
Get the current network mode
- Return Value: Mode string ('offline', 'server' or 'client') (string)
Example:
local str = Game.GetNetMode()
GetAllPlayers (Game Function)
Get a table of all connected multiplayer players
- Return Value: Player list (table)
Example:
local tbl = Game.GetAllPlayers()
GetPlayerById (Game Function)
Get a connected player by id
- Argument 1: Player id (integer)
- Return Value: Player details (table)
Example:
local tbl = Game.GetPlayerById(1)
GetLocalPlayer (Game Function)
Get player details of the local player
- Return Value: Player details (table)
Example:
local tbl = Game.GetLocalPlayer()
GetLocalPlayerId (Game Function)
Get player id of the local player
- Return Value: Player id (integer)
Example:
local num = Game.GetLocalPlayerId()
GetPlayerName (Game Function)
Get the name of a connected player
- Argument 1: Player id (OPTIONAL, defaults to local player) (integer)
- Return Value: Player name (string)
Example:
local str = Game.GetPlayerName()local str = Game.GetPlayerName(1)
IsHostPlayer (Game Function)
Check if a given player id belongs to the host player
- Argument 1: Player id (OPTIONAL, defaults to local player) (integer)
- Return Value: True if player is the host player (boolean)
Example:
local flag = Game.IsHostPlayer()local flag = Game.IsHostPlayer(1)
IsLocalPlayer (Game Function)
Check if a given player id belongs to the local player
- Argument 1: Player id (integer)
- Return Value: True if player is the local player (boolean)
Example:
local flag = Game.IsLocalPlayer(1)
KickPlayer (Game Function)
Kick a player from the server (only available to the host of a locally running session)
- Argument 1: Player id (integer)
- Argument 2: True to ban the player until the game on the server is restarted (OPTIONAL, default false) (boolean)
Example:
Game.KickPlayer(1)Game.KickPlayer(1, true)
GetPlayerCount (Game Function)
Get the number of connected players
Will be 1 in single player, and 0 on a dedicated server without anyone connected
- Return Value: Player count (integer)
Example:
local num = Game.GetPlayerCount()
GetMaxPlayerCount (Game Function)
Get the maximum number of multiplayer players (or 1 if offline)
- Return Value: Max player count (integer)
Example:
local num = Game.GetMaxPlayerCount()
GetMultiplayerSession (Game Function)
Get information about the current multiplayer session (returns nil if there is no session)
- Return Value: Name of the session (string)
- Return Value: True if the server is dedicated (boolean)
- Return Value: Visibility (PUBLIC, FRIENDS, INVITE, LOCKED, LAN) ("PUBLIC" | "FRIENDS" | "INVITE" | "LAN" | "LOCKED")
Example:
local str, flag, visibility = Game.GetMultiplayerSession()
GetHostSessionSettings (Game Function)
Get the session settings used to start hosting the session. Only the host can use this.
- Return Value: Session settings table (or nil if not hosting a session) (table)
Example:
local tbl = Game.GetHostSessionSettings()
ModifyHostSessionSettings (Game Function)
Modify host session settings. Only the host can use this.
Not all fields that can be passed to CreateOnlineSession are supported.
- Argument 1: Session settings (table)
Example:
Game.ModifyHostSessionSettings({ ... })
GetEntitySelectedPlayerId (Game Function)
Get which player has a given entity selected
- Argument 1: Entity to check (entity)
- Return Value: List of player ids (or nil if none) (table)
Example:
local tbl = Game.GetEntitySelectedPlayerId(other_entity)
GetFullscreenMode (Game Function)
Get the display fullscreen mode
- Return Value: Mode ('windowed', 'borderless', 'fullscreen') ("windowed", "borderless", "fullscreen")
Example:
local mode = Game.GetFullscreenMode()
SetFullscreenMode (Game Function)
Change the display fullscreen mode
- Argument 1: Mode ('windowed', 'borderless', 'fullscreen') ("windowed", "borderless", "fullscreen")
Example:
Game.SetFullscreenMode("windowed")
GetScreenResolution (Game Function)
Get active screen resolution
- Return Value: X resolution (integer)
- Return Value: Y resolution (integer)
Example:
local num, num = Game.GetScreenResolution()
SetScreenResolution (Game Function)
Set screen resolution
- Argument 1: X resolution (integer)
- Argument 2: Y resolution (integer)
Example:
Game.SetScreenResolution(1, 1)
GetScreenResolutions (Game Function)
Get a list screen resolutions appropriate for the current fullscreen mode
- Return Value: Resolution list (table)
Example:
local tbl = Game.GetScreenResolutions()
ApplyScreenModeRequired (Game Function)
Apply resolution and fullscreen mode settings
- Return Value: True if a followup call to ConfirmScreenMode or RevertScreenMode is needed (boolean)
Example:
local flag = Game.ApplyScreenModeRequired()
ApplyScreenModeNeedConfirm (Game Function)
Apply resolution and fullscreen mode settings
- Return Value: True if a followup call to ConfirmScreenMode or RevertScreenMode is needed (boolean)
Example:
local flag = Game.ApplyScreenModeNeedConfirm()
ConfirmScreenMode (Game Function)
Confirm changed resolution and fullscreen mode settings
Example:
Game.ConfirmScreenMode()
RevertScreenMode (Game Function)
Revert resolution and fullscreen mode to last confirmed settings
Example:
Game.RevertScreenMode()
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)
- Return Value: Settings table (table)
Example:
local tbl = Game.GetVideoSettings()
GetSupportedUpscalingModes (Game Function)
Get supported Upscaling modes and features
- Return Value: Table with modes and strings for all supported Upscaling modes and features (table)
Example:
local tbl = Game.GetSupportedUpscalingModes()
SetVideoSettings (Game Function)
Modify video settings
- Argument 1: Table with settings that are to be changed (see
GetVideoSettings) (table)
Example:
Game.SetVideoSettings({ ... })
GetVolume (Game Function)
Get the volume of a mix type
- Argument 1: Volume type ('master', 'effect', 'music', 'voice', 'ui') (string)
- Return Value: Volume percentage (100 means full volume) (number)
Example:
local num = Game.GetVolume("text")
SetVolume (Game Function)
Set the volume of a mix type
- Argument 1: Volume type ('master', 'effect', 'music', 'voice', 'ui') (string)
- Argument 2: Volume percentage (100 means full volume) (number)
Example:
Game.SetVolume("text", 1)
GetUnfocusedVolume (Game Function)
Get the volume of the game while unfocused
- Return Value: Volume percentage (100 means full volume) (number)
Example:
local num = Game.GetUnfocusedVolume()
SetUnfocusedVolume (Game Function)
Set the volume of the game while unfocused
- Argument 1: Volume percentage (100 means full volume) (number)
Example:
Game.SetUnfocusedVolume(1)
GetNewsText (Game Function)
Load the news text table from the online source
- Argument 1: LUA function callback when complete (with a table argument containing the news items) (function)
Example:
Game.GetNewsText(function() ... end)
OpenWebsite (Game Function)
Open Website to a special URL
- Argument 1: Site name (one of "STORE", "DISCORD", "NEWSLETTER", "WIKI", "FEEDBACK") (string)
- Argument 2: Numerical extra argument for FEEDBACK (OPTIONAL) (integer)
Example:
Game.OpenWebsite("text")Game.OpenWebsite("text", 1)
ExploreFolder (Game Function)
Open OS file browser to a special folder
- Argument 1: Special folder name (one of "SAVEGAMES", "LOGS", "MODS") (string)
Example:
Game.ExploreFolder("text")
SendFeedback (Game Function)
Send feedback to the developers
- Argument 1: Feedback rating (integer)
- Argument 2: Feedback category (string)
- Argument 3: Feedback text (string)
- Argument 4: Attach save state (boolean)
- Argument 5: Attach captured feedback screenshot (boolean)
- Argument 6: LUA function callback when complete (with one boolean argument containing success state) (function)
Example:
Game.SendFeedback(1, "text", "text", true, true, function() ... end)
UnlockAchievement (Game Function)
Unlock an achievement (only available on unmodded/unmodified game)
- Argument 1: Achievement ID (string)
Example:
Game.UnlockAchievement("text")
Module: Input
The Input module contains Input functions
Source: /Source/Desynced/Lua/Module/DSInputModule.cpp
- Functions
IsShiftDown (Input Function)
Check if the shift key is pressed (either left or right shift key)
- Return Value: Key state (boolean)
Example:
local flag = Input.IsShiftDown()
IsControlDown (Input Function)
Check if the control key is pressed (either left or right control key)
- Return Value: Key state (boolean)
Example:
local flag = Input.IsControlDown()
IsAltDown (Input Function)
Check if the alt key is pressed (either left or right alt key)
- Return Value: Key state (boolean)
Example:
local flag = Input.IsAltDown()
IsKeyDown (Input Function)
Check if a specific key is pressed
This does not work while a modal UI view is open
- Argument 1: Key name (string)
- Return Value: Key pressed state (boolean)
Example:
local flag = Input.IsKeyDown("text")
BindAction (Input Function)
Bind a callback function to a named input action
- Argument 1: Action name (string)
- Argument 2: Key event (one of 'Pressed', 'Released', 'Repeat', 'DoubleClick', 'Axis') (string)
- Argument 3: Lua Function (function)
--- or --- - Argument 1: Action name (string)
- Argument 2: Key event (one of 'Pressed', 'Released', 'Repeat', 'DoubleClick', 'Axis') (string)
- Argument 3: Built in game function name (string)
- Return Value: Binding handle (for use with RemoveActionBinding) (integer)
Example:
local num = Input.BindAction("text", "text", function() ... end)local num = Input.BindAction("text", "text", "text")
BindAxis (Input Function)
Bind a callback function to a named input axis
- Argument 1: Axis name (string)
- Argument 2: Lua Function (function)
--- or --- - Argument 1: Axis name (string)
- Argument 2: Built in game function name (string)
Example:
Input.BindAxis("text", function() ... end)Input.BindAxis("text", "text")
RemoveActionBinding (Input Function)
Remove bound callback functions from a named input action
- Argument 1: Action name (string)
- Argument 2: Action handle (OPTIONAL, return value of BindAction, clear all if not passed) (integer)
Example:
Input.RemoveActionBinding("text")Input.RemoveActionBinding("text", 1)
RemoveAxisBinding (Input Function)
Remove all bound callback functions from a named input axis
- Argument 1: Axis name (string)
Example:
Input.RemoveAxisBinding("text")
AddActionMapping (Input Function)
Map a physical input key to a named input action
- Argument 1: Action name (string)
- Argument 2: Key name (string)
- Argument 3: Options (OPTIONAL, default none) (table)
Example:
Input.AddActionMapping("text", "text")Input.AddActionMapping("text", "text", { ... })
AddAxisMapping (Input Function)
Map a physical input key to a named input axis
- Argument 1: Axis name (string)
- Argument 2: Key name (string)
- Argument 3: Scale (OPTIONAL, default 1.0) (number)
Example:
Input.AddAxisMapping("text", "text")Input.AddAxisMapping("text", "text", 1)
RemoveActionMapping (Input Function)
Remove previously mapped physical inputs from a named input action
- Argument 1: Action name (string)
- Argument 2: Key name (OPTIONAL, remove all if not given) (string)
Example:
Input.RemoveActionMapping("text")Input.RemoveActionMapping("text", "text")
IsBoundToAction (Input Function)
Check if a key is bound to an action
- Argument 1: Key name (string)
- Argument 2: Action name (string)
- Return Value: Is bound (boolean)
Example:
local flag = Input.IsBoundToAction("text", "text")
IsBoundToAxis (Input Function)
Check if a key is bound to an axis
- Argument 1: Key name (string)
- Argument 2: Axis name (string)
- Return Value: Is bound (boolean)
Example:
local flag = Input.IsBoundToAxis("text", "text")
RemoveAxisMapping (Input Function)
Remove previously mapped physical inputs from a named input axis
- Argument 1: Axis name (string)
- Argument 2: Key name (OPTIONAL, remove all if not given) (string)
Example:
Input.RemoveAxisMapping("text")Input.RemoveAxisMapping("text", "text")
GetBindingNames (Input Function)
Get a table with all key names of a category
- Argument 1: Category (one of "KEYBOARD", "MOUSE" or "GAMEPAD") (string)
- Return Value: Table with key ids and localized key names (table)
Example:
local tbl = Input.GetBindingNames("text")
GetUnknownKeyBindingName (Input Function)
Get the name of an unknown key binding name not returned with GetBindingNames
- Argument 1: Key ID (string)
- Return Value: Localized key name or nil if unknown (string)
Example:
local str = Input.GetUnknownKeyBindingName("text")
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)
- Argument 1: Lua function called with arguments (key_name, is_down, axis, mouse_delta) (function)
- Argument 2: Pass true to not apply dead zone scaling to analog gampead inputs (OPTIONAL, default false) (boolean)
- Argument 3: Pass true to not filter out periodical repeat button press events (OPTIONAL, default false) (boolean)
Example:
Input.SetInputProcessor(function() ... end)Input.SetInputProcessor(function() ... end, true, true)
ClearInputProcessor (Input Function)
Clear the active custom input processor
Example:
Input.ClearInputProcessor()
Module: Map
The map module contains global functions affecting the game state
Source: /Source/Desynced/Lua/Module/DSMapModule.cpp
- Functions
- SetGameSpeed
- GetGameSpeed
- IsSimulation
- IsFrontEnd
- GetSettings
- ModifySettings
- GetSeed
- GetSave
- Run
- GetTick
- GetExecutedActionCount
- CreateEntity
- RecreateEntity
- DropItemAt
- GetFaction
- CreateFaction
- GetFactions
- GetFactionCount
- GetPlayerFactions
- GetPlayerFactionCount
- SetPlayerFaction
- GetTotalDays
- GetYear
- GetYearSeason
- GetSunlightIntensity
- GetSunlightAmount
- GetSunlightDirection
- GetSunriseAndSunset
- GetUndiscoveredLocation
- GetLocationInRange
- GetClosestLocation
- SpawnChunks
- GetBlightness
- GetBlightnessDelta
- GetElevation
- GetRichness
- GetVariation
- GetHeight
- GetPlateauDelta
- GetPlateauHeight
- GetWaterHeight
- GetTileData
- Defer
- Delay
- StartTerraforming
- StopTerraforming
- GetEntityAt
- GetFoundationEntityAt
- GetEntitiesAt
- GetEntitiesInRange
- GetEntitiesOnLine
- FindClosestEntity
- GetEntityFromKey
- CountTiles
- GetComponents
- ThrowItemEffect
SetGameSpeed (Map Function)
Modify simulation speed
- Argument 1: Game speed (integer)
Example:
Map.SetGameSpeed(1)
GetGameSpeed (Map Function)
Get simulation speed
- Return Value: Game speed (integer)
Example:
local num = Map.GetGameSpeed()
IsSimulation (Map Function)
Check if LUA is currently running in simulation context
- Return Value: True if in simulation context, false if in UI context (boolean)
Example:
local flag = Map.IsSimulation()
IsFrontEnd (Map Function)
Check if the active map is the front-end menu
- Return Value: True if front-end (boolean)
Example:
local flag = Map.IsFrontEnd()
GetSettings (Map Function)
Get current map settings (read only)
- Return Value: Current map settings (table)
Example:
local tbl = Map.GetSettings()
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.
- Argument 1: Settings key (string)
- Argument 2: New value (anything)
--- or --- - Argument 1: Flat array with keys and values (key1, val1, key2, val2, ...) (table)
Example:
Map.ModifySettings("text", ...)Map.ModifySettings({ ... })
GetSeed (Map Function)
Get map seed (same as GetSettings().seed)
- Return Value: Current map seed (integer)
Example:
local num = Map.GetSeed()
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
- Argument 1: Mod id (OPTIONAL) (string)
- Return Value: Save table (table)
Example:
local tbl = Map.GetSave()local tbl = Map.GetSave("text")
Run (Map Function)
Call bound MapMsg functions
- Argument 1: Message name registered in MapMsg (string)
- Argument 2: Passed values (OPTIONAL, can pass multiple values) (anything)
Example:
Map.Run("text")Map.Run("text", ...)
GetTick (Map Function)
Get the current simulation tick number
- Return Value: Tick number (integer)
Example:
local num = Map.GetTick()
GetExecutedActionCount (Map Function)
Get the number of player actions that have been executed
- Return Value: Action count (integer)
Example:
local num = Map.GetExecutedActionCount()
CreateEntity (Map Function)
Create a new entity from a frame definition
- Argument 1: Faction or faction id (faction)
- Argument 2: Frame id (string)
- Argument 3: Specific visual id or another frame id from which to use the visual (OPTIONAL, defaults to frame visual) (string)
- Argument 4: Pass true for entities spawned as part of map generation (OPTIONAL) (boolean)
- Return Value: Created entity object (or nil on error) (entity)
Example:
local some_entity = Map.CreateEntity("faction_id", "text")local some_entity = Map.CreateEntity("faction_id", "text", "text", true)
RecreateEntity (Map Function)
Recreate an entity with a new frame definition but keep any references to it
- Argument 1: Existing entity to be recreated (entity)
- Argument 2: Frame id (string)
- Argument 3: Specific visual id or another frame id from which to use the visual (OPTIONAL, defaults to frame visual) (string)
- Argument 4: Pass false to dispose extra data instead of passing it on (OPTIONAL, default true) (boolean)
- Argument 5: Pass false to destroy inventory content instead of passing or dropping it (OPTIONAL, default true) (boolean)
- Argument 6: Pass false to not replace the entity back onto the map (OPTIONAL, default true) (boolean)
- Return Value: The same entity object (or nil on error) (entity)
Example:
local some_entity = Map.RecreateEntity(other_entity, "text")local some_entity = Map.RecreateEntity(other_entity, "text", "text", true, true, true)
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).
- Argument 1: Location (area, coordinate or entity)
- Argument 2: Item id (string)
- Argument 3: Amount (OPTIONAL, default 1) (integer)
- Argument 4: Extra data table (OPTIONAL, default nil) (table)
- Argument 5: Frame id (OPTIONAL, otherwise use default dropped item frame) (string)
- Argument 6: Visual id (OPTIONAL, otherwise use default) (string)
Example:
Map.DropItemAt(entity OR [ x, y ] OR [ x, y, w, h ], "text")Map.DropItemAt(entity OR [ x, y ] OR [ x, y, w, h ], "text", 1, { ... }, "text", "text")
GetFaction (Map Function)
Get a faction
- Argument 1: Faction id (string)
- Return Value: Faction object (or nil on error) (faction)
Example:
local some_faction = Map.GetFaction("text")
CreateFaction (Map Function)
Create a new faction (or get it if it already exists)
- Argument 1: Faction id (string)
- Argument 2: Set if this faction is to be controlled by a player (only applicable if the faction does not exist yet) (OPTIONAL, default false) (boolean)
- Return Value: Faction object (faction)
- Return Value: True if this faction was newly created, false if it already existed (boolean)
Example:
local some_faction, flag = Map.CreateFaction("text")local some_faction, flag = Map.CreateFaction("text", true)
GetFactions (Map Function)
Get all factions
- Return Value: List of faction objects (table)
Example:
local tbl = Map.GetFactions()
GetFactionCount (Map Function)
Get the number of spawned factions
- Return Value: Number of factions (integer)
Example:
local num = Map.GetFactionCount()
GetPlayerFactions (Map Function)
Get all player controlled factions
- Return Value: List of faction objects (table)
Example:
local tbl = Map.GetPlayerFactions()
GetPlayerFactionCount (Map Function)
Get the number of spawned player factions
- Return Value: Number of player controlled factions (integer)
Example:
local num = Map.GetPlayerFactionCount()
SetPlayerFaction (Map Function)
Switches a players faction
- Argument 1: Player id (integer)
- Argument 2: Faction id (string)
Example:
Map.SetPlayerFaction(1, "text")
GetTotalDays (Map Function)
Get the number of days progressed
- Return Value: Number of days (floating point value, fractional part indicates time of day) (integer)
Example:
local num = Map.GetTotalDays()
GetYear (Map Function)
Get the current year
- Return Value: Current year (integer)
Example:
local num = Map.GetYear()
GetYearSeason (Map Function)
Get the current season value between 0-1, 0.5 being summer, 0/1 being winter
- Return Value: Season value (number)
Example:
local num = Map.GetYearSeason()
GetSunlightIntensity (Map Function)
Get the current sunlight intensity
- Return Value: Sunlight intensity (number)
Example:
local num = Map.GetSunlightIntensity()
GetSunlightAmount (Map Function)
Get the current amount of sunlight (square root of sunlight intensity)
- Return Value: Amount of sunlight (between 0.0 and 1.0 inclusive) (number)
Example:
local num = Map.GetSunlightAmount()
GetSunlightDirection (Map Function)
Get the direction of the sunlight as a normalized vector
- Return Value: Sunlight X direction (number)
- Return Value: Sunlight Y direction (number)
Example:
local num, num = Map.GetSunlightDirection()
GetSunriseAndSunset (Map Function)
Get the day time of sunrise and sunset
- Argument 1: Return time when the sun crosses a given amount of sunlight intensity (OPTIONAL, default 0.0) (number)
- Return Value: Sunrise time (between 0.0 and 1.0) (number)
- Return Value: Sunset time (between 0.0 and 1.0) (number)
Example:
local num, num = Map.GetSunriseAndSunset()local num, num = Map.GetSunriseAndSunset(1)
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
- Argument 1: Request the Nth undiscovered chunk (OPTIONAL, default first) (integer)
- Return Value: X position (integer)
- Return Value: Y position (integer)
Example:
local num, num = Map.GetUndiscoveredLocation()local num, num = Map.GetUndiscoveredLocation(1)
GetLocationInRange (Map Function)
Get the location of a tile at a given distance from a starting point
This function matches the behavior of GetEntitiesOnLine.
- Argument 1: Area to start the line from (area, coordinate or entity)
- Argument 2: Area as directional indicator from the starting point (area, coordinate or entity)
- Argument 3: Distance to query the coordinate for (integer)
- Return Value: X position (integer)
- Return Value: Y position (integer)
Example:
local num, num = Map.GetLocationInRange(entity OR [ x, y ] OR [ x, y, w, h ], entity OR [ x, y ] OR [ x, y, w, h ], 1)
GetClosestLocation (Map Function)
Get the closest tile location of an area towards another area
Useful when starting area potentially is larger than 1x1.
- Argument 1: Area to test from (result will be a tile in this area) (area, coordinate or entity)
- Argument 2: Area to test against (area, coordinate or entity)
- Return Value: X coordinate (integer)
- Return Value: Y coordinate (integer)
Example:
local num, num = Map.GetClosestLocation(entity OR [ x, y ] OR [ x, y, w, h ], entity OR [ x, y ] OR [ x, y, w, h ])
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.
- Argument 1: Location or area to spawn chunks for (area, coordinate or entity)
- Argument 2: Entity which is causing any new chunks to be spawned (OPTIONAL) (entity)
- Return Value: Returns how many new chunks were created (or will be if spawning is deferred) (integer)
Example:
local num = Map.SpawnChunks(entity OR [ x, y ] OR [ x, y, w, h ])local num = Map.SpawnChunks(entity OR [ x, y ] OR [ x, y, w, h ], other_entity)
GetBlightness (Map Function)
Get blightness for a tile or area
- Argument 1: Location to check (area, coordinate or entity)
- Argument 2: If checking more than a single tile, return the smallest value instead of the biggest (OPTIONAL, default false) (boolean)
- Argument 3: If the first argument is an entity that isn't placed on the map and not docked, return this value instead of an error (OPTIONAL) (number)
- Return Value: blightness (number)
Example:
local num = Map.GetBlightness(entity OR [ x, y ] OR [ x, y, w, h ])local num = Map.GetBlightness(entity OR [ x, y ] OR [ x, y, w, h ], true, 1)
GetBlightnessDelta (Map Function)
Get blightness delta against the blight threshold for a tile or area (same as Map.GetBlightness(..) - Map.GetSettings().blight_threshold)
- Argument 1: Location to check (area, coordinate or entity)
- Argument 2: If checking more than a single tile, return the smallest value instead of the biggest (OPTIONAL, default false) (boolean)
- Argument 3: If the first argument is an entity that isn't placed on the map and not docked, return this value instead of an error (OPTIONAL) (number)
- Return Value: blightness delta (number)
Example:
local num = Map.GetBlightnessDelta(entity OR [ x, y ] OR [ x, y, w, h ])local num = Map.GetBlightnessDelta(entity OR [ x, y ] OR [ x, y, w, h ], true, 1)
GetElevation (Map Function)
Get elevation for a tile or area
- Argument 1: Location to check (area, coordinate or entity)
- Argument 2: If checking more than a single tile, return the smallest value instead of the biggest (OPTIONAL, default false) (boolean)
- Argument 3: If the first argument is an entity that isn't placed on the map and not docked, return this value instead of an error (OPTIONAL) (number)
- Return Value: elevation (number)
Example:
local num = Map.GetElevation(entity OR [ x, y ] OR [ x, y, w, h ])local num = Map.GetElevation(entity OR [ x, y ] OR [ x, y, w, h ], true, 1)
GetRichness (Map Function)
Get richness for a tile or area
- Argument 1: Location to check (area, coordinate or entity)
- Argument 2: If checking more than a single tile, return the smallest value instead of the biggest (OPTIONAL, default false) (boolean)
- Argument 3: If the first argument is an entity that isn't placed on the map and not docked, return this value instead of an error (OPTIONAL) (number)
- Return Value: richness (number)
Example:
local num = Map.GetRichness(entity OR [ x, y ] OR [ x, y, w, h ])local num = Map.GetRichness(entity OR [ x, y ] OR [ x, y, w, h ], true, 1)
GetVariation (Map Function)
Get variation for a tile or area
- Argument 1: Location to check (area, coordinate or entity)
- Argument 2: If checking more than a single tile, return the smallest value instead of the biggest (OPTIONAL, default false) (boolean)
- Argument 3: If the first argument is an entity that isn't placed on the map and not docked, return this value instead of an error (OPTIONAL) (number)
- Return Value: variation (number)
Example:
local num = Map.GetVariation(entity OR [ x, y ] OR [ x, y, w, h ])local num = Map.GetVariation(entity OR [ x, y ] OR [ x, y, w, h ], true, 1)
GetHeight (Map Function)
Get height for a tile or area
- Argument 1: Location to check (area, coordinate or entity)
- Argument 2: If checking more than a single tile, return the smallest value instead of the biggest (OPTIONAL, default false) (boolean)
- Argument 3: If the first argument is an entity that isn't placed on the map and not docked, return this value instead of an error (OPTIONAL) (number)
- Return Value: height (number)
Example:
local num = Map.GetHeight(entity OR [ x, y ] OR [ x, y, w, h ])local num = Map.GetHeight(entity OR [ x, y ] OR [ x, y, w, h ], true, 1)
GetPlateauDelta (Map Function)
Get the height against the plateau height for a tile or area (same as Map.GetHeight(..) - Map.GetPlateauHeight())
- Argument 1: Location to check (area, coordinate or entity)
- Argument 2: If checking more than a single tile, return the smallest value instead of the biggest (OPTIONAL, default false) (boolean)
- Argument 3: If the first argument is an entity that isn't placed on the map and not docked, return this value instead of an error (OPTIONAL) (number)
- Return Value: height delta (number)
Example:
local num = Map.GetPlateauDelta(entity OR [ x, y ] OR [ x, y, w, h ])local num = Map.GetPlateauDelta(entity OR [ x, y ] OR [ x, y, w, h ], true, 1)
GetPlateauHeight (Map Function)
Get plateau height
- Return Value: plateau height (number)
Example:
local num = Map.GetPlateauHeight()
GetWaterHeight (Map Function)
Get water height
- Return Value: water height (number)
Example:
local num = Map.GetWaterHeight()
GetTileData (Map Function)
Get table with full tile data for a given location
- Argument 1: X coordinate (integer)
- Argument 2: Y coordinate (integer)
- Return Value: blightness, elevation, richness, variation (table)
Example:
local tbl = Map.GetTileData(1, 1)
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.
- Argument 1: LUA function to execute after components have been processed (function)
Example:
Map.Defer(function() ... end)
Delay (Map Function)
Delay function for a given number of ticks
A delay function can be registered with
function Delay.FUNCTIONNAME(arg)
- Argument 1: Function name (string)
- Argument 2: Number of ticks to wait until called (0 is like using Defer function) (integer)
- Argument 3: Argument table to pass (OPTIONAL) (table)
Example:
Map.Delay("text", 1)Map.Delay("text", 1, { ... })
StartTerraforming (Map Function)
Start terraforming
- Argument 1: Entity (entity)
- Argument 2: Range (integer)
- Argument 3: Rate (change per tick) (number)
- Return Value: Terraforming instance index (integer)
Example:
local num = Map.StartTerraforming(other_entity, 1, 1)
StopTerraforming (Map Function)
End terraforming
- Argument 1: Terraforming instance index (integer)
Example:
Map.StopTerraforming(1)
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
- Argument 1: X coordinate (integer)
- Argument 2: Y coordinate (integer)
- Argument 3: Filter by frame type (FF_FOUNDATION, FF_WALL, FF_GATE, FF_DROPPEDITEM, FF_CONSTRUCTION, FF_RESOURCE, FF_OPERATING) or faction (FF_OWNFACTION, FF_ENEMYFACTION, FF_NEUTRALFACTION, FF_ALLYFACTION, FF_WORLDFACTION) (OPTIONAL, default FF_ALL) (integer)
- Argument 4: The faction that is considered self with regards to faction filters passed to the previous argument (must be passed for faction filters) (faction)
- Return Value: Entity (or nil if none) (entity)
Example:
local some_entity = Map.GetEntityAt(1, 1)local some_entity = Map.GetEntityAt(1, 1, 1, world_faction)
GetFoundationEntityAt (Map Function)
Get a foundation entity at a specific location (faster than the function above)
- Argument 1: X coordinate (integer)
- Argument 2: Y coordinate (integer)
- Return Value: Entity (or nil if none) (entity)
Example:
local some_entity = Map.GetFoundationEntityAt(1, 1)
GetEntitiesAt (Map Function)
Get all entities at a specific location
- Argument 1: X coordinate (integer)
- Argument 2: Y coordinate (integer)
- Argument 3: Filter by frame type (FF_FOUNDATION, FF_WALL, FF_GATE, FF_DROPPEDITEM, FF_CONSTRUCTION, FF_RESOURCE, FF_OPERATING) or faction (FF_OWNFACTION, FF_ENEMYFACTION, FF_NEUTRALFACTION, FF_ALLYFACTION, FF_WORLDFACTION) (OPTIONAL, default FF_ALL) (integer)
- Argument 4: The faction that is considered self with regards to faction filters passed to the previous argument (must be passed for faction filters) (faction)
- Return Value: Array of entities (table)
Example:
local tbl = Map.GetEntitiesAt(1, 1)local tbl = Map.GetEntitiesAt(1, 1, 1, world_faction)
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.
- Argument 1: Area to start the search from (area, coordinate or entity)
- Argument 2: Search radius in tiles (integer)
- Argument 3: Filter by frame type (FF_FOUNDATION, FF_WALL, FF_GATE, FF_DROPPEDITEM, FF_CONSTRUCTION, FF_RESOURCE, FF_OPERATING) or faction (FF_OWNFACTION, FF_ENEMYFACTION, FF_NEUTRALFACTION, FF_ALLYFACTION, FF_WORLDFACTION) (OPTIONAL, default FF_ALL) (integer)
- Argument 4: The faction that is considered self with regards to faction filters passed to the previous argument (must be passed if no entity is specified as the area) (faction)
- Return Value: Array of entities (table)
Example:
local tbl = Map.GetEntitiesInRange(entity OR [ x, y ] OR [ x, y, w, h ], 1)local tbl = Map.GetEntitiesInRange(entity OR [ x, y ] OR [ x, y, w, h ], 1, 1, world_faction)
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.
- Argument 1: Area to start the line from (area, coordinate or entity)
- Argument 2: Area to end the line at (or directional indicator if passing the next argument) (area, coordinate or entity)
- Argument 3: Search distance towards or beyond end coordinate instead of ending the line there (OPTIONAL, default -1) (integer)
- Argument 4: Filter by frame type (FF_FOUNDATION, FF_WALL, FF_GATE, FF_DROPPEDITEM, FF_CONSTRUCTION, FF_RESOURCE, FF_OPERATING) or faction (FF_OWNFACTION, FF_ENEMYFACTION, FF_NEUTRALFACTION, FF_ALLYFACTION, FF_WORLDFACTION) (OPTIONAL, default FF_ALL) (integer)
- Argument 5: The faction that is considered self with regards to faction filters passed to the previous argument (must be passed if no entity is specified as the area) (faction)
- Return Value: Array of entities (table)
- Return Value: X position of last tile checked (integer)
- Return Value: Y position of last tile checked (integer)
Example:
local tbl, num, num = Map.GetEntitiesOnLine(entity OR [ x, y ] OR [ x, y, w, h ], entity OR [ x, y ] OR [ x, y, w, h ])local tbl, num, num = Map.GetEntitiesOnLine(entity OR [ x, y ] OR [ x, y, w, h ], entity OR [ x, y ] OR [ x, y, w, h ], 1, 1, world_faction)
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.
- Argument 1: Area to start the search from (area, coordinate or entity)
- Argument 2: Search radius in tiles (integer)
- Argument 3: Callback called for each entity in range in order of distance, return true from this to stop the search (function)
- Argument 4: Filter by frame type (FF_FOUNDATION, FF_WALL, FF_GATE, FF_DROPPEDITEM, FF_CONSTRUCTION, FF_RESOURCE, FF_OPERATING) or faction (FF_OWNFACTION, FF_ENEMYFACTION, FF_NEUTRALFACTION, FF_ALLYFACTION, FF_WORLDFACTION) (OPTIONAL, default FF_ALL) (integer)
- Argument 5: The faction that is considered self with regards to faction filters passed to the previous argument (must be passed if no entity is specified as the area) (faction)
- Return Value: The entity for which the callback returned true (or nil if none) (entity)
Example:
local some_entity = Map.FindClosestEntity(entity OR [ x, y ] OR [ x, y, w, h ], 1, function() ... end)local some_entity = Map.FindClosestEntity(entity OR [ x, y ] OR [ x, y, w, h ], 1, function() ... end, 1, world_faction)
GetEntityFromKey (Map Function)
Get an entity from a key (obtained from entity.key)
- Argument 1: Numerical entity key (integer)
- Return Value: The entity object matching the key (entity)
Example:
local some_entity = Map.GetEntityFromKey(1)
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
- Argument 1: Area to start the search from (area, coordinate or entity)
- Argument 2: Search radius in tiles (integer)
- Argument 3: Also count the tiles covering the area, otherwise only count in the radius outside (OPTIONAL, default false) (boolean)
- Return Value: Number of blocked tiles due to landscape (integer)
- Return Value: Number of blocked tiles due to entity without movement or from another faction (integer)
- Return Value: Number of passable tiles with a construction site of the same faction (integer)
- Return Value: Number of passable tiles without a construction site of the same faction (integer)
- Return Value: Number of non-floating entities with movement of the same faction (integer)
Example:
local num, num, num, num, num = Map.CountTiles(entity OR [ x, y ] OR [ x, y, w, h ], 1)local num, num, num, num, num = Map.CountTiles(entity OR [ x, y ] OR [ x, y, w, h ], 1, true)
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.
- Argument 1: Component id (string)
- Argument 2: Set to true to query the base_id value of component definitions if it exists (OPTIONAL, default false) (boolean)
- Return Value: Array of components (table)
Example:
local tbl = Map.GetComponents("text")local tbl = Map.GetComponents("text", true)
ThrowItemEffect (Map Function)
Show a item throw effect
- Argument 1: Source entity (entity)
- Argument 2: Target entity (entity)
- Argument 3: Item id (string)
- Argument 4: Render instance number (OPTIONAL) (integer)
Example:
Map.ThrowItemEffect(other_entity, other_entity, "text")Map.ThrowItemEffect(other_entity, other_entity, "text", 1)
Module: Tool
The tool module contains utility functions
Source: /Source/Desynced/Lua/Module/DSToolModule.cpp
- Functions
Hash (Tool Function)
Create a checksum of a value
- Argument 1: Value(s) (any type, can pass multiple values) (anything)
- Return Value: Checksum (integer)
Example:
local num = Tool.Hash(...)
Copy (Tool Function)
Create a deep copy of a value, most often used with tables
- Argument 1: Value(s) (any type, can pass multiple values) (anything)
- Return Value: Copied value(s) (anything)
Example:
local val = Tool.Copy(...)
TruncateString (Tool Function)
Truncate a string potentially containing Unicode characters
- Argument 1: String to be truncated (string)
- Argument 2: Maximum number of Unicode characters to return (integer)
- Argument 3: How many Unicode characters should be skipped (OPTIONAL) (integer)
- Return Value: Resulting truncated string (string)
- Return Value: True if the string was truncated or false if everything after the offset fit (boolean)
Example:
local str, flag = Tool.TruncateString("text", 1)local str, flag = Tool.TruncateString("text", 1, 1)
CompareStringNoCase (Tool Function)
Compare two strings potentially containing Unicode characters case insensitive
- Argument 1: First string to be compared (string)
- Argument 2: Second string to be compared (string)
- Return Value: True if the two strings are equal ignoring case (boolean)
Example:
local flag = Tool.CompareStringNoCase("text", "text")
ContainsStringNoCase (Tool Function)
Check if a string exists inside another string case insensitive, where the strings potentially contain Unicode characters
- Argument 1: String in which to find another string (string)
- Argument 2: The part to find in the string of the first argument (string)
- Return Value: True if the string is contained ignoring case (boolean)
Example:
local flag = Tool.ContainsStringNoCase("text", "text")
TableToString (Tool Function)
Convert a lua table to a string
- Argument 1: Table (table)
- Return Value: Encoded string (string)
Example:
local str = Tool.TableToString({ ... })
StringToTable (Tool Function)
Convert a string back to a lua table
- Argument 1: Encoded string (string)
- Return Value: Table (table)
Example:
local tbl = Tool.StringToTable("text")
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.
- Argument 1: Table to set the clipboard to (table)
- Argument 2: A one character identifier to be included in the prefix of the encoded string (string)
--- or --- - Argument 1: String to set the clipboard to (only the main mod is allowed to pass raw strings) (string)
- Argument 2: A one character identifier to be included in the prefix of the encoded string (string)
Example:
Tool.SetClipboard({ ... }, "text")Tool.SetClipboard("text", "text")
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.
- Argument 1: A one character identifier to check in the prefix of the encoded string (OPTIONAL, return any if omitted) (string)
- Return Value: Clipboard table content (table)
- Return Value: Decoded prefix character (string)
Example:
local tbl, str = Tool.GetClipboard()local tbl, str = Tool.GetClipboard("text")
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.
- Argument 1: The destination lua table to encode the difference to (table)
- Argument 2: The encoded old table as was returned on a previous call to this function or ApplyTableDelta (OPTIONAL) (string)
- Return Value: Encoded destination table (to use on another call to this function or ApplyTableDelta) (string)
- Return Value: Encoded difference to get from the destination table back to the source table (only returned when old_table_str is passed) (string)
Example:
local str, str = Tool.GetTableDelta({ ... })local str, str = Tool.GetTableDelta({ ... }, "text")
ApplyTableDelta (Tool Function)
Apply an encoded difference string to revert a table back to the source table after using GetTableDelta
- Argument 1: The encoded destination table as was returned by a call to GetTableDelta or this function (string)
- Argument 2: The encoded difference as was returned by a call to GetTableDelta or this function (string)
- Argument 3: Return an encoded table and difference to go forward again to the destination (boolean)
- Return Value: The source table (table)
- Return Value: Encoded returned source table (only returned when get_reverse is passed) (string)
- Return Value: Encoded difference to get from the returned source table back again to the passed destination table (only returned when get_reverse is passed) (string)
Example:
local tbl, str, str = Tool.ApplyTableDelta("text", "text")local tbl, str, str = Tool.ApplyTableDelta("text", "text", true)
GetDateStr (Tool Function)
Format a date and time value as a string
Will use current time if no timestamp gets passed.
- Argument 1: Date format (OPTIONAL, defaults to "%Y.%m.%d-%H.%M.%S") (string)
--- or --- - Argument 1: Unix timestamp (integer)
- Argument 2: Date format (OPTIONAL, defaults to "%Y.%m.%d-%H.%M.%S") (string)
- Return Value: Formatted date/time string (string)
Example:
local str = Tool.GetDateStr()local str = Tool.GetDateStr("text")local str = Tool.GetDateStr(1)local str = Tool.GetDateStr(1, "text")
GetTimeDurationStr (Tool Function)
Format a time duration to a string (HH:MM:SS)
- Argument 1: Seconds (number)
- Return Value: Formatted time duration string (string)
Example:
local str = Tool.GetTimeDurationStr(1)
NewRegisterObject (Tool Function)
Create an empty or copied register object
- Argument 1: Copy contents from another register or a table (OPTIONAL) (register)
- Return Value: New register object (register)
Example:
local reg = Tool.NewRegisterObject({ num = 10, id = "id" })
ParseEntityStates (Tool Function)
Parse binary entity state bit-flags into a readable table
- Argument 1: States bitflag number (integer)
- Return Value: State names (table)
Example:
local tbl = Tool.ParseEntityStates(1)
EncodeEntityStates (Tool Function)
Encode readable table into binary entity state bit-flags
- Argument 1: State names (table)
- Return Value: States bitflag number (integer)
Example:
local num = Tool.EncodeEntityStates({ ... })
EncodeTrustLevels (Tool Function)
Encode readable table into binary trust level bit-flags
- Argument 1: Trust level names (table)
- Return Value: Levels bitflag number (integer)
Example:
local num = Tool.EncodeTrustLevels({ ... })
Module: Twitch
The twitch module contains functions that interact with Twitch.
Source: /Source/Desynced/Lua/Module/DSTwitchModule.cpp
- Functions
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
- Argument 1: Callback which will get called with true or false depending on success (function)
Example:
Twitch.Login(function() ... end)
Logout (Twitch Function)
Clear any stored authentication parameters if logged in
Example:
Twitch.Logout()
IsLoggedIn (Twitch Function)
Check if the user is logged in on Twitch
- Return Value: Login status (boolean)
Example:
local flag = Twitch.IsLoggedIn()
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.
- Argument 1: Callback which will get called with user_id and display_name or nil on error (function)
Example:
Twitch.GetUserData(function() ... end)
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.
- Argument 1: Callback which will get called with an array of reward tables { id = "...", title = "..." } (function)
Example:
Twitch.GetCustomRewards(function() ... end)
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:
Twitch.StartRewards()
StopRewards (Twitch Function)
Stop listening for reward redemptions
Example:
Twitch.StopRewards()
StartChat (Twitch Function)
Start listening for chat messages
When a message is posted, UIMsg.TwitchOnChatMessage(username, message) will get called
- Argument 1: Channel name to join, can be omitted if logged in (OPTIONAL) (string)
Example:
Twitch.StartChat()Twitch.StartChat("text")
StopChat (Twitch Function)
Stop listening for chat messages
Example:
Twitch.StopChat()
Module: UI
The UI module contains UI related functions
Source: /Source/Desynced/Lua/Module/DSUIModule.cpp
- Functions
- Register
- IsRegistered
- New
- AddLayout
- FindWidgetWithTag
- FindWidgetsWithTag
- FindWidgetWithProperty
- FindWidgetsWithProperty
- GetRegisteredLayoutString
- SetRegisteredLayoutString
- GetRegisteredLayoutClass
- SetRegisteredLayoutClass
- GetWidgetsUnderCursor
- GetWidgetWithTagUnderCursor
- GetWidgetWithPropertyUnderCursor
- GetRootWidgets
- MakeModOptionsWidget
- GetMapSettingsArray
- GetScreenSize
- MenuPopup
- StartDrag
- CloseMenuPopup
- CloseTooltip
- RefreshTooltip
- Delay
- PlaySound
- StopMusic
- StopVoice
- StopAmbienceSound
- SetUIHidden
- IsUIHidden
- EntityLocationOnScreen
- Run
- GetLanguages
- GetLanguageCode
- SetLanguageCode
- GetScale
- SetScale
- GetMousePosition
- IsMouseOverUI
- SendChatGlobal
- SendChatPlayer
- SendChatFaction
- SendChatAlliance
Register (UI Function)
Register a layout definition tag
- Argument 1: Layout tag name (string)
- Argument 2: Layout string (string)
- Argument 3: Class table (OPTIONAL) (table)
- Argument 4: Set to true to overwrite an existing layout tag (OPTIONAL, default false) (boolean)
Example:
UI.Register("text", "text")UI.Register("text", "text", { ... }, true)
IsRegistered (UI Function)
Check if a layout tag has been registered
- Argument 1: Layout tag name (string)
- Return Value: True if known layout tag (boolean)
Example:
local flag = UI.IsRegistered("text")
New (UI Function)
Instantiate a new widget
- Argument 1: Layout Text (string)
- Argument 2: Property table (OPTIONAL) (table)
- Return Value: Created widget (or nil on error) (widget)
Example:
local some_widget = UI.New("text")local some_widget = UI.New("text", { ... })
AddLayout (UI Function)
Add widget to screen canvas
- Argument 1: Widget (widget)
- Argument 2: Ordering priority (OPTIONAL, default 0) (integer)
--- or --- - Argument 1: Layout text for creating a new widget inline (string)
- Argument 2: Property table for the inline widget (OPTIONAL) (table)
- Argument 3: Ordering priority (OPTIONAL, default 0) (integer)
- Return Value: The widget passed in the first argument (widget)
Example:
local some_widget = UI.AddLayout(widget)local some_widget = UI.AddLayout(widget, 1)local some_widget = UI.AddLayout("text")local some_widget = UI.AddLayout("text", { ... }, 1)
FindWidgetWithTag (UI Function)
Find a widget with a given tag that is on screen
- Argument 1: Layout tag name (string)
- Return Value: A widget with the given tag or nil if none is on screen (widget)
Example:
local some_widget = UI.FindWidgetWithTag("text")
FindWidgetsWithTag (UI Function)
Find all widgets with a given tag which are on screen
- Argument 1: Layout tag name (string)
- Return Value: An array with widgets with the given tag (table)
Example:
local tbl = UI.FindWidgetsWithTag("text")
FindWidgetWithProperty (UI Function)
Find a widget with a given property that is on screen
- Argument 1: Property key name (string)
- Argument 2: If set, also filter the exact value of the property (OPTIONAL) (anything)
- Return Value: A widget with the given tag or nil if none is on screen (widget)
Example:
local some_widget = UI.FindWidgetWithProperty("text")local some_widget = UI.FindWidgetWithProperty("text", ...)
FindWidgetsWithProperty (UI Function)
Find all widgets with a given property which are on screen
- Argument 1: Property key name (string)
- Argument 2: If set, also filter the exact value of the property (OPTIONAL) (anything)
- Return Value: An array with widgets with the given tag (table)
Example:
local tbl = UI.FindWidgetsWithProperty("text")local tbl = UI.FindWidgetsWithProperty("text", ...)
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.
- Argument 1: Layout tag name (string)
- Return Value: Layout string (string)
Example:
local str = UI.GetRegisteredLayoutString("text")
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.
- Argument 1: Layout tag name (string)
- Argument 2: New layout string (string)
Example:
UI.SetRegisteredLayoutString("text", "text")
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.
- Argument 1: Layout tag name (string)
- Return Value: Class table (table)
Example:
local tbl = UI.GetRegisteredLayoutClass("text")
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.
- Argument 1: Layout tag name (string)
- Argument 2: New class table (table)
Example:
UI.SetRegisteredLayoutClass("text", { ... })
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).
- Argument 1: X position to check or mouse cursor if not given (OPTIONAL) (number)
- Argument 2: Y position to check or mouse cursor if not given (OPTIONAL) (number)
- Return Value: An array with found widgets (table)
Example:
local tbl = UI.GetWidgetsUnderCursor()local tbl = UI.GetWidgetsUnderCursor(1, 1)
GetWidgetWithTagUnderCursor (UI Function)
Find a widgets with a given tag below the mouse cursor or at a position
- Argument 1: Layout tag name (string)
- Argument 2: X position to check or mouse cursor if not given (OPTIONAL) (number)
- Argument 3: Y position to check or mouse cursor if not given (OPTIONAL) (number)
- Return Value: A widget with the given tag or nil if none was found (widget)
Example:
local some_widget = UI.GetWidgetWithTagUnderCursor("text")local some_widget = UI.GetWidgetWithTagUnderCursor("text", 1, 1)
GetWidgetWithPropertyUnderCursor (UI Function)
Find a widgets with a given property below the mouse cursor or at a position
- Argument 1: Property key name (string)
- Argument 2: If set, also filter the exact value of the property (OPTIONAL) (anything)
- Argument 3: X position to check or mouse cursor if not given (OPTIONAL) (number)
- Argument 4: Y position to check or mouse cursor if not given (OPTIONAL) (number)
- Return Value: A widget with the given property or nil if none was found (widget)
Example:
local some_widget = UI.GetWidgetWithPropertyUnderCursor("text")local some_widget = UI.GetWidgetWithPropertyUnderCursor("text", ..., 1, 1)
GetRootWidgets (UI Function)
Get all widgets that have been attached to the screen canvas with UI.AddLayout.
- Return Value: An array with widgets attached to the screen canvas (table)
Example:
local tbl = UI.GetRootWidgets()
MakeModOptionsWidget (UI Function)
Instantiate the options widget of a mod
- Argument 1: Mod id (string)
- Return Value: Created widget (or nil on error) (widget)
Example:
local some_widget = UI.MakeModOptionsWidget("text")
GetMapSettingsArray (UI Function)
Get all custom map settings tables of the active or a specific scenario
- Argument 1: Mod package path ("Mod/Package") (OPTIONAL, default to active scenario) (string)
- Return Value: Array to add map settings tables (contains functions to build settings ui) (table)
Example:
local tbl = UI.GetMapSettingsArray()local tbl = UI.GetMapSettingsArray("text")
GetScreenSize (UI Function)
Get the size of the screen scaled in UI coordinates
- Return Value: Screen size X (number)
- Return Value: Screen size Y (number)
Example:
local num, num = UI.GetScreenSize()
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)
- Argument 1: Widget (widget)
- Argument 2: Pop up next to this widget (OPTIONAL, default pop up at mouse cursor) (widget)
- Argument 3: Direction (OPTIONAL, default DOWN or UP/LEFT/RIGHT/CENTER or special TOOLTIP/SCREEN) (string)
- Argument 4: Alignment (OPTIONAL, default MIDDLE or LEFT/RIGHT/TOP/BOTTOM) (string)
- Argument 5: Attachment X offset (OPTIONAL) (integer)
- Argument 6: Attachment Y offset (OPTIONAL) (integer)
--- or --- - Argument 1: Layout text for creating a new widget inline (string)
- Argument 2: Property table for the inline widget (OPTIONAL) (table)
- Argument 3: Pop up next to this widget (OPTIONAL, default pop up at mouse cursor) (widget)
- Argument 4: Direction (OPTIONAL, default DOWN or UP/LEFT/RIGHT/CENTER or special TOOLTIP/SCREEN) (string)
- Argument 5: Alignment (OPTIONAL, default MIDDLE or LEFT/RIGHT/TOP/BOTTOM) (string)
- Argument 6: Attachment X offset (OPTIONAL) (integer)
- Argument 7: Attachment Y offset (OPTIONAL) (integer)
- Return Value: The widget passed in the first argument or that was created (widget)
Example:
local some_widget = UI.MenuPopup(widget)local some_widget = UI.MenuPopup(widget, widget, "text", "text", 1, 1)local some_widget = UI.MenuPopup("text")local some_widget = UI.MenuPopup("text", { ... }, widget, "text", "text", 1, 1)
StartDrag (UI Function)
Force start a drag and drop operation without the user necessarily having to drag anything
- Argument 1: Drag payload widget (widget)
- Argument 2: Drag visual cursor widget (widget)
- Argument 3: Horizontal alignment of the visual to the cursor (-0.5 is left, 0 is centered, 0.5 is right) (OPTIONAL, default 0) (number)
- Argument 4: Vertical alignment of the visual to the cursor (-0.5 is top, 0 is centered, 0.5 is bottom) (OPTIONAL, default 0) (number)
- Argument 5: Set to true to snap the visual to the cursor, otherwise it will animate from the payload towards it (OPTIONAL, default false) (boolean)
- Return Value: True on success, false if drag already active or visual widget is already on screen (boolean)
Example:
local flag = UI.StartDrag(widget, widget)local flag = UI.StartDrag(widget, widget, 1, 1, true)
CloseMenuPopup (UI Function)
Close the context menu opened with MenuPopup
- Argument 1: Close popup containing this widget (OPTIONAL, default close all popups) (widget)
- Return Value: If a popup was actually closed (boolean)
Example:
local flag = UI.CloseMenuPopup()local flag = UI.CloseMenuPopup(widget)
CloseTooltip (UI Function)
Close the current tooltip
Example:
UI.CloseTooltip()
RefreshTooltip (UI Function)
Refresh the current tooltip
Example:
UI.RefreshTooltip()
Delay (UI Function)
Run code after a given delay (similar to widget tweens)
- Argument 1: Delay time in milliseconds (OPTIONAL, default to call after 1 frame) (number)
- Argument 2: Delay callback (function)
Example:
UI.Delay(function() ... end)UI.Delay(1, function() ... end)
PlaySound (UI Function)
Play a UI sound effect, music, voice or ambience
- Argument 1: Effect ID (string)
- Argument 2: Volume multiplier for sound effect (OPTIONAL, default 1) (integer)
- Argument 3: Pitch multiplier for sound effect (OPTIONAL, default 1) (integer)
- Argument 4: Start time for sound effect (OPTIONAL, default 0) (integer)
Example:
UI.PlaySound("text")UI.PlaySound("text", 1, 1, 1)
StopMusic (UI Function)
Stop the playing music
Example:
UI.StopMusic()
StopVoice (UI Function)
Stop the playing voice
Example:
UI.StopVoice()
StopAmbienceSound (UI Function)
Stop the playing ambience sound effect
Example:
UI.StopAmbienceSound()
SetUIHidden (UI Function)
Hide the entire UI
- Argument 1: UI hidden state (OPTIONAL, if not set will toggle) (boolean)
- Return Value: UI hidden state (boolean)
Example:
local flag = UI.SetUIHidden()local flag = UI.SetUIHidden(true)
IsUIHidden (UI Function)
Check if UI has been hidden with SetUIHidden
- Return Value: UI hidden state (boolean)
Example:
local flag = UI.IsUIHidden()
EntityLocationOnScreen (UI Function)
Query the UI coordinate of an entity in the game camera view
- Argument 1: Input entity (entity)
- Argument 2: Only return success if the position is on screen (or less than 100 points away from the screen border) (OPTIONAL, default false) (boolean)
- Argument 3: Also query invisible entities not currently rendered (far off camera or not in visible area) (OPTIONAL, default false) (boolean)
- Return Value: Success state (query can fail if the camera points away from the entity) (boolean)
- Return Value: Screen position X (number)
- Return Value: Screen position Y (number)
Example:
local flag, num, num = UI.EntityLocationOnScreen(other_entity)local flag, num, num = UI.EntityLocationOnScreen(other_entity, true, true)
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
- Argument 1: LUA function to execute in UI context (function)
- Argument 2: Passed values (OPTIONAL, can pass multiple values) (anything)
--- or --- - Argument 1: Message name registered in UIMsg (string)
- Argument 2: Passed values (OPTIONAL, can pass multiple values) (anything)
Example:
UI.Run(function() ... end)UI.Run(function() ... end, ...)UI.Run("text")UI.Run("text", ...)
GetLanguages (UI Function)
Get a table of languages
- Return Value: languages (pairs of 'code' = 'name') (table)
Example:
local tbl = UI.GetLanguages()
GetLanguageCode (UI Function)
Get the current language code
- Return Value: language code (for example 'en_us') (string)
Example:
local str = UI.GetLanguageCode()
SetLanguageCode (UI Function)
Change the active language
- Argument 1: language code (for example 'en_us') (string)
Example:
UI.SetLanguageCode("text")
GetScale (UI Function)
Get the UI scale factor
- Return Value: scale factor (1.0 being 100%) (number)
Example:
local num = UI.GetScale()
SetScale (UI Function)
Set the UI scale factor
- Argument 1: scale factor (1.0 being 100%) (number)
Example:
UI.SetScale(1)
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
- Argument 1: Widget to get relative position to (OPTIONAL) (widget)
- Return Value: x position of mouse cursor (number)
- Return Value: y position of mouse cursor (number)
Example:
local num, num = UI.GetMousePosition()local num, num = UI.GetMousePosition(widget)
IsMouseOverUI (UI Function)
Check if the mouse cursor is over a UI widget
- Return Value: True if mouse is over UI (boolean)
Example:
local flag = UI.IsMouseOverUI()
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)
- Argument 1: Function name (string)
- Argument 2: Argument table to pass (will be copied, not referenced) (OPTIONAL) (table)
Example:
UI.SendChatGlobal("text")UI.SendChatGlobal("text", { ... })
SendChatPlayer (UI Function)
Send chat function call to a specific player
- Argument 1: Function name (string)
- Argument 2: Target player id (integer)
- Argument 3: Argument table to pass (will be copied, not referenced) (OPTIONAL) (table)
Example:
UI.SendChatPlayer("text", 1)UI.SendChatPlayer("text", 1, { ... })
SendChatFaction (UI Function)
Send chat function call to all players of the local or a specific faction
- Argument 1: Function name (string)
- Argument 2: Argument table to pass (will be copied, not referenced) (OPTIONAL) (table)
- Argument 3: Target faction (OPTIONAL, default local player faction) (faction)
Example:
UI.SendChatFaction("text")UI.SendChatFaction("text", { ... }, "faction_id")
SendChatAlliance (UI Function)
Send chat function call to all players that share visibility with the local or a specific faction
- Argument 1: Function name (string)
- Argument 2: Argument table to pass (will be copied, not referenced) (OPTIONAL) (table)
- Argument 3: Target faction (OPTIONAL, default local player faction) (faction)
Example:
UI.SendChatAlliance("text")UI.SendChatAlliance("text", { ... }, "faction_id")
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
- Functions
- GetHoveredTilePosition
- GetHoveredEntity
- ResetCamera
- MoveCamera
- JumpCameraToEntities
- GetCameraZoom
- FollowEntity
- GetFollowEntity
- SetVisualizations
- GetSelectedEntities
- GetSelectedEntity
- IsSelectedEntity
- SelectEntities
- SelectPreviousEntities
- HighlightEntity
- StartCursorChooseLocation
- StartCursorChooseEntity
- StartCursorConstruction
- StopCursor
- RotateConstructionSite
- SetPostProcess
- PlayEffect
- SetEffectParam
- StopEffect
- InConstructionMode
- GetVisibleEntities
- SetCamera3DPosition
- GetCamera3DPosition
- PanCamera3DPosition
- TiltCamera3DRotation
- LockCamera
- UnlockCamera
- IsRunningHeadless
GetHoveredTilePosition (View Function)
Get the location of the currently hovered tile
- Return Value: X factor of the virtual cursor (integer)
- Return Value: Y factor of the virtual cursor (integer)
Example:
local num, num = View.GetHoveredTilePosition()
GetHoveredEntity (View Function)
Get the entity currently hovered
- Argument 1: Filter by frame type (FF_FOUNDATION, FF_WALL, FF_GATE, FF_DROPPEDITEM, FF_CONSTRUCTION, FF_RESOURCE, FF_OPERATING) or faction (FF_OWNFACTION, FF_ENEMYFACTION, FF_NEUTRALFACTION, FF_ALLYFACTION, FF_WORLDFACTION) (OPTIONAL, default FF_ALL) (integer)
- Return Value: Hovered entity (or nil if none) (entity)
Example:
local some_entity = View.GetHoveredEntity()local some_entity = View.GetHoveredEntity(1)
ResetCamera (View Function)
Reset the camera to the faction home location
- Argument 1: Whether to reset zoom level (OPTIONAL, default true) (boolean)
Example:
View.ResetCamera()View.ResetCamera(true)
MoveCamera (View Function)
Move the camera to a given location
- Argument 1: X position (integer)
- Argument 2: Y position (integer)
- Argument 3: Whether to reset zoom level (OPTIONAL, default true) (boolean)
Example:
View.MoveCamera(1, 1)View.MoveCamera(1, 1, true)
JumpCameraToEntities (View Function)
Focus the camera on one or more entities
- Argument 1: List of entities to focus on (table)
--- or --- - Argument 1: Entities to focus on (argument can be repeated) (entity)
Example:
View.JumpCameraToEntities({ ... })View.JumpCameraToEntities(other_entity)
GetCameraZoom (View Function)
Get Local camera zoom distance
- Return Value: Camera zoom distance (number)
Example:
local num = View.GetCameraZoom()
FollowEntity (View Function)
Sets the entity for the camera to follow
- Argument 1: Entity to follow or nil to stop follow (OPTIONAL) (entity)
Example:
View.FollowEntity()View.FollowEntity(other_entity)
GetFollowEntity (View Function)
Get the entity currently followed by the camera
- Return Value: Followed entity (or nil if there is none) (entity)
Example:
local some_entity = View.GetFollowEntity()
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 },
}
- Argument 1: Table with settings that are to be changed (table)
Example:
View.SetVisualizations({ ... })
GetSelectedEntities (View Function)
Get the currently selected entities
- Return Value: List of selected entities (or nil if empty) (table)
Example:
local tbl = View.GetSelectedEntities()
GetSelectedEntity (View Function)
Get the currently selected entity (will be just the first if multiple are selected)
- Return Value: Selected entity (or nil if empty) (entity)
Example:
local some_entity = View.GetSelectedEntity()
IsSelectedEntity (View Function)
Check if an entity is selected
- Argument 1: Entity to check (entity)
- Return Value: Result of check (boolean)
Example:
local flag = View.IsSelectedEntity(other_entity)
SelectEntities (View Function)
Set the selected entity(s)
- Argument 1: List of entities to select (or nil to unselect everything) (table)
--- or --- - Argument 1: Entities to select (argument can be repeated) (entity)
Example:
View.SelectEntities()View.SelectEntities({ ... })View.SelectEntities(other_entity)
SelectPreviousEntities (View Function)
Switch entity selection to previously selected entities
Example:
View.SelectPreviousEntities()
HighlightEntity (View Function)
Highlight an entity
- Argument 1: Entity to highlight (or nil to remove highlight) (entity)
Example:
View.HighlightEntity()View.HighlightEntity(other_entity)
StartCursorChooseLocation (View Function)
Switch to a cursor mode to select a location on the map
- Argument 1: LUA function called when confirming a location with the location as the argument (function)
- Argument 2: LUA function called when placing aborting the cursor mode (OPTIONAL) (function)
Example:
View.StartCursorChooseLocation(function() ... end)View.StartCursorChooseLocation(function() ... end, function() ... end)
StartCursorChooseEntity (View Function)
Switch to a cursor mode to select an entity on the map
- Argument 1: LUA function called when confirming an entity with the entity as the argument (function)
- Argument 2: LUA function called when aborting the cursor mode (OPTIONAL) (function)
- Argument 3: Set to true to include foundations in selection (OPTIONAL, default false) (boolean)
Example:
View.StartCursorChooseEntity(function() ... end)View.StartCursorChooseEntity(function() ... end, function() ... end, true)
StartCursorConstruction (View Function)
Show entity construction location selection on map
- Argument 1: Frame id (string)
- Argument 2: Specific visual id or another frame id from which to use the visual (OPTIONAL, defaults to frame visual) (string)
- Argument 3: Rotation (0 to 3) (OPTIONAL, otherwise remembers last used rotation) (integer)
- Argument 4: LUA function called when confirming placement with arguments (location, rotation, is_valid) location will be an array if dragging is enabled (OPTIONAL) (function)
- Argument 5: LUA function called when aborting the cursor mode (OPTIONAL) (function)
- Argument 6: LUA function called to check placement with arguments (x, y, rotation, is_visible, can_place, is_powered, size_x, size_y) (OPTIONAL) (function)
- Argument 7: Set to true to allow placing multiple constructions via dragging (OPTIONAL, default false) (boolean)
--- or --- - Argument 1: Array of tables with fields frame (frame id), x/y (optional position offsets), rotation (optional rotation) (table)
- Argument 2: Rotation (0 to 3) (OPTIONAL, otherwise remembers last used rotation) (integer)
- Argument 3: LUA function called when confirming placement with arguments (location, rotation, is_valid) location will be an array if dragging is enabled (OPTIONAL) (function)
- Argument 4: LUA function called when aborting the cursor mode (OPTIONAL) (function)
- Argument 5: LUA function called to check placement with arguments (x, y, rotation, is_visible, can_place, is_powered, size_x, size_y) (OPTIONAL) (function)
- Argument 6: Set to true to allow placing multiple constructions via dragging (OPTIONAL, default false) (boolean)
Example:
View.StartCursorConstruction("text")View.StartCursorConstruction("text", "text", 1, function() ... end, function() ... end, function() ... end, true)View.StartCursorConstruction({ ... })View.StartCursorConstruction({ ... }, 1, function() ... end, function() ... end, function() ... end, true)
StopCursor (View Function)
Cancel cursor mode started with the functions above
Example:
View.StopCursor()
RotateConstructionSite (View Function)
RotateConstructionSite
- Argument 1: Clockwise (OPTIONAL, default false) (boolean)
Example:
View.RotateConstructionSite()View.RotateConstructionSite(true)
SetPostProcess (View Function)
Set a fullscreen effect parameter
- Argument 1: Effect name (string)
- Argument 2: Effect value (numerical or color value) (anything)
Example:
View.SetPostProcess("text", ...)
PlayEffect (View Function)
Play effect at a location
- Argument 1: effect id (string)
- Argument 2: Tile Location X (integer)
- Argument 3: Tile Location Y (integer)
- Argument 4: Set to true to not show the effect outside the local player factions visibility (OPTIONAL, default false) (boolean)
--- or --- - Argument 1: effect id (string)
- Argument 2: entity to play it on (entity)
- Argument 3: Socket name (OPTIONAL) (string)
- Argument 4: Target entity (OPTIONAL) (entity)
- Argument 5: Render instance number (OPTIONAL) (integer)
- Argument 6: Particle effect parameter table (OPTIONAL) (table)
- Return Value: Effect instance (can be used with
View.StopEffect) (integer)
Example:
local num = View.PlayEffect("text", 1, 1)local num = View.PlayEffect("text", 1, 1, true)local num = View.PlayEffect("text", other_entity)local num = View.PlayEffect("text", other_entity, "text", other_entity, 1, { ... })
SetEffectParam (View Function)
Set a parameter on an effect started with View.PlayEffect
- Argument 1: Effect instance (integer)
- Argument 2: Parameter name (string)
- Argument 3: Parameter value (numerical or color value) (anything)
Example:
View.SetEffectParam(1, "text", ...)
StopEffect (View Function)
Stop an effect started with View.PlayEffect
- Argument 1: Effect instance (integer)
Example:
View.StopEffect(1)
InConstructionMode (View Function)
Checks if the player is currently in construction mode
- Return Value: Is in construction mode (boolean)
Example:
local flag = View.InConstructionMode()
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'
- Argument 1: Pass a table to use it as a cache for the return value to avoid allocating a new large table (OPTIONAL) (table)
- Argument 2: Set to true to only get entities with health not at the maximum (OPTIONAL, default false) (boolean)
- Argument 3: Set to true to not get any entities with stealth state unless owned or allied (OPTIONAL, default false) (boolean)
- Argument 4: Return only entities matching a certain trust level (OPTIONAL) (integer)
- Return Value: One array with 5 or 7 elements for each entity (entity, X, Y, distance, trust, health/max_health if true was passed) (table)
- Return Value: How many elements were written to the table (entity count * 4 or 6) (integer)
Example:
local tbl, num = View.GetVisibleEntities()local tbl, num = View.GetVisibleEntities({ ... }, true, true, 1)
SetCamera3DPosition (View Function)
Set the full 3D camera position and target location directly
- Argument 1: A table with x, y and z camera position (or nil if only setting the target location) (3d coordinate)
- Argument 2: A table with x, y and z target location (or nil if only setting the camera position) (3d coordinate)
Example:
View.SetCamera3DPosition()View.SetCamera3DPosition({ x = 1, y = 2, z = 3 }, { x = 1, y = 2, z = 3 })
GetCamera3DPosition (View Function)
Get the 3D camera position and target location
- Return Value: A table with x, y and z camera position (3d coordinate)
- Return Value: A table with x, y and z target location (3d coordinate)
- Return Value: A table with x, y and z normalized look direction (3d coordinate)
- Return Value: Distance from camera position to target location (number)
Example:
local pos, pos, pos, num = View.GetCamera3DPosition()
PanCamera3DPosition (View Function)
Directly shift the camera in 3D space (relative to the current camera rotation)
- Argument 1: Forward/backward move amount (number)
- Argument 2: Right/left move amount (number)
- Argument 3: Up/down move amount (number)
Example:
View.PanCamera3DPosition(1, 1, 1)
TiltCamera3DRotation (View Function)
Directly rotate the camera in place
- Argument 1: Yaw amount in degrees (how much to rotate around the Z axis) (number)
- Argument 2: Pitch amount in degrees (how much to rotate up and down) (number)
Example:
View.TiltCamera3DRotation(1, 1)
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:
View.LockCamera()
UnlockCamera (View Function)
Unlock the camera again after having LockCamera called
Example:
View.UnlockCamera()
IsRunningHeadless (View Function)
Check if the game is running without rendering (headless)
- Return Value: Is in construction mode (boolean)
Example:
local flag = View.IsRunningHeadless()
Meta Tables
Meta Table: Component
A component object represents a component equipped by an entity.
Source: /Source/Desynced/Lua/Meta/DSComponentLuaMeta.cpp
- Functions
- Destroy
- PrepareRemoval
- GetRegister
- GetRegisterNum
- GetRegisterId
- GetRegisterDef
- GetRegisterEntity
- GetRegisterCoord
- RegistersEqual
- SetRegister
- SetRegisterNum
- SetRegisterId
- SetRegisterEntity
- SetRegisterCoord
- FlagRegisterError
- RegisterIsLink
- RegisterIsEmpty
- RegisterIsError
- RegisterHasConnection
- LinkRegisterFromRegister
- UnlinkRegisterFromRegister
- GetRegisterLinkSource
- GetRegisterLinkTarget
- HaveRegisterQueue
- RegisterQueueLength
- RegisterQueueGet
- RegisterQueueGetAll
- RegisterQueueSet
- RegisterQueueInsert
- RegisterQueueRemove
- GetSlot
- ClearActivationChangeFlags
- PrepareProduceProcess
- PrepareGenerateProcess
- PrepareConsumeProcess
- FulfillProcess
- CancelProcess
- GetProcessConsumeSlot
- GetProcessOutputSlot
- OrderItem
- RotateComponent
- RequestStateMove
- SetStateSleep
- SetStateStartWork
- NotifyWorkFailed
- SetStateContinueWork
- WaitForFirstRegisterChange
- WaitForComponentRegisterChange
- WaitForFirstItemSlotChange
- WaitForComponentItemSlotChange
- WaitForLowPower
- WaitForPowerStoredEmpty
- WaitForOtherCompFinish
- Activate
- Shutdown
- CauseToString
- FindClosestTriggeringEntity
- PlayEffect
- PlayWorkEffect
- StopEffects
- SetWorkAnimationSpeed
- Variables
- owner
- faction
- exists
- key
- id
- base_id
- def
- visual_id
- visual_def
- socket_index
- slot_index
- slot_count
- slots
- register_index
- register_count
- is_empty
- is_hidden
- is_active
- is_working
- is_sleeping
- is_updating
- has_move_control
- has_prepared_process
- progress_percent
- interpolated_progress
- ticker
- ticker_target
- has_extra_data
- extra_data
- stored_power
- extra_power
- extra_transfer_range
- power_relay_target
- power_details
- animation_speed
- light_color
- has_active_effects
- triggering_entities
- Operators
Component Functions
Destroy (Component Function)
destroys a component
- Argument 1: Remove contained items by moving into other slots or dropping (OPTIONAL, default false) (boolean)
- Return Value: The final state of the extra_data value after on_remove has been called (table)
Example:
local tbl = component:Destroy()local tbl = component:Destroy(true)
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).
- Argument 1: An item slot that should be kept empty (OPTIONAL) (itemslot)
- Argument 2: Forces dropping of items even for buildings (OPTIONAL, default false) (boolean)
- Return Value: Result (boolean)
Example:
local flag = component:PrepareRemoval()local flag = component:PrepareRemoval(item_slot, true)
GetRegister (Component Function)
Get a register of this component
- Argument 1: Register reference (register reference)
- Return Value: Register object (register)
Example:
local reg = component:GetRegister(1)
GetRegisterNum (Component Function)
Get the number part of a register of this component
- Argument 1: Register reference (register reference)
- Return Value: Number value (integer)
Example:
local num = component:GetRegisterNum(1)
GetRegisterId (Component Function)
Get the id part of a register of this component
- Argument 1: Register reference (register reference)
- Return Value: Id value (id-string)
Example:
local id = component:GetRegisterId(1)
GetRegisterDef (Component Function)
Get the definition table of the id stored in a register of this component
- Argument 1: Register reference (register reference)
- Return Value: Definition table (table)
Example:
local tbl = component:GetRegisterDef(1)
GetRegisterEntity (Component Function)
Get the entity part of a register of this component
- Argument 1: Register reference (register reference)
- Return Value: Entity value (entity)
Example:
local some_entity = component:GetRegisterEntity(1)
GetRegisterCoord (Component Function)
Get the coordinate part of a register of this component
- Argument 1: Register reference (register reference)
- Return Value: Coordinate value (coordinate)
Example:
local pos = component:GetRegisterCoord(1)
RegistersEqual (Component Function)
Compare two registers of this component
- Argument 1: First register reference (register reference)
- Argument 2: Second register reference (register reference)
- Return Value: Comparison result (boolean)
Example:
local flag = component:RegistersEqual(1, 1)
SetRegister (Component Function)
Set a register of this component
- Argument 1: Register reference (register reference)
- Argument 2: Register object or table (or nil to clear a register) (register)
- Argument 3: Force update the register and activate the component (OPTIONAL, default false) (boolean)
Example:
component:SetRegister(1, { num = 10, id = "id" })component:SetRegister(1, { num = 10, id = "id" }, true)
SetRegisterNum (Component Function)
Set the number part of a register of this component
- Argument 1: Register reference (register reference)
- Argument 2: Number value (integer)
Example:
component:SetRegisterNum(1, 1)
SetRegisterId (Component Function)
Set the id part of a register of this component (will overwrites the entity/coordinate part)
- Argument 1: Register reference (register reference)
- Argument 2: Id value (or nil to clear the id part) (string)
- Argument 3: Number value (OPTIONAL) (integer)
Example:
component:SetRegisterId(1)component:SetRegisterId(1, "text", 1)
SetRegisterEntity (Component Function)
Set the entity part of a register of this component (will overwrite the id/coordinate part)
- Argument 1: Register reference (register reference)
- Argument 2: Entity value (or nil to clear the entity part) (entity)
- Argument 3: Number value (OPTIONAL) (integer)
Example:
component:SetRegisterEntity(1)component:SetRegisterEntity(1, other_entity, 1)
SetRegisterCoord (Component Function)
Set the coordinate part of a register of this component (will overwrite the id/entity part)
- Argument 1: Register reference (register reference)
- Argument 2: Coordinate value (or nil to clear the coordinate part) (coordinate)
- Argument 3: Number value (OPTIONAL) (integer)
Example:
component:SetRegisterCoord(1)component:SetRegisterCoord(1, { x = 1, y = 2 }, 1)
FlagRegisterError (Component Function)
Flag the error state on a register of this component
Will stay flagged until the register value changes.
- Argument 1: Register reference (register reference)
- Argument 2: Whether to set the error state (OPTIONAL, default true) (boolean)
Example:
component:FlagRegisterError(1)component:FlagRegisterError(1, true)
RegisterIsLink (Component Function)
Check if a register of this component is linked from another register
- Argument 1: Register reference (register reference)
- Return Value: Link state (boolean)
Example:
local flag = component:RegisterIsLink(1)
RegisterIsEmpty (Component Function)
Check if a register of this component is empty
- Argument 1: Register reference (register reference)
- Return Value: Empty state (boolean)
Example:
local flag = component:RegisterIsEmpty(1)
RegisterIsError (Component Function)
Check if a register of this component is in error state
- Argument 1: Register reference (register reference)
- Return Value: Error state (boolean)
Example:
local flag = component:RegisterIsError(1)
RegisterHasConnection (Component Function)
Check if two registers have a connection via link(s)
- Argument 1: Register one (register reference)
- Argument 2: Register two (register reference)
- Argument 3: Different entity that holds the second register (OPTIONAL) (entity)
--- or --- - Argument 1: Register one (register reference)
- Argument 2: Register two (register reference)
- Argument 3: A component that holds the second register (component)
- Return Value: Check result (boolean)
Example:
local flag = component:RegisterHasConnection(1, 1)local flag = component:RegisterHasConnection(1, 1, other_entity)local flag = component:RegisterHasConnection(1, 1, comp)
LinkRegisterFromRegister (Component Function)
Link a register from another register
- Argument 1: Target register reference (register reference)
- Argument 2: Source register reference (register reference)
- Argument 3: Different entity that holds the source register (OPTIONAL) (entity)
--- or --- - Argument 1: Target register reference (register reference)
- Argument 2: Source register reference (register reference)
- Argument 3: A component that holds the source register (component)
Example:
component:LinkRegisterFromRegister(1, 1)component:LinkRegisterFromRegister(1, 1, other_entity)component:LinkRegisterFromRegister(1, 1, comp)
UnlinkRegisterFromRegister (Component Function)
Unlink a register from another register
- Argument 1: Target register reference (register reference)
- Argument 2: Source register reference (register reference)
- Argument 3: Different entity that holds the source register (OPTIONAL) (entity)
--- or --- - Argument 1: Target register reference (register reference)
- Argument 2: Source register reference (register reference)
- Argument 3: A component that holds the source register (component)
Example:
component:UnlinkRegisterFromRegister(1, 1)component:UnlinkRegisterFromRegister(1, 1, other_entity)component:UnlinkRegisterFromRegister(1, 1, comp)
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.
- Argument 1: Target register reference (register reference)
--- or --- - Argument 1: Target register reference (register reference)
- Argument 2: Entity that holds the source register (entity)
--- or --- - Argument 1: Target register reference (register reference)
- Argument 2: Component that holds the source register (component)
- Return Value: Source register index, absolute entity index unless a source component is specified (or nil if not exist) (integer)
- Return Value: Entity that holds the source register (unless entity/component specified) (entity)
- Return Value: Component that holds the source register or nil if frame register (unless entity/component specified) (component)
Example:
local num, some_entity, some_component = component:GetRegisterLinkSource(1)local num, some_entity, some_component = component:GetRegisterLinkSource(1, other_entity)local num, some_entity, some_component = component:GetRegisterLinkSource(1, comp)
GetRegisterLinkTarget (Component Function)
Get the target index of the first relevant register link
- Argument 1: Source register reference (register reference)
- Argument 2: Different entity that holds the source register (OPTIONAL) (entity)
--- or --- - Argument 1: Source register reference (register reference)
- Argument 2: A component that holds the source register (component)
- Return Value: Target register index, relative to this component (or nil if not exist) (integer)
Example:
local num = component:GetRegisterLinkTarget(1)local num = component:GetRegisterLinkTarget(1, other_entity)local num = component:GetRegisterLinkTarget(1, comp)
HaveRegisterQueue (Component Function)
Check if a register of this entity has a queue (2 or more elements)
- Argument 1: Register reference (register reference)
- Return Value: Queue has 2 or more elements (boolean)
Example:
local flag = component:HaveRegisterQueue(1)
RegisterQueueLength (Component Function)
Count the number of queued elements
- Argument 1: Register reference (register reference)
- Return Value: Queue length (having nothing queued returns 1, register with links returns 0) (integer)
Example:
local num = component:RegisterQueueLength(1)
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.
- Argument 1: Register reference (register reference)
- Argument 2: Queue index (OPTIONAL, default to last) (integer)
- Return Value: Register object (or nil if invalid index) (register)
Example:
local reg = component:RegisterQueueGet(1)local reg = component:RegisterQueueGet(1, 1)
RegisterQueueGetAll (Component Function)
Get the entire queue as an array
- Argument 1: Register reference (register reference)
- Return Value: An array of register values of the same length as
RegisterQueueLength(table)
Example:
local tbl = component:RegisterQueueGetAll(1)
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).
- Argument 1: Register reference (register reference)
- Argument 2: Register object or table (register)
- Argument 3: Queue index (OPTIONAL, default to last) (integer)
Example:
component:RegisterQueueSet(1, { num = 10, id = "id" })component:RegisterQueueSet(1, { num = 10, id = "id" }, 1)
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).
- Argument 1: Register reference (register reference)
- Argument 2: Register object or table (register)
- Argument 3: Insertion index (OPTIONAL, default to appending to the end) (integer)
Example:
component:RegisterQueueInsert(1, { num = 10, id = "id" })component:RegisterQueueInsert(1, { num = 10, id = "id" }, 1)
RegisterQueueRemove (Component Function)
Remove a queued element
- Argument 1: Register reference (register reference)
- Argument 2: Queue index (OPTIONAL, default to last) (integer)
- Return Value: Removed register object (or nil if invalid index) (register)
Example:
local reg = component:RegisterQueueRemove(1)local reg = component:RegisterQueueRemove(1, 1)
GetSlot (Component Function)
Get an item slot of this component
- Argument 1: Slot number (starts at 1) (integer)
- Return Value: Item slot object (itemslot)
Example:
local some_slot = component:GetSlot(1)
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:
component:ClearActivationChangeFlags()
PrepareProduceProcess (Component Function)
Set up a process that consumes ingredients and generates output items
- Argument 1: Ingredients table (item_id keys and count values) (table)
- Argument 2: Outputs table (item_id keys and count values) (when nil, act like PrepareConsumeProcess) (table)
- Argument 3: Order count (if multiple processes are queued up) (OPTIONAL, default 1) (integer)
- Return Value: Returns true if inventory space for outputs and ingredient amounts are available now and process can start (boolean)
- Return Value: A register value describing the first missing ingredient (or nil if all ingredients are available) (register)
- Return Value: Returns true if not enough slots exist for all ingredients and outputs (boolean)
Example:
local flag, reg, flag = component:PrepareProduceProcess({ ... })local flag, reg, flag = component:PrepareProduceProcess({ ... }, { ... }, 1)
PrepareGenerateProcess (Component Function)
Set up a process that generates output items
- Argument 1: Outputs table (item_id keys and count values) (table)
- Return Value: Returns true if inventory space for outputs are available now and process can start (boolean)
Example:
local flag = component:PrepareGenerateProcess({ ... })
PrepareConsumeProcess (Component Function)
Set up a process that consumes ingredients
- Argument 1: Ingredients table (item_id keys and count values) (table)
- Argument 2: Order count (if multiple processes are queued up) (OPTIONAL, default 1) (integer)
--- or --- - Argument 1: Ingredients table (item_id keys and count values) (table)
- Argument 2: Consume from specific item slot (itemslot)
- Return Value: Returns true if ingredient amounts are available now and process can start (boolean)
- Return Value: A register value describing the first missing ingredient (or nil if all ingredients are available) (register)
- Return Value: Returns true if not enough slots exist for all ingredients (boolean)
Example:
local flag, reg, flag = component:PrepareConsumeProcess({ ... })local flag, reg, flag = component:PrepareConsumeProcess({ ... }, 1)local flag, reg, flag = component:PrepareConsumeProcess({ ... }, item_slot)
FulfillProcess (Component Function)
Finish a prepared process (add generated items and remove consumed ingredients)
- Argument 1: Pass true to receive a table with item id keys, each with an array of extra_data tables that have been remove from consumed ingredients (OPTIONAL, default false) (boolean)
- Return Value: The extra data table collection if it was requested and if there was at least one ingredient with an extra_data table (table)
Example:
local tbl = component:FulfillProcess()local tbl = component:FulfillProcess(true)
CancelProcess (Component Function)
Cancel ongoing process and related orders from this component
Example:
component:CancelProcess()
GetProcessConsumeSlot (Component Function)
If there is a prepared process, get an item slot from which items are consumed from.
- Argument 1: This selects the slot when there are multiple consume slots (OPTIONAL, default 1) (integer)
- Return Value: Consuming item slot (nil if no active consume process or invalid argument) (itemslot)
Example:
local some_slot = component:GetProcessConsumeSlot()local some_slot = component:GetProcessConsumeSlot(1)
GetProcessOutputSlot (Component Function)
If there is a prepared process, get an item slot from which items are output to.
- Argument 1: This selects the slot when there are multiple output slots (OPTIONAL, default 1) (integer)
- Return Value: Output item slot (nil if no active generate process or invalid argument) (itemslot)
Example:
local some_slot = component:GetProcessOutputSlot()local some_slot = component:GetProcessOutputSlot(1)
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.
- Argument 1: Item id to be ordered (string)
- Argument 2: Amount to be ordered (integer)
- Argument 3: Mode "None", "HighPriority", "ManualOrder", "Recurring", "ManualOrder|Recurring" (OPTIONAL, default "None") (string)
- Argument 4: If set and not 0, make the order on the channels denoted by the set bits (OPTIONAL) (integer)
- Return Value: Order ID created or modified (integer)
Example:
local num = component:OrderItem("text", 1)local num = component:OrderItem("text", 1, "text", 1)
RotateComponent (Component Function)
Turns component to look at a target entity or location
- Argument 1: Target entity to look at (entity)
- Argument 2: If the entity has movement rotate it instead (OPTIONAL, default false) (boolean)
--- or --- - Argument 1: Target component whose owning entity to look at (component)
- Argument 2: If the entity has movement rotate it instead (OPTIONAL, default false) (boolean)
--- or --- - Argument 1: Location or area to look at (area, coordinate or entity)
- Argument 2: If the entity has movement rotate it instead (OPTIONAL, default false) (boolean)
--- or --- - Argument 1: Offset degree amount to rotate (negative or positive) (number)
Example:
component:RotateComponent(other_entity)component:RotateComponent(other_entity, true)component:RotateComponent(comp)component:RotateComponent(comp, true)component:RotateComponent(entity OR [ x, y ] OR [ x, y, w, h ])component:RotateComponent(entity OR [ x, y ] OR [ x, y, w, h ], true)component:RotateComponent(1)
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.
- Argument 1: Target entity to move next to (entity)
- Argument 2: Range of how close by to stop (OPTIONAL, default 1) (integer)
- Argument 3: Keep moving when component sleeps or starts working (OPTIONAL, default false) (boolean)
--- or --- - Argument 1: Target component whose owning entity to move next to (component)
- Argument 2: Range of how close by to stop (OPTIONAL, default 1) (integer)
- Argument 3: Keep moving when component sleeps or starts working (OPTIONAL, default false) (boolean)
--- or --- - Argument 1: Location or area to move to (area, coordinate or entity)
- Argument 2: Range of how close by to stop (OPTIONAL, default 0) (integer)
- Argument 3: Keep moving when component sleeps or starts working (OPTIONAL, default false) (boolean)
- Return Value: Returns true if movement is needed, otherwise the entity is already in place (boolean)
Example:
local flag = component:RequestStateMove(other_entity)local flag = component:RequestStateMove(other_entity, 1, true)local flag = component:RequestStateMove(comp)local flag = component:RequestStateMove(comp, 1, true)local flag = component:RequestStateMove(entity OR [ x, y ] OR [ x, y, w, h ])local flag = component:RequestStateMove(entity OR [ x, y ] OR [ x, y, w, h ], 1, true)
SetStateSleep (Component Function)
Request the component to sleep
- Argument 1: Number of ticks to sleep (OPTIONAL, default 5) (integer)
- Argument 2: Keep movement control (OPTIONAL, default false) (boolean)
Example:
component:SetStateSleep()component:SetStateSleep(1, true)
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.
- Argument 1: Number of ticks to work (OPTIONAL, default 5) (integer)
- Argument 2: Refresh flag, if true, the component will be updated every 5 ticks during work (OPTIONAL, default false) (boolean)
- Argument 3: Continue work flag, if true, don't restart if already working (OPTIONAL, default false) (boolean)
--- or --- - Argument 1: Total number of ticks to work (integer)
- Argument 2: Refresh tick count, will update the component periodically during work (max 255) (integer)
- Argument 3: Continue work flag, if true, don't restart if already working (OPTIONAL, default false) (boolean)
Example:
component:SetStateStartWork()component:SetStateStartWork(1, true, true)component:SetStateStartWork(1, 1)component:SetStateStartWork(1, 1, true)
NotifyWorkFailed (Component Function)
Notify other components waiting for this with CC_OTHER_COMP_FAIL_WORK
Example:
component:NotifyWorkFailed()
SetStateContinueWork (Component Function)
Continue work that was started with SetStateStartWork
Example:
component:SetStateContinueWork()
WaitForFirstRegisterChange (Component Function)
Get called back the next time the first register of this component changes
Example:
component:WaitForFirstRegisterChange()
WaitForComponentRegisterChange (Component Function)
Get called back the next time any register of this component changes
Example:
component:WaitForComponentRegisterChange()
WaitForFirstItemSlotChange (Component Function)
Get called back the next time the first item slot of this component changes
Example:
component:WaitForFirstItemSlotChange()
WaitForComponentItemSlotChange (Component Function)
Get called back the next time any item slot of this component changes
Example:
component:WaitForComponentItemSlotChange()
WaitForLowPower (Component Function)
Get called back the next time the entity has low power
Example:
component:WaitForLowPower()
WaitForPowerStoredEmpty (Component Function)
Get called back the next time the battery charge is empty
Example:
component:WaitForPowerStoredEmpty()
WaitForOtherCompFinish (Component Function)
Get called back when another component finishes work
It is not possible to wait on multiple components simultaneously
- Argument 1: Another component to get called back the next time it finishes work (component)
Example:
component:WaitForOtherCompFinish(comp)
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:
component:Activate()
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:
component:Shutdown()
CauseToString (Component Function)
Convert a numerical cause variable received in on_update to a string (for debugging purpose)
- Argument 1: Cause (integer)
Example:
component:CauseToString(1)
FindClosestTriggeringEntity (Component Function)
Search for the closest entity of all matching entities inside this components trigger_radius
- Argument 1: Callback called for each entity in range in order of distance, return true from this to stop the search (function)
- Argument 2: Filter by frame type (FF_FOUNDATION, FF_WALL, FF_GATE, FF_DROPPEDITEM, FF_CONSTRUCTION, FF_RESOURCE, FF_OPERATING) or faction (FF_OWNFACTION, FF_ENEMYFACTION, FF_NEUTRALFACTION, FF_ALLYFACTION, FF_WORLDFACTION) (OPTIONAL, default FF_ALL) (integer)
- Return Value: The entity for which the callback returned true (or nil if none) (entity)
Example:
local some_entity = component:FindClosestTriggeringEntity(function() ... end)local some_entity = component:FindClosestTriggeringEntity(function() ... end, 1)
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.
- Argument 1: Effect ID (string)
- Argument 2: Socket name (OPTIONAL) (string)
- Argument 3: Target entity (only for non-looping effects) (OPTIONAL) (entity)
- Argument 4: Particle effect parameter table (only for non-looping effects) (OPTIONAL) (table)
- Argument 5: Render instance number on target if set otherwise on source (OPTIONAL) (integer)
- Return Value: Effect instance index (only for looping effects, can be used with
entity:StopEffect) (integer)
Example:
local num = component:PlayEffect("text")local num = component:PlayEffect("text", "text", other_entity, { ... }, 1)
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.
- Argument 1: Effect ID (string)
- Argument 2: Socket name (OPTIONAL) (string)
- Argument 3: Target entity (only for non-looping effects) (OPTIONAL) (entity)
- Argument 4: Particle effect parameter table (only for non-looping effects) (OPTIONAL) (table)
- Argument 5: Render instance number on target if set otherwise on source (OPTIONAL) (integer)
Example:
component:PlayWorkEffect("text")component:PlayWorkEffect("text", "text", other_entity, { ... }, 1)
StopEffects (Component Function)
Stop all looping effects playing on this component
Example:
component:StopEffects()
SetWorkAnimationSpeed (Component Function)
Sets animation speed multiplied by the components current power efficiency
- Argument 1: New animation speed to be multiplied (OPTIONAL, default 1) (number)
Example:
component:SetWorkAnimationSpeed()component:SetWorkAnimationSpeed(1)
Component Variables
owner (Component Variable)
The owner of this component
Value: Owner entity (entity)
Access: read only
Example:
local some_entity = component.owner
faction (Component Variable)
The faction of the owner of this component
Value: Faction object (faction)
Access: read only
Example:
local some_faction = component.faction
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:
local flag = component.exists
key (Component Variable)
A unique numerical identifier of this component
Value: key (integer)
Access: read only
Example:
local num = component.key
id (Component Variable)
The id of this component
Value: Component id (component-id-string)
Access: read only
Example:
local component_id = component.id
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:
local component_id = component.base_id
def (Component Variable)
The definition table of this component
Value: Component definition (table)
Access: read only
Example:
local tbl = component.def
visual_id (Component Variable)
The visual id of this component
Value: visual id (visual-id-string)
Access: read only
Example:
local visual_id = component.visual_id
visual_def (Component Variable)
The visual definition table of this component
Value: visual definition table (table)
Access: read only
Example:
local tbl = component.visual_def
socket_index (Component Variable)
The socket index this component is attached to
Value: Socket index (or 0 if hidden) (integer)
Access: read only
Example:
local num = component.socket_index
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:
local num = component.slot_index
slot_count (Component Variable)
Check the number of item slots a component has
Value: Number of slots (integer)
Access: read only
Example:
local num = component.slot_count
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:
local tbl = component.slots
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:
local num = component.register_index
register_count (Component Variable)
Check or change the number of registers a component has
Value: Number of registers (integer)
Access: read & write
Example:
local num = component.register_countcomponent.register_count = 1
is_empty (Component Variable)
Returns if the component has no items stored in it
Value: Empty state (boolean)
Access: read only
Example:
local flag = component.is_empty
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:
local flag = component.is_hidden
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:
local flag = component.is_active
is_working (Component Variable)
Returns if the component is still working on something started with SetStateStartWork
Value: Working state (boolean)
Access: read only
Example:
local flag = component.is_working
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:
local flag = component.is_sleeping
is_updating (Component Variable)
Returns if the component currently executing the on_update callback
Value: Updating state (boolean)
Access: read only
Example:
local flag = component.is_updating
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:
local flag = component.has_move_control
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:
local flag = component.has_prepared_process
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:
local num = component.progress_percent
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:
local num = component.interpolated_progress
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:
local num = component.ticker
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:
local num = component.ticker_target
has_extra_data (Component Variable)
Check if extra_data has been created for this component
Value: Result (boolean)
Access: read only
Example:
local flag = component.has_extra_data
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:
local tbl = component.extra_datacomponent.extra_data = { ... }
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:
local num = component.stored_powercomponent.stored_power = 1
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:
local num = component.extra_powercomponent.extra_power = 1
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:
local num = component.extra_transfer_rangecomponent.extra_transfer_range = 1
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:
local some_entity = component.power_relay_targetcomponent.power_relay_target = other_entity
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:
local tbl = component.power_details
animation_speed (Component Variable)
Set Material animation speed if supported by the visual
Value: Speed (number)
Access: read & write
Example:
local num = component.animation_speedcomponent.animation_speed = 1
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:
local col = component.light_colorcomponent.light_color = { 1, 0, 0 }
has_active_effects (Component Variable)
Check if there are any looping effects playing on this component
Value: Result (boolean)
Access: read only
Example:
local flag = component.has_active_effects
triggering_entities (Component Variable)
Get an array with all matching entities inside this components trigger_radius
Value: Entity array (table)
Access: read only
Example:
local tbl = component.triggering_entities
Component Operators
ToString Operator (Component Operator)
Example:
local string_of_component = tostring(component)
Equality Operator (Component Operator)
Example:
local is_same = component_a == component_blocal is_different = component_a =~ component_b
Meta Table: Entity
An entity object represents a single entity that can be placed in the world.
Source: /Source/Desynced/Lua/Meta/DSEntityLuaMeta.cpp
- Functions
- Place
- Unplace
- Destroy
- AddComponent
- GetComponent
- SwapSockets
- GetHiddenComponent
- CountComponents
- FindComponent
- GetFreeSocket
- CheckSocketSize
- GetRegisterLinks
- GetRegister
- GetRegisterNum
- GetRegisterId
- GetRegisterDef
- GetRegisterEntity
- GetRegisterCoord
- RegistersEqual
- SetRegister
- SetRegisterNum
- SetRegisterId
- SetRegisterEntity
- SetRegisterCoord
- FlagRegisterError
- RegisterIsLink
- RegisterIsEmpty
- RegisterIsError
- RegisterHasConnection
- LinkRegisterFromRegister
- UnlinkRegisterFromRegister
- GetRegisterLinkSource
- GetRegisterLinkTarget
- HaveRegisterQueue
- RegisterQueueLength
- RegisterQueueGet
- RegisterQueueGetAll
- RegisterQueueSet
- RegisterQueueInsert
- RegisterQueueRemove
- AddItem
- CountItem
- HaveFreeSpace
- CountFreeSpace
- GetFreeSlot
- GetSlot
- FindSlot
- AddSlots
- AutoMergeSlots
- IsWaitingForOrder
- TransferFrom
- DropItem
- DropComponent
- OrderItem
- GetLocationXY
- EstimateLocationInTicks
- MoveTo
- MoveAway
- Cancel
- LookAt
- IsTouching
- IsInRangeOf
- GetRangeTo
- GetRangeSquaredTo
- IssueDumpingOrders
- DockInto
- Undock
- RemoveEntityInstance
- PlayEffect
- StopEffects
- StopEffect
- Activate
- Deactivate
- GetSizeAtRotation
- SetVisual
- MatchFilter
- ExistsOnFaction
- AddHealth
- RemoveHealth
- Variables
- key
- id
- def
- visual_id
- visual_def
- components
- slots
- has_extra_data
- extra_data
- faction
- visibility_range
- component_boost
- move_boost
- max_health
- health
- is_damaged
- exists
- efficiency
- power_grid_index
- has_power
- extra_power
- extra_transfer_range
- power_range
- power_details
- battery_percent
- battery_stored
- battery_total
- animation_speed
- light_color
- location
- placed_location
- location_hash
- size
- area
- rotation
- move_goal
- is_moving
- has_movement
- is_placed
- is_on_map
- is_docked
- is_docked_on_map
- docked_garage
- reserved_redock_entity
- disconnected
- powered_down
- stealth
- lootable
- has_blight_shield
- has_landing_pad
- logistics_channel_1
- logistics_channel_2
- logistics_channel_3
- logistics_channel_4
- logistics_supplier
- logistics_requester
- logistics_carrier
- logistics_crane_only
- logistics_flying_only
- logistics_can_construction
- logistics_transport_route
- logistics_high_priority
- has_crane
- crane_range
- is_construction
- state_idle
- state_path_blocked
- state_inefficient
- state_unpowered
- state_emergency
- state_broken
- state_custom_1
- state_custom_2
- state_custom_3
- state_custom_4
- idle_mode
- controlling_component
- active_order
- has_component_list
- component_count
- socket_count
- slot_count
- register_count
- frame_register_count
- most_relevant_state
- all_states
- render_instances
- has_active_effects
- idle_ticks
- triggered_components
- interpolated_location
- interpolated_center
- interpolated_rotation
- interpolated_direction
- Operators
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
- Argument 1: Location X (integer)
- Argument 2: Location Y (integer)
- Argument 3: Rotation (0 to 3) (OPTIONAL) (integer)
- Argument 4: Entity for a bot to come out of (cannot be passed together with rotation) (OPTIONAL) (entity)
- Argument 5: Place nearby if blocking (OPTIONAL, default true) (boolean)
--- or --- - Argument 1: Location (coordinate)
- Argument 2: Rotation (0 to 3) (OPTIONAL) (integer)
- Argument 3: Entity for a bot to come out of (cannot be passed together with rotation) (OPTIONAL) (entity)
- Argument 4: Place nearby if blocking (OPTIONAL, default true) (boolean)
- Return Value: Returns boolean false if failed to place, otherwise nil (boolean)
Example:
local flag = entity:Place(1, 1)local flag = entity:Place(1, 1, 1, other_entity, true)local flag = entity:Place({ x = 1, y = 2 })local flag = entity:Place({ x = 1, y = 2 }, 1, other_entity, true)
Unplace (Entity Function)
Remove this entity from the map
Example:
entity:Unplace()
Destroy (Entity Function)
Destroy this entity
Can automatically drop all components and inventory items held by it, as well as additional items
- Argument 1: Flag if items and components held by this entity should be dropped (OPTIONAL, default true) (boolean)
- Argument 2: Table of additional items that drop (item_id keys and count values) (OPTIONAL) (table)
- Argument 3: If set, try to store items in this entities inventory instead of dropping them to the ground (OPTIONAL) (entity)
Example:
entity:Destroy()entity:Destroy(true, { ... }, other_entity)
AddComponent (Entity Function)
Create and add a new component
- Argument 1: Component id (string)
- Argument 2: Add mode ("auto" will find a suitable socket, "hidden" will add the component hidden) (OPTIONAL, default "auto") (string)
- Argument 3: Extra data table (OPTIONAL, default nil) (table)
--- or --- - Argument 1: Component id (string)
- Argument 2: Socket index to place the component (starts at 1) (integer)
- Argument 3: Extra data table (OPTIONAL, default nil) (table)
- Return Value: Component object (or nil on error) (component)
Example:
local some_component = entity:AddComponent("text")local some_component = entity:AddComponent("text", "text", { ... })local some_component = entity:AddComponent("text", 1)local some_component = entity:AddComponent("text", 1, { ... })
GetComponent (Entity Function)
Get an existing component at a specific socket index
- Argument 1: Socket index (starts at 1) (integer)
- Return Value: Component object or nil if not exist (component)
Example:
local some_component = entity:GetComponent(1)
SwapSockets (Entity Function)
Swap the content of two sockets
One or both sockets must contain a component which must fit into the other socket
- Argument 1: First socket index (integer)
- Argument 2: Second socket index (integer)
- Return Value: If it was successful (boolean)
Example:
local flag = entity:SwapSockets(1, 1)
GetHiddenComponent (Entity Function)
Get an existing hidden component
- Argument 1: Hidden component number (starts at 1) (OPTIONAL, default 1) (integer)
- Return Value: Component object or nil if not exist (component)
Example:
local some_component = entity:GetHiddenComponent()local some_component = entity:GetHiddenComponent(1)
CountComponents (Entity Function)
Count the components of the same type on an entity
- Argument 1: Component id (string)
- Argument 2: Set to true to query the base_id value of component definitions if it exists (OPTIONAL, default false) (boolean)
- Return Value: Number of the components (integer)
Example:
local num = entity:CountComponents("text")local num = entity:CountComponents("text", true)
FindComponent (Entity Function)
Find an existing component
- Argument 1: Component id (string)
- Argument 2: Set to true to query the base_id value of component definitions if it exists (OPTIONAL, default false) (boolean)
- Argument 3: Component number (if there are multiples of the same component) (OPTIONAL, default 1) (integer)
- Return Value: Component object or nil if not found (component)
Example:
local some_component = entity:FindComponent("text")local some_component = entity:FindComponent("text", true, 1)
GetFreeSocket (Entity Function)
Check if a free socket of large enough size is available to equip a component
- Argument 1: Component id (string)
- Return Value: Socket index it can be equipped into or nil if not possible (or if passed id is not a component) (integer)
Example:
local num = entity:GetFreeSocket("text")
CheckSocketSize (Entity Function)
Test if a component fits into a socket (regardless if there is already something equipped in the socket)
- Argument 1: Component id (string)
- Argument 2: Socket index to test the component against (starts at 1) (integer)
- Return Value: True if the socket is large enough to hold the component (boolean)
Example:
local flag = entity:CheckSocketSize("text", 1)
GetRegisterLinks (Entity Function)
Get a list of links on the entity
- Argument 1: Also return cross-entity links (OPTIONAL, default false) (boolean)
- Return Value: Array of links (table)
Example:
local tbl = entity:GetRegisterLinks()local tbl = entity:GetRegisterLinks(true)
GetRegister (Entity Function)
Get a register of this entity
- Argument 1: Register reference (register reference)
- Return Value: Register object (register)
Example:
local reg = entity:GetRegister(1)
GetRegisterNum (Entity Function)
Get the number part of a register of this entity
- Argument 1: Register reference (register reference)
- Return Value: Number value (integer)
Example:
local num = entity:GetRegisterNum(1)
GetRegisterId (Entity Function)
Get the id part of a register of this entity
- Argument 1: Register reference (register reference)
- Return Value: Id value (id-string)
Example:
local id = entity:GetRegisterId(1)
GetRegisterDef (Entity Function)
Get the definition table of the id stored in a register of this entity
- Argument 1: Register reference (register reference)
- Return Value: Definition table (table)
Example:
local tbl = entity:GetRegisterDef(1)
GetRegisterEntity (Entity Function)
Get the entity part of a register of this entity
- Argument 1: Register reference (register reference)
- Return Value: Entity value (entity)
Example:
local some_entity = entity:GetRegisterEntity(1)
GetRegisterCoord (Entity Function)
Get the coordinate part of a register of this entity
- Argument 1: Register reference (register reference)
- Return Value: Coordinate value (coordinate)
Example:
local pos = entity:GetRegisterCoord(1)
RegistersEqual (Entity Function)
Compare two registers of this entity
- Argument 1: First register reference (register reference)
- Argument 2: Second register reference (register reference)
- Return Value: Comparison result (boolean)
Example:
local flag = entity:RegistersEqual(1, 1)
SetRegister (Entity Function)
Set a register of this entity
- Argument 1: Register reference (register reference)
- Argument 2: Register object or table (or nil to clear a register) (register)
- Argument 3: Force update the register and activate components (OPTIONAL, default false) (boolean)
Example:
entity:SetRegister(1, { num = 10, id = "id" })entity:SetRegister(1, { num = 10, id = "id" }, true)
SetRegisterNum (Entity Function)
Set the number part of a register of this entity
- Argument 1: Register reference (register reference)
- Argument 2: Number value (integer)
Example:
entity:SetRegisterNum(1, 1)
SetRegisterId (Entity Function)
Set the id part of a register of this entity (will overwrites the entity/coordinate part)
- Argument 1: Register reference (register reference)
- Argument 2: Id value (or nil to clear the id part) (string)
- Argument 3: Number value (OPTIONAL) (integer)
Example:
entity:SetRegisterId(1)entity:SetRegisterId(1, "text", 1)
SetRegisterEntity (Entity Function)
Set the entity part of a register of this entity (will overwrite the id/coordinate part)
- Argument 1: Register reference (register reference)
- Argument 2: Entity value (or nil to clear the entity part) (entity)
- Argument 3: Number value (OPTIONAL) (integer)
Example:
entity:SetRegisterEntity(1)entity:SetRegisterEntity(1, other_entity, 1)
SetRegisterCoord (Entity Function)
Set the coordinate part of a register of this entity (will overwrite the id/entity part)
- Argument 1: Register reference (register reference)
- Argument 2: Coordinate value (or nil to clear the coordinate part) (coordinate)
- Argument 3: Number value (OPTIONAL) (integer)
Example:
entity:SetRegisterCoord(1)entity:SetRegisterCoord(1, { x = 1, y = 2 }, 1)
FlagRegisterError (Entity Function)
Flag the error state on a register of this entity
Will stay flagged until the register value changes.
- Argument 1: Register reference (register reference)
- Argument 2: Whether to set the error state (OPTIONAL, default true) (boolean)
Example:
entity:FlagRegisterError(1)entity:FlagRegisterError(1, true)
RegisterIsLink (Entity Function)
Check if a register of this entity is linked from another register
- Argument 1: Register reference (register reference)
- Return Value: Link state (boolean)
Example:
local flag = entity:RegisterIsLink(1)
RegisterIsEmpty (Entity Function)
Check if a register of this entity is empty
- Argument 1: Register reference (register reference)
- Return Value: Empty state (boolean)
Example:
local flag = entity:RegisterIsEmpty(1)
RegisterIsError (Entity Function)
Check if a register of this entity is in error state
- Argument 1: Register reference (register reference)
- Return Value: Error state (boolean)
Example:
local flag = entity:RegisterIsError(1)
RegisterHasConnection (Entity Function)
Check if two registers have a connection via link(s)
- Argument 1: Register one (register reference)
- Argument 2: Register two (register reference)
- Argument 3: Different entity that holds the second register (OPTIONAL) (entity)
--- or --- - Argument 1: Register one (register reference)
- Argument 2: Register two (register reference)
- Argument 3: A component that holds the second register (component)
- Return Value: Check result (boolean)
Example:
local flag = entity:RegisterHasConnection(1, 1)local flag = entity:RegisterHasConnection(1, 1, other_entity)local flag = entity:RegisterHasConnection(1, 1, comp)
LinkRegisterFromRegister (Entity Function)
Link a register from another register
- Argument 1: Target register reference (register reference)
- Argument 2: Source register reference (register reference)
- Argument 3: Different entity that holds the source register (OPTIONAL) (entity)
--- or --- - Argument 1: Target register reference (register reference)
- Argument 2: Source register reference (register reference)
- Argument 3: A component that holds the source register (component)
Example:
entity:LinkRegisterFromRegister(1, 1)entity:LinkRegisterFromRegister(1, 1, other_entity)entity:LinkRegisterFromRegister(1, 1, comp)
UnlinkRegisterFromRegister (Entity Function)
Unlink a register from another register
- Argument 1: Target register reference (register reference)
- Argument 2: Source register reference (register reference)
- Argument 3: Different entity that holds the source register (OPTIONAL) (entity)
--- or --- - Argument 1: Target register reference (register reference)
- Argument 2: Source register reference (register reference)
- Argument 3: A component that holds the source register (component)
Example:
entity:UnlinkRegisterFromRegister(1, 1)entity:UnlinkRegisterFromRegister(1, 1, other_entity)entity:UnlinkRegisterFromRegister(1, 1, comp)
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.
- Argument 1: Target register reference (register reference)
--- or --- - Argument 1: Target register reference (register reference)
- Argument 2: Entity that holds the source register (entity)
--- or --- - Argument 1: Target register reference (register reference)
- Argument 2: Component that holds the source register (component)
- Return Value: Source register index, absolute entity index unless a source component is specified (or nil if not exist) (integer)
- Return Value: Entity that holds the source register (unless entity/component specified) (entity)
- Return Value: Component that holds the source register or nil if frame register (unless entity/component specified) (component)
Example:
local num, some_entity, some_component = entity:GetRegisterLinkSource(1)local num, some_entity, some_component = entity:GetRegisterLinkSource(1, other_entity)local num, some_entity, some_component = entity:GetRegisterLinkSource(1, comp)
GetRegisterLinkTarget (Entity Function)
Get the target index of the first relevant register link
- Argument 1: Source register reference (register reference)
- Argument 2: Different entity that holds the source register (OPTIONAL) (entity)
--- or --- - Argument 1: Source register reference (register reference)
- Argument 2: A component that holds the source register (component)
- Return Value: Target register index, absolute entity index (or nil if not exist) (integer)
Example:
local num = entity:GetRegisterLinkTarget(1)local num = entity:GetRegisterLinkTarget(1, other_entity)local num = entity:GetRegisterLinkTarget(1, comp)
HaveRegisterQueue (Entity Function)
Check if a register of this entity has a queue (2 or more elements)
- Argument 1: Register reference (register reference)
- Return Value: Queue has 2 or more elements (boolean)
Example:
local flag = entity:HaveRegisterQueue(1)
RegisterQueueLength (Entity Function)
Count the number of queued elements
- Argument 1: Register reference (register reference)
- Return Value: Queue length (having nothing queued returns 1, register with links returns 0) (integer)
Example:
local num = entity:RegisterQueueLength(1)
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.
- Argument 1: Register reference (register reference)
- Argument 2: Queue index (OPTIONAL, default to last) (integer)
- Return Value: Register object (or nil if invalid index) (register)
Example:
local reg = entity:RegisterQueueGet(1)local reg = entity:RegisterQueueGet(1, 1)
RegisterQueueGetAll (Entity Function)
Get the entire queue as an array
- Argument 1: Register reference (register reference)
- Return Value: An array of register values of the same length as
RegisterQueueLength(table)
Example:
local tbl = entity:RegisterQueueGetAll(1)
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).
- Argument 1: Register reference (register reference)
- Argument 2: Register object or table (register)
- Argument 3: Queue index (OPTIONAL, default to last) (integer)
Example:
entity:RegisterQueueSet(1, { num = 10, id = "id" })entity:RegisterQueueSet(1, { num = 10, id = "id" }, 1)
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).
- Argument 1: Register reference (register reference)
- Argument 2: Register object or table (register)
- Argument 3: Insertion index (OPTIONAL, default to appending to the end) (integer)
Example:
entity:RegisterQueueInsert(1, { num = 10, id = "id" })entity:RegisterQueueInsert(1, { num = 10, id = "id" }, 1)
RegisterQueueRemove (Entity Function)
Remove a queued element
- Argument 1: Register reference (register reference)
- Argument 2: Queue index (OPTIONAL, default to last) (integer)
- Return Value: Removed register object (or nil if invalid index) (register)
Example:
local reg = entity:RegisterQueueRemove(1)local reg = entity:RegisterQueueRemove(1, 1)
AddItem (Entity Function)
Add an item to the inventory
- Argument 1: Item id (string)
- Argument 2: Amount (OPTIONAL, default 1) (integer)
- Argument 3: Set to true to count this as item generation in the history graph (OPTIONAL, default false) (boolean)
- Argument 4: Extra data table (OPTIONAL, default nil) (table)
- Return Value: First item slot object into which the item has been added (or nil on error) (itemslot)
- Return Value: Actual amount of items that have been added (integer)
Example:
local some_slot, num = entity:AddItem("text")local some_slot, num = entity:AddItem("text", 1, true, { ... })
CountItem (Entity Function)
Count (unreserved) stacks of an item across all item slots
- Argument 1: Item id (string)
- Argument 2: Count unreserved, if true it will only count unreserved stack amounts (OPTIONAL, default false) (boolean)
- Return Value: Item count (integer)
Example:
local num = entity:CountItem("text")local num = entity:CountItem("text", true)
HaveFreeSpace (Entity Function)
Check if there is any free space to add the item in any item slots
- Argument 1: Item id (string)
- Argument 2: Count of item (OPTIONAL, default 1) (integer)
- Return Value: Can items be added (or nil if the entity has no inventory or the item id is invalid) (boolean)
Example:
local flag = entity:HaveFreeSpace("text")local flag = entity:HaveFreeSpace("text", 1)
CountFreeSpace (Entity Function)
Count how much free space for an item in any item slots
- Argument 1: Item id (string)
- Return Value: Number of available Space (or nil if item id is nil) (integer)
Example:
local num = entity:CountFreeSpace("text")
GetFreeSlot (Entity Function)
Find an item slot with enough free space to store a given amount
- Argument 1: Item id (string)
- Argument 2: Amount to search (OPTIONAL, default max stack size) (integer)
- Return Value: Item slot object with the space available (or nil if there is none) (itemslot)
Example:
local some_slot = entity:GetFreeSlot("text")local some_slot = entity:GetFreeSlot("text", 1)
GetSlot (Entity Function)
Get a single item slot at a specific slot index
- Argument 1: Slot index (starts at 1) (integer)
- Return Value: Item slot object or nil if not exist (itemslot)
Example:
local some_slot = entity:GetSlot(1)
FindSlot (Entity Function)
Find an item slot with a specific item
- Argument 1: Item id (string)
- Argument 2: Limit search to slot with at least this amount of unreserved stack in it (OPTIONAL) (integer)
- Return Value: Item slot object or nil if not found (itemslot)
Example:
local some_slot = entity:FindSlot("text")local some_slot = entity:FindSlot("text", 1)
AddSlots (Entity Function)
Add inventory slots
- Argument 1: Slot type (string)
- Argument 2: Number of slots to add (OPTIONAL, default 1) (integer)
- Return Value: Item slot object of the first newly created slot (or nil on error) (itemslot)
Example:
local some_slot = entity:AddSlots("text")local some_slot = entity:AddSlots("text", 1)
AutoMergeSlots (Entity Function)
Automatically merge stacks of the same item across the inventory
- Argument 1: Limit merging to just one this one item id (OPTIONAL) (string)
- Return Value: Number of inventory slots that became empty due to the merge (integer)
Example:
local num = entity:AutoMergeSlots()local num = entity:AutoMergeSlots("text")
IsWaitingForOrder (Entity Function)
Check if the entity is waiting for an order of a specific item
- Argument 1: Item id (string)
- Argument 2: Return true only if there is an order without a carrier assigned (OPTIONAL, default false) (boolean)
- Return Value: Has item on order (boolean)
Example:
local flag = entity:IsWaitingForOrder("text")local flag = entity:IsWaitingForOrder("text", true)
TransferFrom (Entity Function)
Transfer an item from the inventory of another entity
- Argument 1: Item source entity (entity)
- Argument 2: Item id (string)
- Argument 3: Amount (integer)
- Argument 4: Show the visual item throw effect (OPTIONAL, default false) (boolean)
- Argument 5: Should attempt to auto equip a component if inventory is full (OPTIONAL, default false) (boolean)
- Return Value: Amount actually transferred (can be 0 if there is no free space) (or nil on error) (integer)
Example:
local num = entity:TransferFrom(other_entity, "text", 1)local num = entity:TransferFrom(other_entity, "text", 1, true, true)
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.
- Argument 1: Item id (string)
- Argument 2: Amount (OPTIONAL, default to everything available of that item id) (integer)
- Argument 3: X coordinate of drop target (OPTIONAL) (integer)
- Argument 4: Y coordinate of drop target (OPTIONAL) (integer)
--- or --- - Argument 1: Item slot (itemslot)
- Argument 2: Amount (OPTIONAL, default to everything available in given item slot) (integer)
- Argument 3: X coordinate of drop target (OPTIONAL) (integer)
- Argument 4: Y coordinate of drop target (OPTIONAL) (integer)
Example:
entity:DropItem("text")entity:DropItem("text", 1, 1, 1)entity:DropItem(item_slot)entity:DropItem(item_slot, 1, 1, 1)
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.
- Argument 1: Component to drop (component)
- Argument 2: X coordinate of drop target (integer)
- Argument 3: Y coordinate of drop target (integer)
Example:
entity:DropComponent(comp, 1, 1)
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.
- Argument 1: Item id to be ordered (string)
- Argument 2: Amount to be ordered (integer)
- Argument 3: Mode "None", "HighPriority", "ManualOrder", "Recurring", "ManualOrder|Recurring" (OPTIONAL, default "None") (string)
- Argument 4: If set and not 0, make the order on the channels denoted by the set bits (OPTIONAL) (integer)
- Return Value: Order ID created or modified (integer)
Example:
local num = entity:OrderItem("text", 1)local num = entity:OrderItem("text", 1, "text", 1)
GetLocationXY (Entity Function)
Get the location of this entity. Same as location but returns 2 integers instead of a table.
- Return Value: X coordinate (integer)
- Return Value: Y coordinate (integer)
Example:
local num, num = entity:GetLocationXY()
EstimateLocationInTicks (Entity Function)
Estimate the location of this entity in the future, only different from location when moving.
- Argument 1: How many ticks in the future to estimate for (integer)
- Return Value: X coordinate (integer)
- Return Value: Y coordinate (integer)
Example:
local num, num = entity:EstimateLocationInTicks(1)
MoveTo (Entity Function)
Start moving the entity to a given location
- Argument 1: Target entity to move next to (entity)
- Argument 2: Range of how close by to stop (OPTIONAL, default 1) (integer)
--- or --- - Argument 1: Location or area to move away from (area, coordinate or entity)
- Argument 2: Range of how close by to stop (OPTIONAL, default 0) (integer)
Example:
entity:MoveTo(other_entity)entity:MoveTo(other_entity, 1)entity:MoveTo(entity OR [ x, y ] OR [ x, y, w, h ])entity:MoveTo(entity OR [ x, y ] OR [ x, y, w, h ], 1)
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.
- Argument 1: Location or area to move away from (area, coordinate or entity)
Example:
entity:MoveAway(entity OR [ x, y ] OR [ x, y, w, h ])
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:
entity:Cancel()
LookAt (Entity Function)
Rotate the entity to look towards a given location
- Argument 1: Location (area, coordinate or entity)
Example:
entity:LookAt(entity OR [ x, y ] OR [ x, y, w, h ])
IsTouching (Entity Function)
Check if the entity is touching another entity or a location
- Argument 1: Location (area, coordinate or entity)
- Return Value: True if located next to other entity/location (boolean)
Example:
local flag = entity:IsTouching(entity OR [ x, y ] OR [ x, y, w, h ])
IsInRangeOf (Entity Function)
Check if the entity is in range of another entity or a location
- Argument 1: Location (area, coordinate or entity)
- Argument 2: Range to test (if 1 will act like IsTouching) (integer)
- Return Value: True if in range of other entity/location (boolean)
Example:
local flag = entity:IsInRangeOf(entity OR [ x, y ] OR [ x, y, w, h ], 1)
GetRangeTo (Entity Function)
Measure the range in tiles to another entity or a location
- Argument 1: Location (area, coordinate or entity)
- Return Value: Distance in number of tiles (integer)
Example:
local num = entity:GetRangeTo(entity OR [ x, y ] OR [ x, y, w, h ])
GetRangeSquaredTo (Entity Function)
Get the squared distance to another entity or a location
- Argument 1: Location (area, coordinate or entity)
- Return Value: Squared distance (integer)
Example:
local num = entity:GetRangeSquaredTo(entity OR [ x, y ] OR [ x, y, w, h ])
IssueDumpingOrders (Entity Function)
Request Inventory to be dumped into nearest storage
Example:
entity:IssueDumpingOrders()
DockInto (Entity Function)
Dock this entity into an item slot of another entity
- Argument 1: Garage entity to dock into (entity)
- Return Value: True if docking succeeded, false if garage was full (or nil on error) (boolean)
Example:
local flag = entity:DockInto(other_entity)
Undock (Entity Function)
Undock this entity
- Argument 1: If true, reserve the item slot for this entity to come back later (OPTIONAL, default false) (boolean)
- Argument 2: If false, don't place the entity on the map after undocking (OPTIONAL, default true) (boolean)
- Return Value: True if undocking succeeded (or nil on error) (boolean)
Example:
local flag = entity:Undock()local flag = entity:Undock(true, true)
RemoveEntityInstance (Entity Function)
removes an instance from the entity
Example:
entity:RemoveEntityInstance()
PlayEffect (Entity Function)
Spawn particle/sound effect on this entity
- Argument 1: Effect ID (string)
- Argument 2: Socket name (OPTIONAL) (string)
- Argument 3: Target entity (only for non-looping effects) (OPTIONAL) (entity)
- Argument 4: Particle effect parameter table (only for non-looping effects) (OPTIONAL) (table)
- Argument 5: Render instance number on target if set otherwise on source (OPTIONAL) (integer)
- Return Value: Effect instance (only for looping effects, can be used with
entity:StopEffect) (integer)
Example:
local num = entity:PlayEffect("text")local num = entity:PlayEffect("text", "text", other_entity, { ... }, 1)
StopEffects (Entity Function)
Stop all looping particle/sound effects
Example:
entity:StopEffects()
StopEffect (Entity Function)
Stop a specific looping particle/sound effect
- Argument 1: Effect Instance (integer)
Example:
entity:StopEffect(1)
Activate (Entity Function)
Activate event of the visuals frame blueprint
Example:
entity:Activate()
Deactivate (Entity Function)
Deactivate event of the visuals frame blueprint
Example:
entity:Deactivate()
GetSizeAtRotation (Entity Function)
Get the size this entity would have at a given rotation
- Argument 1: Rotation (0 to 3) (integer)
- Return Value: Size width (integer)
- Return Value: Size height (integer)
Example:
local num, num = entity:GetSizeAtRotation(1)
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.
- Argument 1: Visual id (string)
- Argument 2: Rotation (0 to 3) (OPTIONAL) (integer)
- Return Value: Result (boolean)
Example:
local flag = entity:SetVisual("text")local flag = entity:SetVisual("text", 1)
MatchFilter (Entity Function)
Check if this entity matches an entity filter
- Argument 1: Filter by frame type (FF_FOUNDATION, FF_WALL, FF_GATE, FF_DROPPEDITEM, FF_CONSTRUCTION, FF_RESOURCE, FF_OPERATING) or faction (FF_OWNFACTION, FF_ENEMYFACTION, FF_NEUTRALFACTION, FF_ALLYFACTION, FF_WORLDFACTION) (OPTIONAL, default FF_ALL) (integer)
- Argument 2: The faction that is considered self with regards to faction filters passed to the previous argument (must be passed for faction filters) (faction)
- Return Value: True if the entity matches the filter (boolean)
Example:
local flag = entity:MatchFilter()local flag = entity:MatchFilter(1, world_faction)
ExistsOnFaction (Entity Function)
Check if this entity still exists and is owned by a given faction
- Argument 1: Faction or faction id to check (faction)
- Return Value: Result (boolean)
Example:
local flag = entity:ExistsOnFaction("faction_id")
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)
- Argument 1: Add amount (integer)
- Return Value: New health amount on entity (integer)
Example:
local num = entity:AddHealth(1)
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)
- Argument 1: Remove amount (integer)
- Argument 2: Which entity caused the damage (OPTIONAL) (entity)
- Argument 3: type of damage to remove (OPTIONAL) (string)
- Return Value: New health amount on entity (0 if destroyed) (integer)
Example:
local num = entity:RemoveHealth(1)local num = entity:RemoveHealth(1, other_entity, "text")
Entity Variables
key (Entity Variable)
A unique numerical identifier of this entity
Value: key (integer)
Access: read only
Example:
local num = entity.key
id (Entity Variable)
The frame id of this entity
Value: frame id (frame-id-string)
Access: read only
Example:
local frame_id = entity.id
def (Entity Variable)
The frame definition table of this entity
Value: frame definition table (table)
Access: read only
Example:
local tbl = entity.def
visual_id (Entity Variable)
The visual id of this entity
Value: visual id (visual-id-string)
Access: read only
Example:
local visual_id = entity.visual_id
visual_def (Entity Variable)
The visual definition table of this entity
Value: visual definition table (table)
Access: read only
Example:
local tbl = entity.visual_def
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:
local tbl = entity.components
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:
local tbl = entity.slots
has_extra_data (Entity Variable)
Check if extra_data has been created for this entity
Value: Result (boolean)
Access: read only
Example:
local flag = entity.has_extra_data
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:
local tbl = entity.extra_dataentity.extra_data = { ... }
faction (Entity Variable)
The faction of this entity
Value: Faction object (faction)
Access: read & write
Example:
local some_faction = entity.factionentity.faction = "faction_id"
visibility_range (Entity Variable)
The visibility range of this entity
Must be between 0 and 255
Value: Visibility range (integer)
Access: read & write
Example:
local num = entity.visibility_rangeentity.visibility_range = 1
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:
local num = entity.component_boostentity.component_boost = 1
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:
local num = entity.move_boostentity.move_boost = 1
max_health (Entity Variable)
The maximum health of this entity
Must be between 1 and 65535
Value: Maximum health (integer)
Access: read & write
Example:
local num = entity.max_healthentity.max_health = 1
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:
local num = entity.healthentity.health = 1
is_damaged (Entity Variable)
Check if the entity is not at max health
Value: Damaged state (boolean)
Access: read only
Example:
local flag = entity.is_damaged
exists (Entity Variable)
Check if this entity still exists or if it was destroyed
Value: Exist state (boolean)
Access: read only
Example:
local flag = entity.exists
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:
local num = entity.efficiency
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:
local num = entity.power_grid_index
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:
local flag = entity.has_power
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:
local num = entity.extra_powerentity.extra_power = 1
extra_transfer_range (Entity Variable)
The dynamic extra power range of this entity
Value: Extra power range in tiles (integer)
Access: read & write
Example:
local num = entity.extra_transfer_rangeentity.extra_transfer_range = 1
power_range (Entity Variable)
The power range of this entity
Value: power range (integer)
Access: read only
Example:
local num = entity.power_range
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:
local tbl = entity.power_details
battery_percent (Entity Variable)
Get a percent number how full all equipped batteries are
Value: Percentage 0 to 100 (integer)
Access: read only
Example:
local num = entity.battery_percent
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:
local num = entity.battery_stored
battery_total (Entity Variable)
Get the summed up total capacity of all equipped batteries
Value: Stored power amount (integer)
Access: read only
Example:
local num = entity.battery_total
animation_speed (Entity Variable)
Material animation speed if supported by the visual
Value: animation speed (integer)
Access: read & write
Example:
local num = entity.animation_speedentity.animation_speed = 1
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:
local col = entity.light_colorentity.light_color = { 1, 0, 0 }
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:
local pos = entity.location
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:
local pos = entity.placed_location
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:
local num = entity.location_hash
size (Entity Variable)
The tile size of this entity
Value: Size (coordinate)
Access: read only
Example:
local pos = entity.size
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:
local x, y, w, h = entity.area
rotation (Entity Variable)
The rotation of this entity
Value: Rotation (0 to 3) (integer)
Access: read only
Example:
local num = entity.rotation
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:
local pos = entity.move_goal
is_moving (Entity Variable)
Check if the entity is moving
Value: Movement state (boolean)
Access: read only
Example:
local flag = entity.is_moving
has_movement (Entity Variable)
Check if this entity has movement
Value: True if the entity has movement (boolean)
Access: read only
Example:
local flag = entity.has_movement
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:
local flag = entity.is_placed
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:
local flag = entity.is_on_map
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:
local flag = entity.is_docked
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:
local flag = entity.is_docked_on_map
docked_garage (Entity Variable)
The garage this entity is docked in
Value: Garage entity (nil if not docked) (entity)
Access: read only
Example:
local some_entity = entity.docked_garage
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:
local some_entity = entity.reserved_redock_entity
disconnected (Entity Variable)
Disconnected from logistics network state of this entity
Value: Disconnected state (boolean)
Access: read & write
Example:
local flag = entity.disconnectedentity.disconnected = true
powered_down (Entity Variable)
Controls the power down state of an entity.
Value: Power down state (boolean)
Access: read & write
Example:
local flag = entity.powered_downentity.powered_down = true
stealth (Entity Variable)
Controls the stealth effect of an entity.
Value: Stealth state (boolean)
Access: read & write
Example:
local flag = entity.stealthentity.stealth = true
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:
local flag = entity.lootableentity.lootable = true
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:
local flag = entity.has_blight_shieldentity.has_blight_shield = true
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:
local flag = entity.has_landing_padentity.has_landing_pad = true
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:
local flag = entity.logistics_channel_1entity.logistics_channel_1 = true
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:
local flag = entity.logistics_channel_2entity.logistics_channel_2 = true
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:
local flag = entity.logistics_channel_3entity.logistics_channel_3 = true
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:
local flag = entity.logistics_channel_4entity.logistics_channel_4 = true
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:
local flag = entity.logistics_supplierentity.logistics_supplier = true
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:
local flag = entity.logistics_requesterentity.logistics_requester = true
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:
local flag = entity.logistics_carrierentity.logistics_carrier = true
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:
local flag = entity.logistics_crane_onlyentity.logistics_crane_only = true
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:
local flag = entity.logistics_flying_onlyentity.logistics_flying_only = true
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:
local flag = entity.logistics_can_constructionentity.logistics_can_construction = true
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:
local flag = entity.logistics_transport_routeentity.logistics_transport_route = true
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:
local flag = entity.logistics_high_priorityentity.logistics_high_priority = true
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:
local flag = entity.has_crane
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:
local num = entity.crane_rangeentity.crane_range = 1
is_construction (Entity Variable)
Check if this entity is a construction site
Value: Construction site (boolean)
Access: read only
Example:
local flag = entity.is_construction
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:
local flag = entity.state_idle
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:
local flag = entity.state_path_blocked
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:
local flag = entity.state_inefficient
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:
local flag = entity.state_unpowered
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:
local flag = entity.state_emergency
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:
local flag = entity.state_broken
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:
local flag = entity.state_custom_1entity.state_custom_1 = true
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:
local flag = entity.state_custom_2entity.state_custom_2 = true
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:
local flag = entity.state_custom_3entity.state_custom_3 = true
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:
local flag = entity.state_custom_4entity.state_custom_4 = true
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:
local mode = entity.idle_mode
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:
local some_component = entity.controlling_component
active_order (Entity Variable)
Get currently executing order (or nil if none)
Value: Order info (or nil) (table)
Access: read only
Example:
local tbl = entity.active_order
has_component_list (Entity Variable)
Check if the entity has a component list and can have components
Value: Result (boolean)
Access: read only
Example:
local flag = entity.has_component_list
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:
local num = entity.component_count
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:
local num = entity.socket_count
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:
local num = entity.slot_count
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:
local num = entity.register_count
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:
local num = entity.frame_register_countentity.frame_register_count = 1
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:
local state = entity.most_relevant_state
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:
local tbl = entity.all_states
render_instances (Entity Variable)
Get number of render instances associated with this entity
Value: Count (integer)
Access: read only
Example:
local num = entity.render_instances
has_active_effects (Entity Variable)
Check if there are any looping effects playing on this entity
Value: Result (boolean)
Access: read only
Example:
local flag = entity.has_active_effects
idle_ticks (Entity Variable)
Return the number of ticks this entity has been idle for
Value: Idle tick count (integer)
Access: read only
Example:
local num = entity.idle_ticks
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:
local tbl = entity.triggered_components
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:
local pos = entity.interpolated_location
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:
local pos = entity.interpolated_center
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:
local num = entity.interpolated_rotation
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:
local pos = entity.interpolated_direction
Entity Operators
ToString Operator (Entity Operator)
Example:
local string_of_entity = tostring(entity)
Equality Operator (Entity Operator)
Example:
local is_same = entity_a == entity_blocal is_different = entity_a =~ entity_b
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.
- Argument 1: Function name (string)
- Argument 2: Callback function (function)
Example:
eventlistener:Bind("text", function() ... end)
Unbind (EventListener Function)
Unbind a specific function from this listener
Depending on the type of this listener unbinding functions might not be supported.
- Argument 1: Function name (string)
- Argument 2: Callback function (function)
Example:
eventlistener:Unbind("text", function() ... end)
UnbindAll (EventListener Function)
Unbind all functions bound to a given name
Depending on the type of this listener unbinding functions might not be supported.
- Argument 1: Function name (string)
Example:
eventlistener:UnbindAll("text")
EventListener Operators
Index Operator (EventListener Operator)
Depending on context or the type of this listener calling a bound function might not be supported.
Example:
local eventlistener_item = eventlistener.thing
NewIndex Operator (EventListener Operator)
Bind a function to this listener, usually done with a function assignment like
function LISTENER.FUNCTIONNAME(arg1, arg2) ... end
Example:
eventlistener.thing = new_value
Meta Table: Faction
A faction object represents a player or world owned faction.
Source: /Source/Desynced/Lua/Meta/DSFactionLuaMeta.cpp
- Functions
- Unlock
- IsUnlocked
- IsResearchable
- HavePickedUpItem
- GetPowerGrids
- GetPowerGrid
- GetPowerGridIndexAt
- GetPowerHistory
- GetItemHistory
- GetItemAmount
- GetItemAvailability
- GetItemTotals
- ModifyItemTotals
- GetActiveOrders
- GetNumActiveOrders
- CancelOrder
- OrderTransfer
- CanPlace
- GetPlaceableLocation
- RevealArea
- HideArea
- IsVisible
- IsDiscovered
- IsSeen
- FindClosestHiddenTile
- RunUI
- OrderEntitiesToMoveAway
- UpdateEntityInRegisters
- Respawn
- AddMood
- GetComponents
- GetEntitiesWithComponent
- GetEntitiesWithRegister
- GetEntitiesWithId
- GetEntityWithId
- GetVisibleEntities
- SetTrust
- GetTrust
- ResetTrust
- GetSharedVisibilityCount
- IsSharingVisibilityWith
- ShareVisibility
- UnshareVisibility
- Variables
- is_world_faction
- is_player_controlled
- has_logged_in_player
- default_trust
- entities
- num_entities
- num_operating_entities
- num_unlocked_techs
- foundation_entities
- all_items
- has_extra_data
- extra_data
- has_blight_shield
- id
- component_boost
- index
- name
- seed
- unlocks
- unlocked_techs
- unlocked_items
- unlocked_frames
- unlocked_components
- unlocked_values
- unlocked_codex
- researchable_techs
- items_picked_up
- discovered_tiles
- moods
- color
- home_location
- home_entity
- Operators
Faction Functions
Unlock (Faction Function)
Unlock something
- Argument 1: Id to unlock (can be item, frame, component, blueprint, behavior, codex or tech) (string)
- Argument 2: Notification (OPTIONAL, default true) (boolean)
- Return Value: Returns false if already unlocked (boolean)
Example:
local flag = faction:Unlock("text")local flag = faction:Unlock("text", true)
IsUnlocked (Faction Function)
Check if something was unlocked
- Argument 1: Id to check (string)
- Return Value: Result of check (boolean)
Example:
local flag = faction:IsUnlocked("text")
IsResearchable (Faction Function)
Check if a tech is available for research
- Argument 1: Tech id (string)
- Return Value: Result of check (boolean)
Example:
local flag = faction:IsResearchable("text")
HavePickedUpItem (Faction Function)
Check if an item was picked up
- Argument 1: Item id (string)
- Return Value: Result of check (boolean)
Example:
local flag = faction:HavePickedUpItem("text")
GetPowerGrids (Faction Function)
Get stats on all power grids of this faction
- Return Value: Power grids (table)
Example:
local tbl = faction:GetPowerGrids()
GetPowerGrid (Faction Function)
Get stats on all power grids of this faction
- Argument 1: Grid index (see entity.power_details or faction:GetPowerGridIndexAt) (integer)
- Return Value: Power grid details (table)
Example:
local tbl = faction:GetPowerGrid(1)
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.
- Argument 1: Location to check (area, coordinate or entity)
- Argument 2: Additional range around the location to check (OPTIONAL, default 0) (integer)
- Return Value: Index of the power grid (or nil if not inside any power grid) (integer)
Example:
local num = faction:GetPowerGridIndexAt(entity OR [ x, y ] OR [ x, y, w, h ])local num = faction:GetPowerGridIndexAt(entity OR [ x, y ] OR [ x, y, w, h ], 1)
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
- Argument 1: Resolution (1 finest, 3 most coarse) (integer)
- Argument 2: Number of elements to read (integer)
- Return Value: Power history data { total_produced = .., total_consumed = .. } (table)
Example:
local tbl = faction:GetPowerHistory(1, 1)
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
- Argument 1: item id (string)
- Argument 2: Resolution (1 finest, 3 most coarse) (integer)
- Argument 3: Number of elements to read (integer)
- Return Value: Item history data { added = .., removed = .. } (table)
Example:
local tbl = faction:GetItemHistory("text", 1, 1)
GetItemAmount (Faction Function)
Get the total amount currently available of an item
- Argument 1: item id (string)
- Return Value: Total item availability count (integer)
Example:
local num = faction:GetItemAmount("text")
GetItemAvailability (Faction Function)
Get a table of all entities that hold a specific item
- Argument 1: item id (string)
- Return Value: Item availability table (key is entity, value is amount held) or nil if not available (table)
Example:
local tbl = faction:GetItemAvailability("text")
GetItemTotals (Faction Function)
Get the total amount of generated (mined/produced) and consumed (as ingredients) for an item
- Argument 1: item id (string)
- Return Value: Total amount generated (integer)
- Return Value: Total amount consumed (integer)
Example:
local num, num = faction:GetItemTotals("text")
ModifyItemTotals (Faction Function)
Modify the total amount of generated (mined/produced) and consumed (as ingredients) for an item
- Argument 1: item id (string)
- Argument 2: Change to total amount generated (positive value to increase, negative value to reduce) (integer)
- Argument 3: Change to total amount consumed (positive value to increase, negative value to reduce) (integer)
- Argument 4: Store this change in the history graph (passed numbers must be positive values) (OPTIONAL) (boolean)
Example:
faction:ModifyItemTotals("text", 1, 1)faction:ModifyItemTotals("text", 1, 1, true)
GetActiveOrders (Faction Function)
Get a list of all active orders
- Argument 1: Filter orders to only contain those that involve this entity (OPTIONAL) (entity)
- Return Value: Array of orders (table)
Example:
local tbl = faction:GetActiveOrders()local tbl = faction:GetActiveOrders(other_entity)
GetNumActiveOrders (Faction Function)
Get the count of all active orders
- Argument 1: Filter orders to only contain those that involve this entity (OPTIONAL) (entity)
- Return Value: Count of orders (integer)
Example:
local num = faction:GetNumActiveOrders()local num = faction:GetNumActiveOrders(other_entity)
CancelOrder (Faction Function)
Cancel an existing order
- Argument 1: Order id (integer)
Example:
faction:CancelOrder(1)
OrderTransfer (Faction Function)
Create order to move items from one entity to another
Either source or target entity must be owned by this faction
- Argument 1: Source entity (entity)
- Argument 2: Target entity (entity)
- Argument 3: Item id (string)
- Argument 4: Amount (OPTIONAL, default to anything available in first slot with item id) (integer)
- Argument 5: Pass true update an existing order first with a new amount before creating a new order (OPTIONAL) (boolean)
--- or --- - Argument 1: Source entity (entity)
- Argument 2: Target entity (entity)
- Argument 3: Source item slot (itemslot)
- Argument 4: Amount (OPTIONAL, default to anything available in source item slot) (integer)
- Argument 5: Pass true update an existing order first with a new amount before creating a new order (OPTIONAL) (boolean)
--- or --- - Argument 1: Source entity (entity)
- Argument 2: Target entity (entity)
- Argument 3: Source component (component)
- Return Value: Return true if successful and false if the source doesn't hold the item amount or the target can't receive it (boolean)
Example:
local flag = faction:OrderTransfer(other_entity, other_entity, "text")local flag = faction:OrderTransfer(other_entity, other_entity, "text", 1, true)local flag = faction:OrderTransfer(other_entity, other_entity, item_slot)local flag = faction:OrderTransfer(other_entity, other_entity, item_slot, 1, true)local flag = faction:OrderTransfer(other_entity, other_entity, comp)
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.
- Argument 1: Frame id (string)
- Argument 2: Location X (integer)
- Argument 3: Location Y (integer)
- Argument 4: Rotation (0 to 3) (OPTIONAL, default 0) (integer)
- Argument 5: Specific visual id or another frame id from which to use the visual (OPTIONAL, defaults to frame visual) (string)
- Argument 6: Construction flag (OPTIONAL, default false) (boolean)
- Argument 7: Treat ungenerated map areas as blocking (OPTIONAL, default true) (boolean)
- Argument 8: Return blocking buildings (OPTIONAL, default false) (boolean)
- Argument 9: Return array of dropped items in area (OPTIONAL, default false) (boolean)
- Return Value: Result of the check (boolean)
- Return Value: Blocking buildings table (only returned if get_blocking_buildings was set, will be nil if there are none) (table)
- Return Value: Dropped items table (only returned if get_dropped_items was set, will be nil if there are none) (table)
Example:
local flag, tbl, tbl = faction:CanPlace("text", 1, 1)local flag, tbl, tbl = faction:CanPlace("text", 1, 1, 1, "text", true, true, true, true)
GetPlaceableLocation (Faction Function)
Return the closest location where CanPlace would return true
- Argument 1: Frame id (string)
- Argument 2: Location X (integer)
- Argument 3: Location Y (integer)
- Argument 4: Rotation (0 to 3) (OPTIONAL, default 0) (integer)
- Argument 5: Specific visual id or another frame id from which to use the visual (OPTIONAL, defaults to frame visual) (string)
- Argument 6: Construction flag (OPTIONAL, default false) (boolean)
- Argument 7: Treat ungenerated map areas as blocking (OPTIONAL, default true) (boolean)
- Return Value: Resulting Location X (integer)
- Return Value: Resulting Location Y (integer)
Example:
local num, num = faction:GetPlaceableLocation("text", 1, 1)local num, num = faction:GetPlaceableLocation("text", 1, 1, 1, "text", true, true)
RevealArea (Faction Function)
Reveal visibility of an area
- Argument 1: Area (area, coordinate or entity)
- Argument 2: Visibility range (integer)
Example:
faction:RevealArea(entity OR [ x, y ] OR [ x, y, w, h ], 1)
HideArea (Faction Function)
Hide visibility of an area
- Argument 1: Area (area, coordinate or entity)
- Argument 2: Visibility range (integer)
Example:
faction:HideArea(entity OR [ x, y ] OR [ x, y, w, h ], 1)
IsVisible (Faction Function)
Check if a tile or area is currently visible to this faction
- Argument 1: Location to check (area, coordinate or entity)
- Argument 2: If true and area specifies multiple tiles, require all tiles to be visible (OPTIONAL, default false) (boolean)
- Return Value: Result of check (boolean)
Example:
local flag = faction:IsVisible(entity OR [ x, y ] OR [ x, y, w, h ])local flag = faction:IsVisible(entity OR [ x, y ] OR [ x, y, w, h ], true)
IsDiscovered (Faction Function)
Check if a tile or area has been revealed by this faction
- Argument 1: Location to check (area, coordinate or entity)
- Argument 2: If true and area specifies multiple tiles, require all tiles to be discovered (OPTIONAL, default false) (boolean)
- Return Value: Result of check (boolean)
Example:
local flag = faction:IsDiscovered(entity OR [ x, y ] OR [ x, y, w, h ])local flag = faction:IsDiscovered(entity OR [ x, y ] OR [ x, y, w, h ], true)
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)
- Argument 1: Entity to check (entity)
- Return Value: Result of check (boolean)
Example:
local flag = faction:IsSeen(other_entity)
FindClosestHiddenTile (Faction Function)
Finds closest non visible tile
- Argument 1: Start X coordinate (integer)
- Argument 2: Start Y coordinate (integer)
- Argument 3: Stop search after checking how many tiles (integer)
- Argument 4: Skip blight tiles (OPTIONAL, default true) (boolean)
- Return Value: Result X position (integer)
- Return Value: Result Y position (integer)
Example:
local num, num = faction:FindClosestHiddenTile(1, 1, 1)local num, num = faction:FindClosestHiddenTile(1, 1, 1, true)
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
- Argument 1: LUA function to execute in UI context (function)
- Argument 2: Passed values (OPTIONAL, can pass multiple values) (anything)
--- or --- - Argument 1: Message name registered in UIMsg (string)
- Argument 2: Passed values (OPTIONAL, can pass multiple values) (anything)
Example:
faction:RunUI(function() ... end)faction:RunUI(function() ... end, ...)faction:RunUI("text")faction:RunUI("text", ...)
OrderEntitiesToMoveAway (Faction Function)
Order movable entities to move away from a given area
- Argument 1: Location or area (area, coordinate or entity)
- Argument 2: An entity that will be excepted from the order (OPTIONAL) (entity)
- Return Value: The number of entities that successfully were ordered to move away (integer)
- Return Value: The total number of blocking entities currently in the area (of any faction, excludes the excepted entity) (integer)
Example:
local num, num = faction:OrderEntitiesToMoveAway(entity OR [ x, y ] OR [ x, y, w, h ])local num, num = faction:OrderEntitiesToMoveAway(entity OR [ x, y ] OR [ x, y, w, h ], other_entity)
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
- Argument 1: The old entity value (entity)
- Argument 2: The new entity value (or nil to clear it) (entity)
Example:
faction:UpdateEntityInRegisters(other_entity)faction:UpdateEntityInRegisters(other_entity, other_entity)
Respawn (Faction Function)
Respawn the faction
Example:
faction:Respawn()
AddMood (Faction Function)
Add some amount to one of the faction moods
- Argument 1: Mood name (one of the table keys in moods) (string)
- Argument 2: Amount to add (integer)
Example:
faction:AddMood("text", 1)
GetComponents (Faction Function)
Get all components of a given type equipped by entities of this faction
- Argument 1: Component id (string)
- Argument 2: Set to true to query the base_id value of component definitions if it exists (OPTIONAL, default false) (boolean)
- Return Value: Array of components (table)
Example:
local tbl = faction:GetComponents()local tbl = faction:GetComponents("text", true)
GetEntitiesWithComponent (Faction Function)
Get all entities of this faction that have a given component equipped
- Argument 1: Component id (string)
- Argument 2: Set to true to query the base_id value of component definitions if it exists (OPTIONAL, default false) (boolean)
- Argument 3: Set to not return hidden components (OPTIONAL, default false) (boolean)
- Return Value: Array of entities (table)
Example:
local tbl = faction:GetEntitiesWithComponent("text")local tbl = faction:GetEntitiesWithComponent("text", true, true)
GetEntitiesWithRegister (Faction Function)
Get all entities of this faction that have a specific frame register set, optionally filtered by id or entity
- Argument 1: Frame register number (integer)
- Argument 2: Return only entities which have any kind of entity referenced in the register (OPTIONAL, default false) (boolean)
--- or --- - Argument 1: Frame register number (integer)
- Argument 2: Id filter (string)
- Argument 3: Additionally return all entities which have any kind of entity referenced in the register (OPTIONAL, default false) (boolean)
--- or --- - Argument 1: Frame register number (integer)
- Argument 2: Entity filter (entity)
- Return Value: Array of entities matching the filter (table)
Example:
local tbl = faction:GetEntitiesWithRegister(1)local tbl = faction:GetEntitiesWithRegister(1, true)local tbl = faction:GetEntitiesWithRegister(1, "text")local tbl = faction:GetEntitiesWithRegister(1, "text", true)local tbl = faction:GetEntitiesWithRegister(1, other_entity)
GetEntitiesWithId (Faction Function)
Get all entities of this faction with a given frame id
Cannot be used with foundation type frame ids
- Argument 1: Frame id (string)
- Return Value: Array of entities (table)
Example:
local tbl = faction:GetEntitiesWithId("text")
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
- Argument 1: Frame id (string)
- Return Value: Entity (or nil if none) (entity)
Example:
local some_entity = faction:GetEntityWithId("text")
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
- Argument 1: Pass a table to use it as a cache for the return value to avoid allocating a new large table (OPTIONAL) (table)
- Argument 2: Set to true to only get entities with visual register set or a state (OPTIONAL, default false) (boolean)
- Argument 3: If set will only check against that single entity instead of everything on screen (OPTIONAL) (entity)
- Argument 4: Only usable with visual_or_state set to true, return only entities with certain states (OPTIONAL) (integer)
- Return Value: One array with 4 or 6 elements for each entity (entity, X, Y, distance as well as visual register and states if true was passed) (table)
- Return Value: How many elements were written to the table (entity count * 4 or 6) (integer)
Example:
local tbl, num = faction:GetVisibleEntities()local tbl, num = faction:GetVisibleEntities({ ... }, true, other_entity, 1)
SetTrust (Faction Function)
Set the trust level towards another faction
The trust level from/to the world faction and self can't be changed
- Argument 1: Other faction or faction id (faction)
- Argument 2: Trust level, one of 'ENEMY', 'NEUTRAL' or 'ALLY' (string)
- Argument 3: If set to true, will apply the trust level bidirectional for the other faction towards this as well (OPTIONAL, default false) (boolean)
--- or --- - Argument 1: Entity to use the owning faction for the check (entity)
- Argument 2: Trust level, one of 'ENEMY', 'NEUTRAL' or 'ALLY' (string)
- Argument 3: If set to true, will apply the trust level bidirectional for the other faction towards this as well (OPTIONAL, default false) (boolean)
Example:
faction:SetTrust("faction_id", "text")faction:SetTrust("faction_id", "text", true)faction:SetTrust(other_entity, "text")faction:SetTrust(other_entity, "text", true)
GetTrust (Faction Function)
Get the trust level towards another faction
- Argument 1: Other faction or faction id (faction)
--- or --- - Argument 1: Entity to use the owning faction for the check (entity)
- Return Value: Trust level, one of 'ENEMY', 'NEUTRAL' or 'ALLY' (will always be 'ALLY' when checking against self and nil when other faction doesn't exist) ("ENEMY" | "NEUTRAL" | "ALLY")
Example:
local trust = faction:GetTrust("faction_id")local trust = faction:GetTrust(other_entity)
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:
faction:ResetTrust()
GetSharedVisibilityCount (Faction Function)
Check if this faction is sharing visibility with anyone and with how many other factions visibility is shared with
- Return Value: Number of factions visibility is shared with (or nil if not sharing visibility) (integer)
Example:
local num = faction:GetSharedVisibilityCount()
IsSharingVisibilityWith (Faction Function)
Check if this faction is sharing visibility with another factions
- Argument 1: Other faction or faction id (faction)
- Return Value: True if faction is sharing visibility with the other faction (boolean)
Example:
local flag = faction:IsSharingVisibilityWith("faction_id")
ShareVisibility (Faction Function)
Share visibility with another faction
- Argument 1: Other faction or faction id (faction)
Example:
faction:ShareVisibility("faction_id")
UnshareVisibility (Faction Function)
Unshare visibility with other factions
Example:
faction:UnshareVisibility()
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:
local flag = faction.is_world_faction
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:
local flag = faction.is_player_controlled
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:
local flag = faction.has_logged_in_player
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:
local trust = faction.default_trustfaction.default_trust = "NEUTRAL"
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:
local tbl = faction.entities
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:
local num = faction.num_entities
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:
local num = faction.num_operating_entities
num_unlocked_techs (Faction Variable)
Get the number of unlocked techs
Value: number of unlocked techs (integer)
Access: read only
Example:
local num = faction.num_unlocked_techs
foundation_entities (Faction Variable)
Get foundation entities owned by this faction
Value: Table with a list of foundation entities (table)
Access: read only
Example:
local tbl = faction.foundation_entities
all_items (Faction Variable)
Get all resources available to this faction
Value: item_id => count (table)
Access: read only
Example:
local tbl = faction.all_items
has_extra_data (Faction Variable)
Check if extra_data has been created for this faction
Value: Result (boolean)
Access: read only
Example:
local flag = faction.has_extra_data
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:
local tbl = faction.extra_datafaction.extra_data = { ... }
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:
local flag = faction.has_blight_shieldfaction.has_blight_shield = true
id (Faction Variable)
The id of this faction
Value: Faction id (faction-id-string)
Access: read only
Example:
local faction_id = faction.id
component_boost (Faction Variable)
The component efficiency boost of this faction in percent (default 100).
Value: Component efficiency percent (integer)
Access: read & write
Example:
local num = faction.component_boostfaction.component_boost = 1
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:
local faction_id = faction.index
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:
local str = faction.namefaction.name = "text"
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:
local num = faction.seed
unlocks (Faction Variable)
Get list of unlocked things
Value: List of unlocked ids (table)
Access: read only
Example:
local tbl = faction.unlocks
unlocked_techs (Faction Variable)
Get list of unlocked techs
Value: tech id list (table)
Access: read only
Example:
local tbl = faction.unlocked_techs
unlocked_items (Faction Variable)
Get list of unlocked items (does not include frames or components)
Value: item id list (table)
Access: read only
Example:
local tbl = faction.unlocked_items
unlocked_frames (Faction Variable)
Get list of unlocked frames
Value: frame id list (table)
Access: read only
Example:
local tbl = faction.unlocked_frames
unlocked_components (Faction Variable)
Get list of unlocked components
Value: component id list (table)
Access: read only
Example:
local tbl = faction.unlocked_components
unlocked_values (Faction Variable)
Get list of unlocked values
Value: value id list (table)
Access: read only
Example:
local tbl = faction.unlocked_values
unlocked_codex (Faction Variable)
Get list of unlocked codex entries
Value: codex id list (table)
Access: read only
Example:
local tbl = faction.unlocked_codex
researchable_techs (Faction Variable)
Get list of all techs available for research
Value: tech id list (table)
Access: read only
Example:
local tbl = faction.researchable_techs
items_picked_up (Faction Variable)
Get list of all picked up items
Value: item id list (table)
Access: read only
Example:
local tbl = faction.items_picked_up
discovered_tiles (Faction Variable)
Get the total number of visibility tiles this faction has revealed
Value: Discovered tiles count (integer)
Access: read only
Example:
local num = faction.discovered_tiles
moods (Faction Variable)
Get table of faction moods
Value: faction mood table (table)
Access: read only
Example:
local tbl = faction.moods
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:
local col = faction.colorfaction.color = { 1, 0, 0 }
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:
local pos = faction.home_locationfaction.home_location = { x = 1, y = 2 }
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:
local some_entity = faction.home_entityfaction.home_entity = other_entity
Faction Operators
ToString Operator (Faction Operator)
Example:
local string_of_faction = tostring(faction)
Equality Operator (Faction Operator)
Example:
local is_same = faction_a == faction_blocal is_different = faction_a =~ faction_b
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
- Argument 1: Item id (string)
- Argument 2: Amount (integer)
- Argument 3: Extra data table (OPTIONAL, default nil) (table)
Example:
itemslot:SetItemAndStack("text", 1)itemslot:SetItemAndStack("text", 1, { ... })
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.
- Argument 1: Amount to be added (integer)
- Argument 2: Set to true to count this stack modification as item generation in the history graph (OPTIONAL, default false) (boolean)
Example:
itemslot:AddStack(1)itemslot:AddStack(1, true)
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)
- Argument 1: Amount to be removed (integer)
- Argument 2: Set to true to count this stack modification as item consumption in the history graph (OPTIONAL, default false) (boolean)
Example:
itemslot:RemoveStack(1)itemslot:RemoveStack(1, true)
Clear (ItemSlot Function)
Clear the content in this slot
- Return Value: The extra_data table before the slot was cleared (table)
Example:
local tbl = itemslot:Clear()
SetLockedItem (ItemSlot Function)
Sets the item and locks an otherwise empty slot
- Argument 1: Item id (or nil to change a locked slot to empty) (string)
- Return Value: True if the locked item was set (False if slot contains something else already) (boolean)
Example:
local flag = itemslot:SetLockedItem()local flag = itemslot:SetLockedItem("text")
Swap (ItemSlot Function)
Swap the entire contents (including reservations) of two slots of the same slot type on the same inventory
- Argument 1: Other item slot (must be of the same slot type and on the same inventory) (itemslot)
Example:
itemslot:Swap(item_slot)
Move (ItemSlot Function)
Move as much as possible (including reservations) into another slot on the same inventory
- Argument 1: Target item slot (must be on the same inventory and be empty or have the same item) (itemslot)
- Argument 2: Limit amount to be moved (OPTIONAL, default everything) (integer)
- Return Value: True if any items or reservations have been moved (boolean)
Example:
local flag = itemslot:Move(item_slot)local flag = itemslot:Move(item_slot, 1)
GetReserveInfo (ItemSlot Function)
Gets all the reserve information relative to this slot
- Return Value: A set of tables of each reserve info related to this slot (table)
Example:
local tbl = itemslot:GetReserveInfo()
CancelOrders (ItemSlot Function)
Cancel all orders related to this item slot
Example:
itemslot:CancelOrders()
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.
- Argument 1: Item id to be ordered (string)
- Argument 2: Amount to be ordered (integer)
- Argument 3: Priority "None", "HighPriority", "ManualOrder" (OPTIONAL, default "None") (string)
- Argument 4: If set and not 0, make the order on the channels denoted by the set bits (OPTIONAL) (integer)
- Argument 5: Make a fixed order from this slot (must be different entity, must have amount available) (OPTIONAL) (itemslot)
- Argument 6: Component through which the items will be ordered (must be on same entity as this slot, also see
component:OrderItem) (OPTIONAL) (component) - Return Value: Order ID created or modified (integer)
Example:
local num = itemslot:OrderItem("text", 1)local num = itemslot:OrderItem("text", 1, "text", 1, item_slot, comp)
GetUnreservedSpaceFor (ItemSlot Function)
The amount of free space actually available to be filled with a specific item (slot can be empty)
- Argument 1: Item id (item-id-string)
- Return Value: Unreserved free space count (integer)
Example:
local num = itemslot:GetUnreservedSpaceFor("item_id")
CountGenerateAmount (ItemSlot Function)
Get how many items a component with a prepared process is generating into this slot
- Argument 1: Component which is generating item(s) (or nil to count all) (component)
- Return Value: How many items the component is generating into this item slot (0 if not generating into this slot) (integer)
Example:
local num = itemslot:CountGenerateAmount()local num = itemslot:CountGenerateAmount(comp)
CountConsumeAmount (ItemSlot Function)
Get how many items a component with a prepared process is consuming from this slot
- Argument 1: Component which is consuming item(s) (or nil to count all) (component)
- Return Value: How many items the component is consuming from this item slot (0 if not consuming from this slot) (integer)
Example:
local num = itemslot:CountConsumeAmount()local num = itemslot:CountConsumeAmount(comp)
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:
local item_id = itemslot.id
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:
local tbl = itemslot.def
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:
local num = itemslot.stackitemslot.stack = 1
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:
local num = itemslot.max_stack
reserved_stack (ItemSlot Variable)
The amount of reserved items for ingredients or outgoing orders
Value: Reserved amount (integer)
Access: read only
Example:
local num = itemslot.reserved_stack
unreserved_stack (ItemSlot Variable)
The amount of items not reserved for ingredients or outgoing orders
Value: Unreserved amount (integer)
Access: read only
Example:
local num = itemslot.unreserved_stack
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:
local num = itemslot.reserved_space
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:
local num = itemslot.unreserved_space
has_order (ItemSlot Variable)
Check if there exists any order related to this slot
Value: Check result (boolean)
Access: read only
Example:
local flag = itemslot.has_order
owner (ItemSlot Variable)
The entity that owns this slot
Value: Entity (entity)
Access: read only
Example:
local some_entity = itemslot.owner
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:
local flag = itemslot.exists
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:
local some_entity = itemslot.entityitemslot.entity = other_entity
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:
local some_entity = itemslot.reserved_entity
component (ItemSlot Variable)
The component that holds this slot
Value: Component object or nil if none (component)
Access: read only
Example:
local some_component = itemslot.component
type (ItemSlot Variable)
The type of slot
Value: Slot type (string)
Access: read only
Example:
local str = itemslot.type
has_extra_data (ItemSlot Variable)
Check if extra_data has been created for this item slot
Value: Result (boolean)
Access: read only
Example:
local flag = itemslot.has_extra_data
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:
local tbl = itemslot.extra_dataitemslot.extra_data = { ... }
locked (ItemSlot Variable)
Is this item slot locked from changing item def?
Value: Locked (boolean)
Access: read & write
Example:
local flag = itemslot.lockeditemslot.locked = true
ItemSlot Operators
ToString Operator (ItemSlot Operator)
Example:
local string_of_itemslot = tostring(itemslot)
Equality Operator (ItemSlot Operator)
Example:
local is_same = itemslot_a == itemslot_blocal is_different = itemslot_a =~ itemslot_b
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):
- Run the entry lua file of all active mod packages
- 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.
- 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.
- Call package:post_init()
- When starting a new game, run the function package:on_world_spawn()
- 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.
- 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:
local str = modpackage.id
name (ModPackage Variable)
Get the package name
Value: Name value (string)
Access: read only
Example:
local str = modpackage.name
description (ModPackage Variable)
Get the package description
Value: Name value (string)
Access: read only
Example:
local str = modpackage.description
entry (ModPackage Variable)
Get the package entry file
Value: Entry value (string)
Access: read only
Example:
local str = modpackage.entry
type (ModPackage Variable)
Get the package type
Value: Type (string)
Access: read only
Example:
local str = modpackage.type
dependencies (ModPackage Variable)
Get the dependencies list
Value: Dependency array (table)
Access: read only
Example:
local tbl = modpackage.dependencies
modes (ModPackage Variable)
Get the multiplayer game modes list
Value: Modes array (table)
Access: read only
Example:
local tbl = modpackage.modes
mod_id (ModPackage Variable)
Get the mod id
Value: id value (string)
Access: read only
Example:
local str = modpackage.mod_id
mod_name (ModPackage Variable)
Get the mod name
Value: name value (string)
Access: read only
Example:
local str = modpackage.mod_name
mod_version_name (ModPackage Variable)
Get the mod version name
Value: version value (string)
Access: read only
Example:
local str = modpackage.mod_version_name
mod_version_code (ModPackage Variable)
Get the mod version code
Value: version value (string)
Access: read only
Example:
local str = modpackage.mod_version_code
mod_author (ModPackage Variable)
Get the mod author
Value: author value (string)
Access: read only
Example:
local str = modpackage.mod_author
mod_homepage (ModPackage Variable)
Get the mod homepage
Value: homepage value (string)
Access: read only
Example:
local str = modpackage.mod_homepage
mod_description (ModPackage Variable)
Get the mod description
Value: description value (string)
Access: read only
Example:
local str = modpackage.mod_description
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:
local tbl = modpackage.includesmodpackage.includes = { ... }
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:
register:Clear()
Init (Register Function)
Copy contents from another register or table
- Argument 1: New register object or table (register)
Example:
register:Init({ num = 10, id = "id" })
Register Variables
num (Register Variable)
The number stored in this register
Value: Number (integer)
Access: read & write
Example:
local num = register.numregister.num = 1
id (Register Variable)
The generic id stored in this register
Value: Id (id-string)
Access: read & write
Example:
local id = register.idregister.id = "id"
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:
local tbl = register.def
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:
local value_id = register.value_idregister.value_id = "value_id"
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:
local item_id = register.item_idregister.item_id = "item_id"
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:
local frame_id = register.frame_idregister.frame_id = "frame_id"
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:
local component_id = register.component_idregister.component_id = "component_id"
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:
local tech_id = register.tech_idregister.tech_id = "tech_id"
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:
local some_entity = register.entityregister.entity = other_entity
coord (Register Variable)
The coordinate stored in this register or nil if no coordinate is stored
Value: Coordinate (coordinate)
Access: read & write
Example:
local pos = register.coordregister.coord = { x = 1, y = 2 }
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:
local num = register.coord_xregister.coord_x = 1
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:
local num = register.coord_yregister.coord_y = 1
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:
local some_entity = register.raw_entity
is_link (Register Variable)
Check if a register is linked from another register
Value: link state (boolean)
Access: read only
Example:
local flag = register.is_link
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:
local flag = register.is_empty
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:
local flag = register.raw_is_empty
is_error (Register Variable)
Check if a register is in error state
Value: Error (boolean)
Access: read only
Example:
local flag = register.is_error
Register Operators
ToString Operator (Register Operator)
Example:
local string_of_register = tostring(register)
Equality Operator (Register Operator)
Example:
local is_same = register_a == register_blocal is_different = register_a =~ register_b
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:
local result = register_a + register_b
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:
local result = register_a - register_b
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:
local result = register_a * register_b
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:
local result = register_a // register_b
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:
local result = register_a % register_b
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
- Return Value: Valid state (boolean)
Example:
local flag = widget:IsValid()
IsVisible (Widget Function)
Check if widget is visible on screen (self and no parent is hidden)
- Return Value: Visible state (boolean)
Example:
local flag = widget:IsVisible()
Add (Widget Function)
Add a widget to a panel widget
- Argument 1: The widget to add (widget)
--- or --- - Argument 1: Layout text for creating a new widget inline (string)
- Argument 2: Property table for the inline widget (OPTIONAL) (table)
- Return Value: The added widget (widget)
Example:
local some_widget = widget:Add(widget)local some_widget = widget:Add("text")local some_widget = widget:Add("text", { ... })
SetContent (Widget Function)
Set the content of a single-child panel widget
- Argument 1: The widget to set (widget)
--- or --- - Argument 1: Layout text for creating a new widget inline (string)
- Argument 2: Property table for the inline widget (OPTIONAL) (table)
- Return Value: The set widget (widget)
Example:
local some_widget = widget:SetContent(widget)local some_widget = widget:SetContent("text")local some_widget = widget:SetContent("text", { ... })
Clear (Widget Function)
Clear all widgets in a panel widget
Example:
widget:Clear()
GetChild (Widget Function)
Get a child widget
- Argument 1: Which child to get (OPTIONAL, default 1) (integer)
- Return Value: Child widget (widget)
Example:
local some_widget = widget:GetChild()local some_widget = widget:GetChild(1)
SortChildren (Widget Function)
Sort all child widgets
- Argument 1: Sort predicate callback (will be called with two widgets to compare) (function)
Example:
widget:SortChildren(function() ... end)
RemoveFromParent (Widget Function)
Remove a widget from its parent
Example:
widget:RemoveFromParent()
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.
- Argument 1: Function property name (string)
- Argument 2: Passed values (OPTIONAL, can pass multiple values) (anything)
- Return Value: Return values of call (anything)
Example:
local val = widget:SendEvent("text")local val = widget:SendEvent("text", ...)
GetDesiredSize (Widget Function)
Get the desired size of a widget
- Return Value: Width (number)
- Return Value: Height (number)
Example:
local num, num = widget:GetDesiredSize()
SetPosition (Widget Function)
Set the position of a widget placed a canvas panel widget
- Argument 1: X position (number)
- Argument 2: Y position (number)
- Argument 3: Z order, widgets with higher values are drawn on top (OPTIONAL) (number)
Example:
widget:SetPosition(1, 1)widget:SetPosition(1, 1, 1)
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
- Argument 1: Widget to get relative position to (OPTIONAL) (widget)
- Return Value: X position (number)
- Return Value: Y position (number)
- Return Value: X size (number)
- Return Value: Y size (number)
Example:
local num, num, num, num = widget:GetViewportPosition()local num, num, num, num = widget:GetViewportPosition(widget)
SetIgnoreHitTest (Widget Function)
Set this widget (and any children) to not interact with the mouse cursor (clicking or dragging over)
- Argument 1: Ignore hit test (OPTIONAL) (boolean)
Example:
widget:SetIgnoreHitTest()widget:SetIgnoreHitTest(true)
TweenTo (Widget Function)
Animate a numerical property
- Argument 1: Parameter name (string)
- Argument 2: Target value (number)
- Argument 3: Duration in milliseconds (OPTIONAL, default 400) (number)
- Argument 4: Wait time in milliseconds (OPTIONAL, default 0) (number)
- Argument 5: Easing function name (OPTIONAL, default "InOutQuad") (string)
- Argument 6: Animation finished callback (OPTIONAL) (function)
Example:
widget:TweenTo("text", 1)widget:TweenTo("text", 1, 1, 1, "text", function() ... end)
TweenFromTo (Widget Function)
Animate a numerical property
- Argument 1: Parameter name (string)
- Argument 2: Start value (number)
- Argument 3: Target value (number)
- Argument 4: Duration in milliseconds (OPTIONAL, default 400) (number)
- Argument 5: Wait time in milliseconds (OPTIONAL, default 0) (number)
- Argument 6: Easing function name (OPTIONAL, default "InOutQuad") (string)
- Argument 7: Animation finished callback (OPTIONAL) (function)
Example:
widget:TweenFromTo("text", 1, 1)widget:TweenFromTo("text", 1, 1, 1, 1, "text", function() ... end)
StopTween (Widget Function)
Stop an active tween
- Argument 1: Parameter name (string)
- Return Value: True if a tween existed and was stopped (boolean)
Example:
local flag = widget:StopTween("text")
GetTweenTarget (Widget Function)
Get the target value of an active tween
- Argument 1: Parameter name (string)
- Return Value: Target value (or nil if not active tween) (number)
Example:
local num = widget:GetTweenTarget("text")
FindAbove (Widget Function)
Find property in any widget above in the layout tree
- Argument 1: Parameter name (string)
- Return Value: Parameter value if found (anything)
Example:
local val = widget:FindAbove("text")
Widget Variables
parent (Widget Variable)
Get the parent of a widget
Value: Parent widget (or nil if none) (widget)
Access: read only
Example:
local some_widget = widget.parent
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:
local some_widget = widget.root
children (Widget Variable)
Get or set an array of child widgets
Value: Array of child widgets (table)
Access: read & write
Example:
local tbl = widget.childrenwidget.children = { ... }
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:
local num = widget.child_countwidget.child_count = 1
has_children (Widget Variable)
Check if child widgets exist
Value: True if there are any child widgets (boolean)
Access: read only
Example:
local flag = widget.has_children
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:
local num = widget.child_indexwidget.child_index = 1
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:
local some_widget = widget.next_sibling
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:
local some_widget = widget.previous_sibling
class (Widget Variable)
Get the table passed to UI.Register
Value: Class table (or nil if none) (table)
Access: read only
Example:
local tbl = widget.class
Widget Operators
Index Operator (Widget Operator)
Read properties of this widget
Example:
local widget_item = widget.thing
NewIndex Operator (Widget Operator)
Modify or add new properties of this widget
Example:
widget.thing = new_value
ToString Operator (Widget Operator)
Example:
local string_of_widget = tostring(widget)
Length Operator (Widget Operator)
Get number of child widgets (same as child_count)
Example:
local num_of_widget = #widget
Equality Operator (Widget Operator)
Example:
local is_same = widget_a == widget_blocal is_different = widget_a =~ widget_b