LuaGameScript

class LuaGameScript - sort
help() Internal
set_game_state{game_finished=…, player_won=…, next_level=…, can_continue=…, victorious_force=…} Set scenario state.
get_entity_by_tag(tag) → LuaEntity
show_message_dialog{text=…, image=…, point_to=…, style=…} Show an in-game message dialog.
disable_tips_and_tricks() Disable showing tips and tricks.
is_demo() → boolean Is this the demo version of Factorio?
reload_script() Forces a reload of the scenario script from the original scenario location.
reload_mods() Forces a reload of all mods.
save_atlas() Saves the current configuration of Atlas to a file.
check_consistency() Run internal consistency checks.
regenerate_entity(entities) Regenerate autoplacement of some entities on all surfaces.
take_screenshot{player=…, by_player=…, surface=…, position=…, resolution=…, zoom=…, path=…, show_gui=…, show_entity_info=…, anti_alias=…, quality=…} Take a screenshot and save it to a file.
set_wait_for_screenshots_to_finish() Forces the screenshot saving system to wait until all queued screenshots have been written to disk.
take_technology_screenshot{force=…, path=…, by_player=…, selected_technology=…, skip_disabled=…, quality=…}
table_to_json(data) → string Convert a table to a JSON string
json_to_table(json) → Any Convert a JSON string to a table
write_file(filename, data, append, for_player) Write a string to a file.
remove_path(path) Remove file or directory.
remove_offline_players(players) Remove players who are currently not connected from the map.
force_crc() Force a CRC check.
create_force(force) → LuaForce Create a new force.
merge_forces(source, destination) Marks two forces to be merge together.
create_surface(name, settings) → LuaSurface Create a new surface
server_save(name) Instruct the server to save the map.
auto_save(name) Instruct the game to perform an auto-save.
delete_surface(surface) Deletes the given surface and all entities on it.
disable_replay() Disables replay saving for the current save file.
disable_tutorial_triggers() Disables tutorial triggers, that unlock new tutorials and show notices about unlocked tutorials.
direction_to_string(direction) Converts the given direction into the string version of the direction.
print(message, color) Print text to the chat console all players.
create_random_generator(seed) → LuaRandomGenerator Creates a deterministic standalone random generator with the given seed or if a seed is not provided the initial map seed is used.
check_prototype_translations() Goes over all items, entities, tiles, recipes, technologies among other things and logs if the locale is incorrect.
play_sound{path=…, position=…, volume_modifier=…} → boolean Plays a sound for every player in the game on every surface.
is_valid_sound_path(SoundPath) → boolean Checks if the given sound path is valid.
kick_player(PlayerSpecification, reason) Kicks the given player from this multiplayer game.
ban_player(PlayerSpecification, reason) Bans the given player from this multiplayer game.
unban_player(PlayerSpecification) Unbans the given player from this multiplayer game.
purge_player(PlayerSpecification) Purges the given players messages from the game.
mute_player(PlayerSpecification) Mutes the given player.
unmute_player(PlayerSpecification) Unmutes the given player.
count_pipe_groups() Counts how many distinct groups of pipes exist in the world.
is_multiplayer() → boolean Is the map loaded is multiplayer?
get_active_entities_count(surface) → uint Gets the number of entities that are active (updated each tick).
get_map_exchange_string() → string Gets the map exchange string for the map generation settings that were used to create this map.
parse_map_exchange_string(map_exchange_string) → MapExchangeStringData Convert a map exchange string to map gen settings and map settings.
get_train_stops(opts) → array of LuaEntity Gets train stops matching the given filters.
get_player(player) → LuaPlayer Gets the given player or returns nil if no player is found.
get_surface(surface) → LuaSurface Gets the given surface or returns nil if no surface is found.
create_profiler() → LuaProfiler Creates a LuaProfiler, which is used for measuring script performance.
evaluate_expression(expression, variables) → double Evaluate an expression, substituting variables as provided.
player :: LuaPlayer [R] The player typing at the console - nil in all other instances.
players :: custom dictionary uint or stringLuaPlayer [R]
map_settings :: MapSettings [R]
difficulty_settings :: DifficultySettings [R] Although it can be done; because different difficulties can have different technology or recipe trees it's not recommended to change difficulty settings mid-game.
difficulty :: defines.difficulty [R] Current scenario difficulty.
forces :: custom dictionary uint or stringLuaForce [R]
entity_prototypes :: custom dictionary stringLuaEntityPrototype [R]
item_prototypes :: custom dictionary stringLuaItemPrototype [R]
fluid_prototypes :: custom dictionary stringLuaFluidPrototype [R]
tile_prototypes :: custom dictionary stringLuaTilePrototype [R]
equipment_prototypes :: custom dictionary stringLuaEquipmentPrototype [R]
damage_prototypes :: custom dictionary stringLuaDamagePrototype [R]
virtual_signal_prototypes :: custom dictionary stringLuaVirtualSignalPrototype [R]
equipment_grid_prototypes :: custom dictionary stringLuaEquipmentGridPrototype [R]
recipe_prototypes :: custom dictionary stringLuaRecipePrototype [R]
technology_prototypes :: custom dictionary stringLuaTechnologyPrototype [R]
decorative_prototypes :: custom dictionary stringLuaDecorativePrototype [R]
autoplace_control_prototypes :: custom dictionary stringLuaAutoplaceControlPrototype [R]
noise_layer_prototypes :: custom dictionary stringLuaNoiseLayerPrototype [R]
mod_setting_prototypes :: custom dictionary stringLuaModSettingPrototype [R]
custom_input_prototypes :: custom dictionary stringLuaCustomInputPrototype [R]
ammo_category_prototypes :: custom dictionary stringLuaAmmoCategoryPrototype [R]
named_noise_expressions :: custom dictionary stringLuaNamedNoiseExpression [R]
item_subgroup_prototypes :: custom dictionary stringLuaGroup [R]
item_group_prototypes :: custom dictionary stringLuaGroup [R]
fuel_category_prototypes :: custom dictionary stringLuaFuelCategoryPrototype [R]
resource_category_prototypes :: custom dictionary stringLuaResourceCategoryPrototype [R]
achievement_prototypes :: custom dictionary stringLuaAchievementPrototype [R]
module_category_prototypes :: custom dictionary stringLuaModuleCategoryPrototype [R]
equipment_category_prototypes :: custom dictionary stringLuaEquipmentCategoryPrototype [R]
trivial_smoke_prototypes :: custom dictionary stringLuaTrivialSmokePrototype [R]
shortcut_prototypes :: custom dictionary stringLuaShortcutPrototype [R]
recipe_category_prototypes :: custom dictionary stringLuaRecipeCategoryPrototype [R]
styles :: custom dictionary stringstring [R] The styles that LuaGuiElement can use.
tick :: uint [R] Current map tick.
ticks_played :: uint [R] The number of ticks since this game was 'created'.
tick_paused :: boolean [RW] If the tick has been paused.
ticks_to_run :: uint [RW] The number of ticks to be run while the tick is paused.
finished :: boolean [R] Is the scenario finished?
speed :: float [RW] Speed to update the map at.
surfaces :: custom dictionary uint or stringLuaSurface [R]
active_mods :: dictionary stringstring [R] The active mods versions.
connected_players :: array of LuaPlayer [R] The online players This is primarily useful when you want to do some action against all online players.
permissions :: LuaPermissionGroups [R]
backer_names :: custom dictionary uintstring [R]
default_map_gen_settings :: MapGenSettings [R] The default map gen settings for this save.
enemy_has_vision_on_land_mines :: boolean [RW] Determines if enemy land mines are completely invisible or not.
autosave_enabled :: boolean [RW] True by default.
draw_resource_selection :: boolean [RW] True by default.
pollution_statistics :: LuaFlowStatistics [R] The pollution statistics for this map.

