Main Functions
Version History
| Build Version | Change Date | Change Type | Description |
|---|---|---|---|
| 676042 | 2025-06-21 | stable | Current version |
Overview
The mainfunctions.lua script provides essential game functions for save/load operations, entity management, time handling, and game flow control. These functions form the backbone of DST's runtime operations and are used throughout the game for critical system management.
Usage Example
-- Entity spawning
local flower = SpawnPrefab("flower")
flower.Transform:SetPosition(10, 0, 5)
-- Time functions
local current_time = GetTime()
local tick_time = GetTickTime()
-- Save operations
SavePersistentString("my_save", data, true, function()
print("Save completed")
end)
Save/Load Functions
SavePersistentString(name, data, encode, callback)
Status: stable
Description: Saves data to persistent storage with optional encoding and callback notification.
Parameters:
name(string): Name identifier for the save datadata(string): Data to be savedencode(boolean): Whether to encode the datacallback(function): Optional callback function executed after save
Example:
local save_data = "player_settings=enabled"
SavePersistentString("settings", save_data, true, function()
print("Settings saved successfully")
end)
ErasePersistentString(name, callback)
Status: stable
Description: Removes persistent data with the given name.
Parameters:
name(string): Name identifier for the data to erasecallback(function): Optional callback function executed after erasure
Example:
ErasePersistentString("old_save", function()
print("Old save data removed")
end)
Entity Management Functions
SpawnPrefab(name, skin, skin_id, creator)
Status: stable
Description: Spawns a prefab instance in the game world with optional skin and creator information.
Parameters:
name(string): Prefab name to spawnskin(string): Optional skin identifierskin_id(string): Optional skin IDcreator(EntityScript): Optional creator entity
Returns:
- (EntityScript): The spawned entity instance
Example:
-- Spawn a basic flower
local flower = SpawnPrefab("flower")
-- Spawn with specific skin
local character = SpawnPrefab("wilson", "wilson_formal")
-- Check if spawning succeeded
if flower then
flower.Transform:SetPosition(x, y, z)
end
ReplacePrefab(original_inst, name, skin, skin_id, creator)
Status: stable
Description: Replaces an existing entity with a new prefab at the same position.
Parameters:
original_inst(EntityScript): Entity to replacename(string): New prefab nameskin(string): Optional skin identifierskin_id(string): Optional skin IDcreator(EntityScript): Optional creator entity
Returns:
- (EntityScript): The replacement entity instance
Example:
-- Replace a sapling with a tree
local tree = ReplacePrefab(sapling, "tree")
CreateEntity(name)
Status: stable
Description: Creates a new entity with optional name identifier.
Parameters:
name(string): Optional name for the entity
Returns:
- (EntityScript): The created entity script
Example:
local custom_entity = CreateEntity("MyCustomEntity")
custom_entity:AddComponent("health")
RemoveEntity(guid)
Status: stable
Description: Removes an entity from the game world by its GUID.
Parameters:
guid(number): Entity GUID to remove
Example:
local entity_guid = entity.GUID
RemoveEntity(entity_guid)
Time Functions
GetTime()
Status: stable
Description: Returns the current game time in seconds.
Returns:
- (number): Current game time
Example:
local current_time = GetTime()
print("Game has been running for", current_time, "seconds")
GetTick()
Status: stable
Description: Returns the current game tick count.
Returns:
- (number): Current tick number
Example:
local tick = GetTick()
if tick % 30 == 0 then
-- Execute every 30 ticks (approximately 1 second)
DoPeriodicTask()
end
GetTickTime()
Status: stable
Description: Returns the duration of one game tick in seconds.
Returns:
- (number): Tick duration in seconds
Example:
local tick_duration = GetTickTime()
local ticks_per_second = 1 / tick_duration
GetStaticTime()
Status: stable
Description: Returns the current static time (unaffected by time scale).
Returns:
- (number): Current static time
GetTimeReal()
Status: stable
Description: Returns real-world time in milliseconds since game start.
Returns:
- (number): Real time in milliseconds
SecondsToTimeString(total_seconds)
Status: stable
Description: Converts seconds to a formatted time string.
Parameters:
total_seconds(number): Time in seconds to convert
Returns:
- (string): Formatted time string (MM:SS or SS format)
Example:
local time_str = SecondsToTimeString(125)
print(time_str) -- Output: "2:05"
Game Flow Control
SimReset(instanceparameters)
Status: stable
Description: Resets the simulation with new instance parameters.
Parameters:
instanceparameters(table): Optional parameters for the new instance
Example:
-- Reset to main menu
SimReset({reset_action = RESET_ACTION.LOAD_FRONTEND})
Shutdown()
Status: stable
Description: Safely shuts down the game, handling cleanup operations.
Example:
-- Graceful shutdown
Shutdown()
DoRestart(save)
Status: stable
Description: Restarts the game with optional save operation.
Parameters:
save(boolean): Whether to save before restarting
Example:
-- Restart without saving
DoRestart(false)
-- Restart with save
DoRestart(true)
Pause/Resume Functions
SetPause(val, reason)
Status: stable
Description: Sets the game pause state with optional reason.
Parameters:
val(boolean): Whether to pause the gamereason(string): Optional reason for pause
Example:
-- Pause the game
SetPause(true, "Menu opened")
-- Resume the game
SetPause(false)
IsPaused()
Status: stable
Description: Checks if the game is currently paused.
Returns:
- (boolean): True if game is paused
Example:
if not IsPaused() then
-- Only update when not paused
UpdateGameLogic()
end
SetAutopaused(autopause)
Status: stable
Description: Sets automatic pause state (e.g., when inventory is open).
Parameters:
autopause(boolean): Whether to enable autopause
Script and Asset Loading
LoadScript(filename)
Status: stable
Description: Loads and caches a Lua script file.
Parameters:
filename(string): Script filename relative to scripts directory
Returns:
- (any): The loaded script's return value
Example:
local utility_script = LoadScript("util/helpers")
RunScript(filename)
Status: stable
Description: Loads and executes a Lua script file.
Parameters:
filename(string): Script filename to execute
Example:
RunScript("custom/initialization")
LoadPrefabFile(filename, async_batch_validation, search_asset_first_path)
Status: stable
Description: Loads prefab definitions from a file with optional validation settings.
Parameters:
filename(string): Prefab file to loadasync_batch_validation(boolean): Whether to use async validationsearch_asset_first_path(boolean): Whether to prioritize asset paths
Returns:
- (table): Array of loaded prefab definitions
Example:
-- Load character prefabs
LoadPrefabFile("prefabs/characters")
-- Load with async validation
LoadPrefabFile("prefabs/items", true)
Network and Multiplayer
OnPlayerLeave(player_guid, expected)
Status: stable
Description: Handles player disconnection events.
Parameters:
player_guid(number): GUID of the leaving playerexpected(boolean): Whether the disconnection was expected
OnNetworkDisconnect(message, should_reset, force_immediate_reset, details, miscdata)
Status: stable
Description: Handles network disconnection with appropriate UI feedback.
Parameters:
message(string): Disconnection reason codeshould_reset(boolean): Whether to reset to main menuforce_immediate_reset(boolean): Whether to force immediate resetdetails(table): Additional disconnect detailsmiscdata(any): Miscellaneous data
Debug and Development
SetDebugEntity(inst)
Status: stable
Description: Sets an entity as the current debug target.
Parameters:
inst(EntityScript): Entity to debug
Example:
-- Set player as debug target
SetDebugEntity(ThePlayer)
GetDebugEntity()
Status: stable
Description: Gets the current debug entity.
Returns:
- (EntityScript): Current debug entity
ExecuteConsoleCommand(fnstr, guid, x, z)
Status: stable
Description: Executes arbitrary Lua code in console context.
Parameters:
fnstr(string): Lua code to executeguid(number): Optional player GUID for contextx(number): Optional X position overridez(number): Optional Z position override
Error Handling
DisplayError(error)
Status: stable
Description: Displays an error dialog with appropriate options for recovery.
Parameters:
error(string): Error message to display
State Queries
InGamePlay()
Status: stable
Description: Checks if the game is currently in gameplay state (not in menus).
Returns:
- (boolean): True if in gameplay
Example:
if InGamePlay() then
-- Only process game logic when actually playing
ProcessPlayerActions()
end
IsMigrating()
Status: stable
Description: Checks if the game is currently migrating between servers.
Returns:
- (boolean): True if migrating
Related Modules
- Main: Game initialization and platform detection
- EntityScript: Entity scripting framework
- SaveIndex: Save file management
- Networking: Network communication
- Scheduler: Task scheduling system
- DebugHelpers: Development and debugging tools