Main toplevel type, provides access to most of the API though its members. An instance of LuaGameScript is available as the global object named game.

help()

Internal

set_game_state{game_finished=…, player_won=…, next_level=…, can_continue=…, victorious_force=…}

Set scenario state.

Parameters
Table with the following fields:
get_entity_by_tag(tag) → LuaEntity

Parameters
tag :: string
show_message_dialog{text=…, image=…, point_to=…, style=…}

Show an in-game message dialog.

Parameters
Table with the following fields:
  • text :: LocalisedString: What the dialog should say
  • image :: string (optional): Path to an image to show on the dialog
  • point_to :: GuiArrowSpecification (optional): If specified, dialog will show an arrow pointing to this place. When not specified, the arrow will point to the player's position. (Use point_to={type="nowhere"} to remove the arrow entirely.) The dialog itself will be placed near the arrow's target.
  • style :: string (optional): The gui style to use for this speech bubble. Must be of type speech_bubble.
Note: Can only be used when the map contains exactly one player.
disable_tips_and_tricks()

Disable showing tips and tricks.

is_demo() → boolean

Is this the demo version of Factorio?

reload_script()

Forces a reload of the scenario script from the original scenario location.

Note: This disables the replay if replay is enabled.
reload_mods()

Forces a reload of all mods.

Note: This will act like saving and loading from the mod(s) perspective.
Note: This will do nothing if run in multiplayer.
Note: This disables the replay if replay is enabled.
save_atlas()

Saves the current configuration of Atlas to a file. This will result in huge file containing all of the game graphics moved to as small space as possible.

Note: Exists mainly for debugging reasons.
check_consistency()

Run internal consistency checks. Allegedly prints any errors it finds.

Note: Exists mainly for debugging reasons.
regenerate_entity(entities)

Regenerate autoplacement of some entities on all surfaces. This can be used to autoplace newly-added entities.

Parameters
entities :: string or array of string: Prototype names of entity or entities to autoplace.
Note: All specified entity prototypes must be autoplacable.
take_screenshot{player=…, by_player=…, surface=…, position=…, resolution=…, zoom=…, path=…, show_gui=…, show_entity_info=…, anti_alias=…, quality=…}

Take a screenshot and save it to a file.

Parameters
Table with the following fields:
  • player :: PlayerSpecification (optional)
  • by_player :: PlayerSpecification (optional): If defined, the screenshot will only be taken for this player.
  • surface :: SurfaceSpecification (optional): If defined, the screenshot will be taken on this surface.
  • position :: Position (optional): If defined, the screenshot will be centered on this position.
  • resolution :: Position (optional): Maximum allowed resolution is 16384x16384 (resp. 8192x8192 when anti_alias is true), but maximum recommended resolution is 4096x4096 (resp. 2048x2048).
  • zoom :: double (optional)
  • path :: string (optional): Path to save the screenshot in
  • show_gui :: boolean (optional): Include game GUI in the screenshot?
  • show_entity_info :: boolean (optional): Include entity info (alt-mode)?
  • anti_alias :: boolean (optional): Render in double resolution and scale down (including GUI)?
  • quality :: int (optional): The render quality if using jpg format (0-100 inclusive).
Note: If Factorio is running headless, this function will do nothing.
set_wait_for_screenshots_to_finish()

Forces the screenshot saving system to wait until all queued screenshots have been written to disk.

take_technology_screenshot{force=…, path=…, by_player=…, selected_technology=…, skip_disabled=…, quality=…}

Parameters
Table with the following fields:
  • force :: ForceSpecification (optional): The force to use. If not given the "player" force is used.
  • path :: string (optional): Path to save the screenshot in.
  • by_player :: PlayerSpecification (optional): If defined, the screenshot will only be taken for this player.
  • selected_technology :: TechnologySpecification (optional): The technology to highlight.
  • skip_disabled :: boolean (optional): If true, disabled technologies will be skipped. Their successors will be attached to the disabled technology's parents. Defaults to false.
  • quality :: int (optional): The render quality if using jpg format (0-100 inclusive).
table_to_json(data) → string

Convert a table to a JSON string

Parameters
data :: table
json_to_table(json) → Any

Convert a JSON string to a table

Parameters
json :: string: The string to convert
Return value
The returned object, or nil if the json was invalid.
write_file(filename, data, append, for_player)

Write a string to a file.

Parameters
filename :: string: Path to the file to write to.
data :: LocalisedString: File content
append :: boolean (optional): When true, this will append to the end of the file. Defaults to false, which will overwrite any pre-existing file with the new data.
for_player :: uint (optional): If given, the file will only be written for this player_index. 0 means only the server if one exists.
remove_path(path)

Remove file or directory. Given path is taken relative to the script output directory. Can be used to remove files created by LuaGameScript::write_file.

Parameters
path :: string: Path to remove, relative to the script output directory
remove_offline_players(players)

Remove players who are currently not connected from the map.

Parameters
players :: array of LuaPlayer or string (optional): List of players to remove. If not specified, remove all offline players.
force_crc()

Force a CRC check. Tells all peers to calculate their current map CRC; these CRC are then compared against each other. If a mismatch is detected, the game is desynced and some peers are forced to reconnect.

create_force(force) → LuaForce

Create a new force.

Parameters
force :: string: Name of the new force
Return value
The force that was just created
Note: The game currently supports a maximum of 64 forces, including the three built-in forces. This means that a maximum of 61 new forces may be created.
Note: Force names must be unique.
merge_forces(source, destination)

Marks two forces to be merge together. All entities in the source force will be reassigned to the target force. The source force will then be destroyed.

Parameters
source :: ForceSpecification: The force to remove
destination :: ForceSpecification: The force to reassign all entities to
Note: The three built-in forces -- player, enemy and neutral -- can't be destroyed. I.e. they can't be used as the source argument to this function.
Note: The source force is not merged until the end of the current tick or if called during the on_forces_merging event or on_forces_merged event the end of the next tick.
create_surface(name, settings) → LuaSurface

Create a new surface

Parameters
name :: string: Name of the new surface
settings :: MapGenSettings (optional): Map generation settings
Return value
The surface that was just created
Note: The game currently supports a maximum of 4,294,967,295 surfaces, including the default surface.
Note: Surface names must be unique
server_save(name)

Instruct the server to save the map.

Parameters
name :: string (optional): Save name. If not specified, writes into the currently-running save.
auto_save(name)

Instruct the game to perform an auto-save.

Parameters
name :: string (optional): The autosave name if any. Saves will be named _autosave-*name* when provided.
Note: Only the server will save in multiplayer. In single player a standard auto-save is triggered.
delete_surface(surface)

Deletes the given surface and all entities on it.

Parameters
surface :: string or LuaSurface: The surface to be deleted. Currently the primary surface (1, 'nauvis') cannot be deleted.
disable_replay()

Disables replay saving for the current save file. Once done there's no way to re-enable replay saving for the save file without loading an old save.

disable_tutorial_triggers()

Disables tutorial triggers, that unlock new tutorials and show notices about unlocked tutorials.

direction_to_string(direction)

Converts the given direction into the string version of the direction.

Parameters
direction :: defines.direction
print(message, color)

Print text to the chat console all players.

Parameters
message :: LocalisedString
color :: Color (optional)
create_random_generator(seed) → LuaRandomGenerator

Creates a deterministic standalone random generator with the given seed or if a seed is not provided the initial map seed is used.

Parameters
seed :: uint (optional)
Note: *Make sure* you actually want to use this over math.random(...) as this provides entirely different functionality over math.random(...).
check_prototype_translations()

Goes over all items, entities, tiles, recipes, technologies among other things and logs if the locale is incorrect.

Note: Also prints true/false if called from the console.
play_sound{path=…, position=…, volume_modifier=…} → boolean

Plays a sound for every player in the game on every surface.

Parameters
Table with the following fields:
  • path :: SoundPath: The sound to play
  • position :: Position (optional): Where the sound should be played. If not given it's played 'everywhere'.
  • volume_modifier :: double (optional): Must be between 0 and 1 inclusive.
is_valid_sound_path(SoundPath) → boolean

Checks if the given sound path is valid.

Parameters
kick_player(PlayerSpecification, reason)

Kicks the given player from this multiplayer game. Does nothing if this is a single player game or if the player running this isn't an admin.

Parameters
PlayerSpecification: The player to kick.
reason :: LocalisedString (optional): The reason given if any.
ban_player(PlayerSpecification, reason)

Bans the given player from this multiplayer game. Does nothing if this is a single player game of if the player running this isn't an admin.

Parameters
PlayerSpecification: The player to ban.
reason :: LocalisedString (optional): The reason given if any.
unban_player(PlayerSpecification)

Unbans the given player from this multiplayer game. Does nothing if this is a single player game of if the player running this isn't an admin.

Parameters
PlayerSpecification: The player to unban.
purge_player(PlayerSpecification)

Purges the given players messages from the game. Does nothing if the player running this isn't an admin.

Parameters
PlayerSpecification: The player to purge.
mute_player(PlayerSpecification)

Mutes the given player. Does nothing if the player running this isn't an admin.

Parameters
PlayerSpecification: The player to mute.
unmute_player(PlayerSpecification)

Unmutes the given player. Does nothing if the player running this isn't an admin.

Parameters
PlayerSpecification: The player to unmute.
count_pipe_groups()

Counts how many distinct groups of pipes exist in the world.

is_multiplayer() → boolean

Is the map loaded is multiplayer?

get_active_entities_count(surface) → uint

Gets the number of entities that are active (updated each tick).

Parameters
surface :: SurfaceSpecification (optional): If give, only the entities active on this surface are counted.
Note: This is very expensive to calculate.
get_map_exchange_string() → string

Gets the map exchange string for the map generation settings that were used to create this map.

parse_map_exchange_string(map_exchange_string) → MapExchangeStringData

Convert a map exchange string to map gen settings and map settings.

Parameters
map_exchange_string :: string
get_train_stops(opts) → array of LuaEntity

Gets train stops matching the given filters.

Parameters
opts (optional): Table with the following fields:
get_player(player) → LuaPlayer

Gets the given player or returns nil if no player is found.

Parameters
player :: uint or string: The player index or name.
Note: This is a shortcut for game.players[...]
get_surface(surface) → LuaSurface

Gets the given surface or returns nil if no surface is found.

Parameters
surface :: uint or string: The surface index or name.
Note: This is a shortcut for game.surfaces[...]
create_profiler() → LuaProfiler

Creates a LuaProfiler, which is used for measuring script performance.

Note: LuaProfiler cannot be serialized.
evaluate_expression(expression, variables) → double

Evaluate an expression, substituting variables as provided. For details on the formula, see the relevant page on the Factorio wiki.

Parameters
expression :: string: The expression to evaluate.
variables :: dictionary stringdouble (optional): Variables to be substituted.
Example
Calculate the number of research units required to unlock mining productivity level 10.
local formula = game.forces["player"].technologies["mining-productivity-4"].research_unit_count_formula
local units = game.evaluate_expression(formula, { L = 10, l = 10 })
player :: LuaPlayer [Read-only]

The player typing at the console - nil in all other instances. See LuaGameScript::players for accessing all players.

players :: custom dictionary uint or stringLuaPlayer [Read-only]

Note: This is a sparse table so pairs(), a known player index, or player name should be used to access elements.
map_settings :: MapSettings [Read-only]

difficulty_settings :: DifficultySettings [Read-only]

Although it can be done; because different difficulties can have different technology or recipe trees it's not recommended to change difficulty settings mid-game.

difficulty :: defines.difficulty [Read-only]

Current scenario difficulty.

forces :: custom dictionary uint or stringLuaForce [Read-only]

entity_prototypes :: custom dictionary stringLuaEntityPrototype [Read-only]

item_prototypes :: custom dictionary stringLuaItemPrototype [Read-only]

fluid_prototypes :: custom dictionary stringLuaFluidPrototype [Read-only]

tile_prototypes :: custom dictionary stringLuaTilePrototype [Read-only]

equipment_prototypes :: custom dictionary stringLuaEquipmentPrototype [Read-only]

damage_prototypes :: custom dictionary stringLuaDamagePrototype [Read-only]

virtual_signal_prototypes :: custom dictionary stringLuaVirtualSignalPrototype [Read-only]

equipment_grid_prototypes :: custom dictionary stringLuaEquipmentGridPrototype [Read-only]

recipe_prototypes :: custom dictionary stringLuaRecipePrototype [Read-only]

technology_prototypes :: custom dictionary stringLuaTechnologyPrototype [Read-only]

decorative_prototypes :: custom dictionary stringLuaDecorativePrototype [Read-only]

autoplace_control_prototypes :: custom dictionary stringLuaAutoplaceControlPrototype [Read-only]

noise_layer_prototypes :: custom dictionary stringLuaNoiseLayerPrototype [Read-only]

mod_setting_prototypes :: custom dictionary stringLuaModSettingPrototype [Read-only]

custom_input_prototypes :: custom dictionary stringLuaCustomInputPrototype [Read-only]

ammo_category_prototypes :: custom dictionary stringLuaAmmoCategoryPrototype [Read-only]

named_noise_expressions :: custom dictionary stringLuaNamedNoiseExpression [Read-only]

item_subgroup_prototypes :: custom dictionary stringLuaGroup [Read-only]

item_group_prototypes :: custom dictionary stringLuaGroup [Read-only]

fuel_category_prototypes :: custom dictionary stringLuaFuelCategoryPrototype [Read-only]

resource_category_prototypes :: custom dictionary stringLuaResourceCategoryPrototype [Read-only]

achievement_prototypes :: custom dictionary stringLuaAchievementPrototype [Read-only]

module_category_prototypes :: custom dictionary stringLuaModuleCategoryPrototype [Read-only]

equipment_category_prototypes :: custom dictionary stringLuaEquipmentCategoryPrototype [Read-only]

trivial_smoke_prototypes :: custom dictionary stringLuaTrivialSmokePrototype [Read-only]

shortcut_prototypes :: custom dictionary stringLuaShortcutPrototype [Read-only]

recipe_category_prototypes :: custom dictionary stringLuaRecipeCategoryPrototype [Read-only]

styles :: custom dictionary stringstring [Read-only]

The styles that LuaGuiElement can use. A mapping of style name to style type.

tick :: uint [Read-only]

Current map tick.

ticks_played :: uint [Read-only]

The number of ticks since this game was 'created'. A game is 'created' either by using "new game" or "new game from scenario".

Note: This differs over LuaGameScript::tick in that making a game from a scenario always starts with ticks_played value at 0 even if the scenario has its own level data where the LuaGameScript::tick is > 0.
Note: This value has no relation with LuaGameScript::tick and can be completely different values.
tick_paused :: boolean [Read-Write]

If the tick has been paused. This means that entity update has been paused.

ticks_to_run :: uint [Read-Write]

The number of ticks to be run while the tick is paused. When LuaGameScript::tick_paused is true, ticks_to_run behaves the following way: While this is > 0, the entity update is running normally and this value is decremented every tick. When this reaches 0, the game will pause again.

finished :: boolean [Read-only]

Is the scenario finished?

speed :: float [Read-Write]

Speed to update the map at. 1.0 is normal speed -- 60 UPS.

Note: Minimum value is 0.01.
surfaces :: custom dictionary uint or stringLuaSurface [Read-only]

active_mods :: dictionary stringstring [Read-only]

The active mods versions. The keys are mod names, the values are the versions.

Example
This will print the names and versions of active mods to player p's console.
for name, version in pairs(game.active_mods) do
  p.print(name .. " version " .. version)
end
connected_players :: array of LuaPlayer [Read-only]

The online players

This is primarily useful when you want to do some action against all online players.

Note: This does *not* index using player index. See LuaPlayer::index on each player instance for the player index.
permissions :: LuaPermissionGroups [Read-only]

backer_names :: custom dictionary uintstring [Read-only]

default_map_gen_settings :: MapGenSettings [Read-only]

The default map gen settings for this save.

enemy_has_vision_on_land_mines :: boolean [Read-Write]

Determines if enemy land mines are completely invisible or not.

autosave_enabled :: boolean [Read-Write]

True by default. Can be used to disable autosaving. Make sure to turn it back on soon after.

draw_resource_selection :: boolean [Read-Write]

True by default. Can be used to disable the highlighting of resource patches when they are hovered on the map.

pollution_statistics :: LuaFlowStatistics [Read-only]

The pollution statistics for this map.