Factorio Library documentation

This documentation is auto-generated by the Lua language server. These docs are greatly unpolished and lack any quality of life features whatsoever. This site will be replaced with a custom implementation in the future.

Array


DictLangRequest

player

LuaPlayer

tick

uint

DictTranslationRequest

dict

string

key

string

language

string

DictWipData


Dictionary

Localised strings identified by an internal key. Keys must be unique and language-agnostic.

table<string, LocalisedString>

EventData.on_player_dictionaries_ready

Called when a player's dictionaries are ready to be used. Handling this event is not required.

player_index

uint

EventData.on_player_language_changed

Called when a player's language changes. Handling this event is not required.

language

string

player_index

uint

Gui


GuiBase

build

function GuiBase.build(player: LuaPlayer)

Build the GUI for the given player.

change_mode

function GuiBase.change_mode(self: Gui, e: EventData.on_gui_checked_state_changed)

clear_completed

function GuiBase.clear_completed(self: Gui)

hide

function GuiBase.hide(self: Gui)

on_textfield_confirmed

function GuiBase.on_textfield_confirmed(self: Gui, e: EventData.on_gui_confirmed)

on_textfield_text_changed

function GuiBase.on_textfield_text_changed(_: any, e: EventData.on_gui_confirmed)

on_todo_toggled

function GuiBase.on_todo_toggled(self: Gui, e: EventData.on_gui_checked_state_changed)

on_window_closed

function GuiBase.on_window_closed(self: Gui)

show

function GuiBase.show(self: Gui)

toggle_pinned

function GuiBase.toggle_pinned(self: Gui)

toggle_visible

function GuiBase.toggle_visible(self: Gui)

update_footer

function GuiBase.update_footer(self: Gui)

GuiElemDef

A GUI element definition. This extends LuaGuiElement.add_param with several new attributes. Children may be defined in the array portion as an alternative to the children subtable.

GuiElemDefClass|GuiElemDefClass|GuiElemDefClass[][]

GuiElemDefClass

A GUI element definition. This extends LuaGuiElement.add_param with several new attributes. Children may be defined in the array portion as an alternative to the children subtable.

children

GuiElemDefClass|GuiElemDefClass[][]?

Children to add to this element

content

(GuiElemDefClass|GuiElemDefClass|GuiElemDefClass[][])?

To add a tab, specify tab and content and leave all other fields unset.

drag_target

string?

Set the element's drag target to the element whose name matches this string. The drag target must be present in the elems table.

elem_mods

LuaGuiElement?

Modifications to make to the element itself

handler

(fun(e: EventData.on_gui_checked_state_changed|EventData.on_gui_click|EventData.on_gui_closed|EventData.on_gui_confirmed|EventData.on_gui_elem_changed...(+7))|table<defines.events,...(too long).....(+7))>)?

Handler(s) to assign to this element

style_mods

LuaStyle?

Modifications to make to the element's style

tab

(GuiElemDefClass|GuiElemDefClass|GuiElemDefClass[][])?

To add a tab, specify tab and content and leave all other fields unset.


GuiElemHandler

A handler function to invoke when receiving GUI events for this element. Alternatively, separate handlers may be specified for different events.

fun(e: EventData.on_gui_checked_state_changed|EventData.on_gui_click|EventData.on_gui_closed|EventData.on_gui_confirmed|EventData.on_gui_elem_changed...(+7))|table<defines.events, ...(too long)...d...(+7))>

GuiEventData

Aggregate type of all possible GUI events.

EventData.on_gui_checked_state_changed|EventData.on_gui_click|EventData.on_gui_closed|EventData.on_gui_confirmed|EventData.on_gui_elem_changed...(+7)

IconSpecification

icon

string

icon_size

int

MigrationsTable

Migration code to run for specific mod version. A given function will run if the previous mod version is less than the given version.

Example

{
  ["1.0.1"] = function()
    global.foo = nil
    for _, player_table in pairs(global.players) do
      player_table.bar = "Lorem ipsum"
    end
  end,
  ["1.0.7"] = function()
    global.bar = {}
  end
  ["1.1.0"] = function(arg)
    global.foo = arg
  end
}

If the mod is upgraded from 1.0.4 to 1.1.0, then the migrations for 1.0.7 and 1.1.0 will be run.

table<string, fun(...any)>

Queue


RawDictionary


SpriteSpecification


TaskIdent

A unique identifier for a previously added task, used in on-tick-n.remove.

index

number

The tasks' index in the tick's Tasks table.

tick

number

The tick this task is scheduled for.


Tasks

A table of tasks.

Each task can be anything that is not a function, as specified in on-tick-n.add.

This is not an array, there may be gaps. Always use pairs to iterate this table.

Example

event.on_tick(function(e)
  for _, task in pairs(on_tick_n.retrieve(e.tick) or {}) do
    if task == "say_hi" then
      game.print("Hello there!")
    elseif task == "order_66" then
      for _, player in pairs(game.players) do
        player.die()
      end
    end
  end
end)
table<number, any>

TrainCompositionCounts

back_movers

number

The number of back-facing locomotives in the train.

front_movers

number

The number of front-facing locomotives in the train.

total

number

The total number of rolling stocks in the train.

wagons

number

The number of wagons in the train.


TranslatedDictionary

Translations are identified by their internal key. If the translation failed, then it will not be present. Locale fallback groups can be used if every key needs a guaranteed translation.

table<string, string>

flib_bounding_box

Utilities for manipulating bounding boxes. All functions support both the shorthand and explicit syntaxes for boxes and positions, and will preserve the syntax that was passed in. Boxes are considered immutable; all functions will return new boxes.

local flib_bounding_box = require("__flib__/bounding-box")

ceil

function flib_bounding_box.ceil(box: BoundingBox)
  -> BoundingBox

Return a new box expanded to the nearest tile edges.

center

function flib_bounding_box.center(box: BoundingBox)
  -> MapPosition

Calculate the centerpoint of the box.

contains_box

function flib_bounding_box.contains_box(box1: BoundingBox, box2: BoundingBox)
  -> boolean

Check if the first box contains the second box.

contains_position

function flib_bounding_box.contains_position(box: BoundingBox, pos: MapPosition)
  -> boolean

Check if the given box contains the given position.

ensure_explicit

function flib_bounding_box.ensure_explicit(box: BoundingBox)
  -> BoundingBox

Return the box in explicit form.

ensure_short

function flib_bounding_box.ensure_short(box: BoundingBox)
  -> BoundingBox

Return the box in shorthand form.

expand_to_contain_box

function flib_bounding_box.expand_to_contain_box(box1: BoundingBox, box2: BoundingBox)
  -> BoundingBox

Return a new box with initial dimensions box1, expanded to contain box2.

expand_to_contain_position

function flib_bounding_box.expand_to_contain_position(box: BoundingBox, pos: MapPosition)
  -> BoundingBox

Return a new box expanded to contain the given position.

floor

function flib_bounding_box.floor(box: BoundingBox)
  -> BoundingBox

Return a new box shrunk to the nearest tile edges.

from_dimensions

function flib_bounding_box.from_dimensions(center: MapPosition, width: number, height: number)
  -> BoundingBox

Create a new box from a centerpoint and dimensions.

from_position

function flib_bounding_box.from_position(pos: MapPosition, snap?: boolean)
  -> BoundingBox

Create a 1x1 box from the given position, optionally snapped to the containing tile edges.

height

function flib_bounding_box.height(box: BoundingBox)
  -> number

Calculate the height of the box.

intersects_box

function flib_bounding_box.intersects_box(box1: BoundingBox, box2: BoundingBox)
  -> boolean

Check if the first box intersects (overlaps) the second box.

move

function flib_bounding_box.move(box: BoundingBox, delta: MapPosition)
  -> BoundingBox

Return a new box with the same dimensions, moved by the given delta.

recenter_on

function flib_bounding_box.recenter_on(box: BoundingBox, pos: MapPosition)
  -> BoundingBox

Return a new box with the same dimensions centered on the given position.

resize

function flib_bounding_box.resize(box: BoundingBox, delta: number)
  -> BoundingBox

Return a new box grown or shrunk by the given delta. A positive delta will grow the box, a negative delta will shrink it.

rotate

function flib_bounding_box.rotate(box: BoundingBox)
  -> BoundingBox

Return a new box rotated 90 degrees about its center.

square

function flib_bounding_box.square(box: BoundingBox)
  -> BoundingBox

Return a new box expanded to create a square.

width

function flib_bounding_box.width(box: BoundingBox)
  -> number

Calculate the width of the box.


flib_data_util

Utilities for data stage prototype manipulation.

local flib_data_util = require("__flib__/data-util")

black_image

string

A black image, for use with tool backgrounds. This image is 1x1.

build_sprite

function flib_data_util.build_sprite(name?: string, position?: MapPosition, filename?: string, size?: Vector, mipmap_count?: number, mods?: table)
  -> SpriteSpecification

Build a sprite from constituent parts.

copy_prototype

function flib_data_util.copy_prototype(prototype: table, new_name: string, remove_icon?: boolean)
  -> table

Copy a prototype, assigning a new name and minable properties.

@param new_name — string

create_icons

function flib_data_util.create_icons(prototype: table, new_layers?: IconSpecification[])
  -> IconSpecification[]|nil

Copy prototype.icon/icons to a new fully defined icons array, optionally adding new icon layers.

Returns nil if the prototype's icons are incorrectly or incompletely defined.

dark_red_button_tileset

string

A dark red button tileset. Used for the flib_tool_button_dark_red style.

empty_image

string

An empty image. This image is 8x8 to facilitate usage with GUI styles.

get_energy_value

function flib_data_util.get_energy_value(energy_string: string)
  -> number?
  2. string?

Convert an energy string to base unit value + suffix.

Returns nil if energy_string is incorrectly formatted.

planner_base_image

string

A desaturated planner image. Tint this sprite to easily add your own planners.


flib_dictionary

Utilities for creating dictionaries of localised string translations.

local flib_dictionary = require("__flib__/dictionary-lite")

add

function flib_dictionary.add(dict_name: string, key: string, localised: LocalisedString)

Add the given string to the dictionary.

events

table

For use with __core__/lualib/event_handler. Pass flib_dictionary into handler.add_lib to handle all relevant events automatically.

get

function flib_dictionary.get(player_index: uint, dict_name: string)
  -> table<string, string>?

Get the specified dictionary for the player. Will return nil if the dictionary has not finished translating.

get_all

function flib_dictionary.get_all(player_index: uint)
  -> table<string, table<string, string>>?

Get all dictionaries for the player. Will return nil if the player's language has not finished translating.

handle_events

function flib_dictionary.handle_events()

Handle all non-bootstrap events with default event handlers. Will not overwrite any existing handlers. If you have custom handlers for on_tick, on_string_translated, or on_player_joined_game, ensure that you call the corresponding module lifecycle handler..

new

function flib_dictionary.new(name: string, initial_strings?: table<string, LocalisedString>)

Create a new dictionary. The name must be unique.

on_configuration_changed

function

on_init

function flib_dictionary.on_init()

on_player_dictionaries_ready

unknown

on_player_joined_game

function flib_dictionary.on_player_joined_game(e: EventData.on_player_joined_game)

on_player_language_changed

unknown

on_string_translated

function flib_dictionary.on_string_translated(e: EventData.on_string_translated)

on_tick

function flib_dictionary.on_tick()

flib_dictionary_global


flib_direction

Functions for working with directions.

local flib_direction = require("__flib__/direction")

east

integer

defines.direction.east

from_positions

function flib_direction.from_positions(source: MapPosition, target: MapPosition, round?: boolean)
  -> defines.direction

Calculate the direction of travel from the source to the target.

@param round — If true, round to the nearest defines.direction.

next

function flib_direction.next(direction: defines.direction, eight_way?: boolean)
  -> defines.direction

Calculate the next four-way or eight-way direction.

north

integer

defines.direction.north

northeast

integer

defines.direction.northeast

northwest

integer

defines.direction.northwest

opposite

function flib_direction.opposite(direction: defines.direction)
  -> defines.direction

Calculate the opposite direction.

previous

function flib_direction.previous(direction: defines.direction, eight_way?: boolean)
  -> defines.direction

Calculate the previous four-way or eight-way direction.

south

integer

defines.direction.south

southeast

integer

defines.direction.southeast

southwest

integer

defines.direction.southwest

to_orientation

function flib_direction.to_orientation(direction: defines.direction)
  -> RealOrientation

Calculate an orientation from a direction.

to_vector

function flib_direction.to_vector(direction: defines.direction, distance?: number)
  -> MapPosition

Calculate a vector from a direction.

@param distance — default: 1

to_vector_2d

function flib_direction.to_vector_2d(direction: defines.direction, longitudinal: number, orthogonal: number)
  -> MapPosition?

Calculate a two-dimensional vector from a cardinal direction.

@param longitudinal — Distance to move in the specified direction.

@param orthogonal — Distance to move perpendicular to the specified direction. A negative distance will move "left" and a positive distance will move "right" from the perspective of the direction.

west

integer

defines.direction.west


flib_format

Various string formatting functions.

local flib_format = require("__flib__/format")

number

function flib_format.number(amount: number, append_suffix?: boolean, fixed_precision?: number)
  -> string

Format a number for display, adding commas and an optional SI suffix. Specify fixed_precision to display the number with the given width, adjusting precision as necessary.

time

function flib_format.time(tick?: uint, include_leading_zeroes?: boolean)
  -> string

Convert the given tick or game.tick into "[hh:]mm:ss" format.


flib_gui

Utilities for building GUIs and handling GUI events.

local flib_gui = require("__flib__/gui-lite")

add

function flib_gui.add(parent: LuaGuiElement, def: GuiElemDefClass|GuiElemDefClass|GuiElemDefClass[][], elems?: table<string, LuaGuiElement>)
  -> elems: table<string, LuaGuiElement>
  2. first: LuaGuiElement

Add a new child or children to the given GUI element.

@param def — Can be a single element, or an array of elements.

@param elems — Optional initial elems table.

@return elems — Elements with names will be collected into this table.

@return first — The element that was created first; the "top level" element.

add_handlers

function flib_gui.add_handlers(new_handlers: table<string, fun(e: EventData.on_gui_checked_state_changed|EventData.on_gui_click|EventData.on_gui_closed|EventData.on_gui_confirmed|EventData.on_gui_elem_changed...(+7))>, wrapper?: fun(e: EventData.on_gui_checked_state_changed|EventData.on_gui_click|EventData.on_gui_closed|EventData.on_gui_confirmed|EventData.on_gui_elem_changed...(+7), handler: function))

Add the given handler functions to the registry for use with flib_gui.add. Each handler must have a unique name. If a wrapper function is provided, it will be called instead, and will receive the event data and handler. The wrapper can be used to execute logic or gather data common to all handler functions for this GUI.

dispatch

function flib_gui.dispatch(e: EventData.on_gui_checked_state_changed|EventData.on_gui_click|EventData.on_gui_closed|EventData.on_gui_confirmed|EventData.on_gui_elem_changed...(+7))
  -> handled: boolean

Dispatch the handler associated with this event and GUI element. The handler must have been added using flib_gui.add_handlers.

@return handled — True if an event handler was called.

events

table

For use with __core__/lualib/event_handler. Pass flib_gui into handler.add_lib to handle all GUI events automatically.

handle_events

function flib_gui.handle_events()

Handle all GUI events with flib_gui.dispatch. Will not overwrite any existing event handlers.


flib_math

Extension of the Lua 5.2 math library.

local flib_math = require("__flib__/math")

ceil_to

function flib_math.ceil_to(num: number, num_decimals: number)
  -> number

Ceil a number to N decimal places. Use math.ceil directly if no decimals are needed.

ceiled

function flib_math.ceiled(num: number, divisor?: number)
  -> number|unknown

Ceil a number to the nearest multiple of divisor.

@param divisornum will be ceiled to the nearest multiple of divisor (default: 1).

clamp

function flib_math.clamp(x: number, min?: number, max?: number)
  -> number

Clamp a number between minimum and maximum values.

@param min — default 0

@param max — default 1

deg_to_rad

number

Multiply by degrees to convert to radians.

local rad = 1 x flib_math.deg_to_rad -- 0.0174533

floor_to

function flib_math.floor_to(num: number, num_decimals: number)
  -> number

Floor a number to N decimal places. Use math.floor directly if no decimals are needed.

floored

function flib_math.floored(num: number, divisor?: number)
  -> number|unknown

Floor a number to the nearest multiple of divisor.

@param divisornum will be floored to the nearest multiple of divisor (default: 1).

lerp

function flib_math.lerp(num1: number, num2: number, amount: number)
  -> number

Linearly interpolate between num1 and num2 by amount.

The parameter amount is clamped between 0 and 1.

When amount = 0, returns num1.

When amount = 1, returns num2.

When amount = 0.5, returns the midpoint of num1 and num2.

max_double

number

max_int

integer

2,147,483,647

max_int16

integer

32,767

max_int53

integer

9,007,199,254,740,991

max_int8

integer

127

max_uint

integer

4,294,967,295

max_uint16

integer

65,535

max_uint8

integer

255

maximum

function flib_math.maximum(set: number[])
  -> number

Returns the argument with the maximum value from a set.

mean

function flib_math.mean(set: number[])
  -> number

Calculate the mean (average) of a set of numbers.

midrange

function flib_math.midrange(set: number[])
  -> number

Calculate the mean of the largest and the smallest values in a set of numbers.

min_double

number

min_int

integer

-2,147,483,648

min_int16

integer

-32,768

min_int53

integer

-9,007,199,254,740,992

min_int8

integer

-128

minimum

function flib_math.minimum(set: number[])
  -> number

Returns the argument with the minimum value from a set.

rad_to_deg

number

Multiply by radians to convert to degrees.

local deg = 1 x flib_math.rad_to_deg -- 57.2958

range

function flib_math.range(set: number[])
  -> number

Calculate the range in a set of numbers.

round

function flib_math.round(num: number, divisor?: number)
  -> number

Round a number to the nearest multiple of divisor. Defaults to nearest integer if divisor is not provided.

From lua-users.org.

@param divisornum will be rounded to the nearest multiple of divisor (default: 1).

round_to

function flib_math.round_to(num: number, num_decimals: number)
  -> number

Round a number to the nearest N decimal places.

From lua-users.org.

sign

function flib_math.sign(x: number)
  -> number

Return the signedness of a number as a multiplier.

sum

function flib_math.sum(set: number[])
  -> number

Calculate the sum of a set of numbers.


flib_migration

Mod migration and version comparison functions.

local flib_migration = require("__flib__/migration")

format_version

function flib_migration.format_version(version: string, format?: string)
  -> string?

Normalize version strings for easy comparison.

Examples

migration.format_version("1.10.1234", "%04d")
migration.format_version("3", "%02d")

@param format — default: %02d

handle_on_configuration_changed

function flib_migration.handle_on_configuration_changed(version_migrations?: table<string, fun(...any)>, generic_handler?: fun(e: ConfigurationChangedData))

Handle on_configuration_changed with the given generic and version-specific migrations. Will override any existing on_configuration_changed event handler. Both arguments are optional.

is_newer_version

function flib_migration.is_newer_version(old_version: string, current_version: string, format?: string)
  -> boolean?

Check if current_version is newer than old_version.

@param format — default: %02d

on_config_changed

function flib_migration.on_config_changed(e: ConfigurationChangedData, migrations?: table<string, fun(...any)>, mod_name?: string, ...any)
  -> run_generic_micrations: boolean

Determine if migrations need to be run for this mod, then run them if needed.

Examples

script.on_configuration_changed(function(e)
  if migration.on_config_changed(e, migrations) then
    -- Run generic (non-init) migrations
    rebuild_prototype_data()
  end
end

@param mod_name — The mod to check against. Defaults to the current mod.

@param ... — All additional arguments will be passed to each function within migrations.

run

function flib_migration.run(old_version: string, migrations: table<string, fun(...any)>, format?: string, ...any)

Run migrations against the given version.

@param format — default: %02d

@param ... — All additional arguments will be passed to each function within migrations.


flib_on_tick_n

Schedule tasks to be executed later.

local flib_on_tick_n = require("__flib__/on-tick-n")

add

function flib_on_tick_n.add(tick: number, task: any)
  -> ident: TaskIdent

Add a task to execute on the given tick.

@param task — The data representing this task. This can be anything except for a function.

@return ident — An identifier for the task. Save this if you might remove the task before execution.

init

function flib_on_tick_n.init()

Initialize the module's script data table.

Must be called at the beginning of on_init. Can also be used to delete all current tasks.

remove

function flib_on_tick_n.remove(ident: TaskIdent)
  -> boolean

Remove a scheduled task.

@param ident — The identifier object for the task, as returned from on-tick-n.add.

retrieve

function flib_on_tick_n.retrieve(tick: number)
  -> table<number, any>?

Retrieve the tasks for the given tick, if any.

Must be called during on_tick.


flib_orientation

Functions for working with orientations.

local flib_orientation = require("__flib__/orientation")

add

function flib_orientation.add(orientation1: number, orientation2: number)
  -> the: number

Add two orientations together.

@return the — orientations added together

east

number

north

number

northeast

number

northwest

number

opposite

function flib_orientation.opposite(orientation: number)
  -> number

Returns the opposite orientation.

south

number

southeast

number

southwest

number

to_direction

function flib_orientation.to_direction(orientation: number, eight_way: boolean)
  -> defines.direction

Returns a 4way or 8way direction from an orientation.

west

number

flib_position

Utilities for manipulating positions. All functions support both the shorthand and explicit syntaxes and will preserve the syntax that was passed in.

local flib_position = require("__flib__/position")

add

function flib_position.add(pos1: <P>, pos2: <P>)
  -> <P>

Add two positions.

ceil

function flib_position.ceil(pos: <P>)
  -> <P>

Ceil the given position.

distance

function flib_position.distance(pos1: <P>, pos2: <P>)
  -> number

Calculate the distance between two positions.

distance_squared

function flib_position.distance_squared(pos1: <P>, pos2: <P>)
  -> number

Calculate the squared distance between two positions.

div

function flib_position.div(pos1: <P>, pos2: <P>)
  -> <P>

Divide two positions.

ensure_explicit

function flib_position.ensure_explicit(pos: <P>)
  -> <P>

Return the position in explicit form.

ensure_short

function flib_position.ensure_short(pos: <P>)
  -> <P>

Return the position in shorthand form.

eq

function flib_position.eq(pos1: <P>, pos2: <P>)
  -> boolean

Test if two positions are equal.

floor

function flib_position.floor(pos: <P>)
  -> <P>

Floor the given position.

from_chunk

function flib_position.from_chunk(pos: ChunkPosition)
  -> TilePosition

Convert a ChunkPosition into a TilePosition by multiplying by 32.

le

function flib_position.le(pos1: <P>, pos2: <P>)
  -> boolean

Test if pos1 is less than or equal to pos2.

lt

function flib_position.lt(pos1: <P>, pos2: <P>)
  -> boolean

Test if pos1 is less than pos2.

mod

function flib_position.mod(pos1: <P>, pos2: <P>)
  -> <P>

Take the remainder (modulus) of two positions.

mul

function flib_position.mul(pos1: <P>, pos2: <P>)
  -> <P>

Multiply two positions.

pow

function flib_position.pow(pos1: <P>, pos2: <P>)
  -> <P>

Take the power of two positions. pos1^pos2.

sub

function flib_position.sub(pos1: <P>, pos2: <P>)
  -> <P>

Subtract two positions.

to_chunk

function flib_position.to_chunk(pos: MapPosition|TilePosition)
  -> ChunkPosition

Convert a MapPosition or TilePosition into a ChunkPosition by dividing by 32 and flooring.

to_tile

function flib_position.to_tile(pos: MapPosition)
  -> TilePosition

Convert a MapPosition into a TilePosition by flooring.


flib_queue

Lua queue implementation.

Based on "Queues and Double Queues" from Programming in Lua.

local flib_queue = require("__flib__/queue")

iter

function flib_queue.iter(self: Queue<<T>>)
  -> fun(self: Queue<<T>>, index: integer):<T>

Iterate over a queue's elements from the beginning to the end.

Example

local my_queue = queue.new()
for i = 1, 10 do
  queue.push_back(my_queue, 1)
end

-- 1 2 3 4 5 6 7 8 9 10
for num in queue.iter(my_queue) do
  log(i)
end

iter_left

function

iter_rev

function flib_queue.iter_rev(self: Queue<<T>>)
  -> fun(self: Queue<<T>>, index: integer):<T>

Iterate over a queue's elements from the end to the beginning.

Example

local my_queue = queue.new()
for i = 1, 10 do
  queue.push_back(my_queue, 1)
end

-- 10 9 8 7 6 5 4 3 2 1
for num in queue.iter_rev(my_queue) do
  log(i)
end

iter_right

function

length

function flib_queue.length(self: Queue<<T>>)
  -> number

Get the length of the queue.

new

function flib_queue.new()
  -> Queue

Create a new queue.

pop_back

function flib_queue.pop_back(self: Queue<<T>>)
  -> <T>?

Retrieve an element from the back of the queue.

pop_front

function flib_queue.pop_front(self: Queue<<T>>)
  -> <T>?

Retrieve an element from the front of the queue.

pop_left

function

pop_right

function

push_back

function flib_queue.push_back(self: Queue<<T>>, value: <T>)

Push an element into the back of the queue.

push_front

function flib_queue.push_front(self: Queue<<T>>, value: <T>)

Push an element into the front of the queue.

push_left

function

push_right

function

flib_table

Extension of the Lua 5.2 table library.

NOTE: Several functions in this module will only work with arrays, which are tables with sequentially numbered keys. All table functions will work with arrays as well, but array functions will not work with tables.

local flib_table: = require("__flib__/table")

array_copy

function flib_table.array_copy(arr: Array)
  -> Array

Shallow copy an array's values into a new array.

This function is optimized specifically for arrays, and should be used in place of table.shallow_copy for arrays.

array_merge

function flib_table.array_merge(arrays: Array)
  -> Array

Merge all of the given arrays into a single array.

@param arrays — An array of arrays to merge.

deep_compare

function flib_table.deep_compare(tbl1: table, tbl2: table)
  -> boolean

Recursively compare two tables for inner equality.

Does not compare metatables.

deep_copy

function flib_table.deep_copy(tbl: <T>)
  -> <T>

Recursively copy the contents of a table into a new table.

Does not create new copies of Factorio objects.

@param tbl — The table to make a copy of.

deep_merge

function flib_table.deep_merge(tables: Array)
  -> table

Recursively merge two or more tables.

Values from earlier tables are overwritten by values from later tables, unless both values are tables, in which case they are recursively merged.

Non-merged tables are deep-copied, so the result is brand-new.

Examples

local tbl = {foo = "bar"}
log(tbl.foo) -- logs "bar"
log (tbl.bar) -- errors (key is nil)
tbl = table.merge{tbl, {foo = "baz", set = 3}}
log(tbl.foo) -- logs "baz"
log(tbl.set) -- logs "3"

@param tables — An array of tables to merge.

filter

function flib_table.filter(tbl: table<<K>, <V>>, filter: fun(value: <V>, key: <K>):boolean, array_insert?: boolean)
  -> table<<K>, <V>>

Create a filtered version of a table based on the results of a filter function.

Calls filter(value, key) on each element in the table, returning a new table with only pairs for which filter returned a truthy value.

Examples

local tbl = {1, 2, 3, 4, 5, 6}
local just_evens = table.filter(tbl, function(v) return v % 2 == 0 end) -- {[2] = 2, [4] = 4, [6] = 6}
local just_evens_arr = table.filter(tbl, function(v) return v % 2 == 0 end, true) -- {2, 4, 6}

@param array_insert — If true, the result will be constructed as an array of values that matched the filter. Key references will be lost.

find

function flib_table.find(tbl: table<<K>, <V>>, value: <V>)
  -> key: <K>?

Find and return the first key containing the given value.

Examples

local tbl = {"foo", "bar"}
local key_of_foo = table.find(tbl, "foo") -- 1
local key_of_baz = table.find(tbl, "baz") -- nil

@param tbl — The table to search.

@param value — The value to match. Must have an eq metamethod set, otherwise will error.

@return key — The first key corresponding to value, if any.

for_each

function flib_table.for_each(tbl: table<<K>, <V>>, callback: fun(value: <V>, key: <K>):boolean)
  -> Whether: boolean

Call the given function for each item in the table, and abort if the function returns truthy.

Calls callback(value, key) for each item in the table, and immediately ceases iteration if the callback returns truthy.

Examples

local tbl = {1, 2, 3, 4, 5}
-- Run a function for each item (identical to a standard FOR loop)
table.for_each(tbl, function(v) game.print(v) end)
-- Determine if any value in the table passes the test
local value_is_even = table.for_each(tbl, function(v) return v % 2 == 0 end)
-- Determine if ALL values in the table pass the test (invert the test result and function return)
local all_values_less_than_six = not table.for_each(tbl, function(v) return not (v < 6) end)

@param callback — Receives value and key as parameters.

@return Whether — the callback returned truthy for any one item, and thus halted iteration.

for_n_of

function flib_table.for_n_of(tbl: table<<K>, <V>>, from_k: <K>, n: number, callback: fun(value: <V>, key: <K>):<C>, boolean, boolean, _next?: fun(tbl: table<<K>, <V>>, from_k: <K>):<K>, <V>)
  -> next_key: <K>?
  2. results: table<<K>, <C>>
  3. reached_end: boolean

Call the given function on a set number of items in a table, returning the next starting key.

Calls callback(value, key) over n items from tbl, starting after from_k.

The first return value of each invocation of callback will be collected and returned in a table keyed by the current item's key.

The second return value of callback is a flag requesting deletion of the current item.

The third return value of callback is a flag requesting that the iteration be immediately aborted. Use this flag to early return on some condition in callback. When aborted, for_n_of will return the previous key as from_k, so the next call to for_n_of will restart on the key that was aborted (unless it was also deleted).

DO NOT delete entires from tbl from within callback, this will break the iteration. Use the deletion flag instead.

Examples

local extremely_large_table = {
  [1000] = 1,
  [999] = 2,
  [998] = 3,
  ...,
  [2] = 999,
  [1] = 1000,
}
event.on_tick(function()
  global.from_k = table.for_n_of(extremely_large_table, global.from_k, 10, function(v) game.print(v) end)
end)

@param tbl — The table to iterate over.

@param from_k — The key to start iteration at, or nil to start at the beginning of tbl. If the key does not exist in tbl, it will be treated as nil, unless a custom _next function is used.

@param n — The number of items to iterate.

@param callback — Receives value and key as parameters.

@param _next — A custom next() function. If not provided, the default next() will be used.

@return next_key — Where the iteration ended. Can be any valid table key, or nil. Pass this as from_k in the next call to for_n_of for tbl.

@return results — The results compiled from the first return of callback.

@return reached_end — Whether or not the end of the table was reached on this iteration.

get_or_insert

function flib_table.get_or_insert(table: table<<K>, <V>>, key: <K>, default_value: <V>)
  -> <V>

Retrieve the value at the key, or insert the default value.

invert

function flib_table.invert(tbl: table<<K>, <V>>)
  -> table<<V>, <K>>

Invert the given table such that [value] = key, returning a new table.

Non-unique values are overwritten based on the ordering from pairs().

Examples

local tbl = {"foo", "bar", "baz", set = "baz"}
local inverted = table.invert(tbl) -- {foo = 1, bar = 2, baz = "set"}

map

function flib_table.map(tbl: table<<K>, <V>>, mapper: fun(value: <V>, key: <V>):<N>?)
  -> table<<K>, <N>>

Create a transformed table using the output of a mapper function.

Calls mapper(value, key) on each element in the table, using the return as the new value for the key.

Examples

local tbl = {1, 2, 3, 4, 5}
local tbl_times_ten = table.map(tbl, function(v) return v * 10 end) -- {10, 20, 30, 40, 50}

partial_sort

function flib_table.partial_sort(arr: Array<<V>>, from_index?: number, iterations: number, comp: fun(a: <V>, b: <V>))
  -> next_index: number?

Partially sort an array.

This function utilizes insertion sort, which is extremely inefficient with large data sets. However, you can spread the sorting over multiple ticks, reducing the performance impact. Only use this function if table.sort is too slow.

@param from_index — The index to start iteration at (inclusive). Pass nil or a number less than 2 to begin at the start of the array.

@param iterations — The number of iterations to perform. Higher is more performance-heavy. This number should be adjusted based on the performance impact of the custom comp function (if any) and the size of the array.

@param comp — A comparison function for sorting. Must return truthy if a < b.

@return next_index — The index to start the next iteration at, or nil if the end was reached.

reduce

function flib_table.reduce(tbl: table<<K>, <V>>, reducer: fun(acc: <R>, value: <V>, key: <K>):<R>, initial_value?: <R>)
  -> <R>

"Reduce" a table's values into a single output value, using the results of a reducer function.

Calls reducer(accumulator, value, key) on each element in the table, returning a single accumulated output value.

Examples

local tbl = {10, 20, 30, 40, 50}
local sum = table.reduce(tbl, function(acc, v) return acc + v end)
local sum_minus_ten = table.reduce(tbl, function(acc, v) return acc + v end, -10)

@param initial_value — The initial value for the accumulator. If not provided or is falsy, the first value in the table will be used as the initial accumulator value and skipped as key. Calling reduce() on an empty table without an initial_value will cause a crash.

retrieve

function

shallow_copy

function flib_table.shallow_copy(tbl: <T>, use_rawset?: boolean)
  -> The: <T>

Shallowly copy the contents of a table into a new table.

The parent table will have a new table reference, but any subtables within it will still have the same table reference.

Does not copy metatables.

@param use_rawset — Use rawset to set the values (ignores metamethods).

@return The — copied table.

shallow_merge

function flib_table.shallow_merge(tables: table[])
  -> table

Shallowly merge two or more tables. Unlike table.deep_merge, this will only combine the top level of the tables.

size

function

Retrieve the size of a table.

Uses Factorio's built-in table_size function.

slice

function flib_table.slice(arr: Array<<V>>, start?: number, stop?: number)
  -> A: Array<<V>>

Retrieve a shallow copy of a portion of an array, selected from start to end inclusive.

The original array will not be modified.

Examples

local arr = {10, 20, 30, 40, 50, 60, 70, 80, 90}
local sliced = table.slice(arr, 3, 7) -- {30, 40, 50, 60, 70}
log(serpent.line(arr)) -- {10, 20, 30, 40, 50, 60, 70, 80, 90} (unchanged)

@param start — default: 1

@param stop — Stop at this index. If zero or negative, will stop n items from the end of the array (default: #arr).

@return A — new array with the copied values.

splice

function flib_table.splice(arr: Array<<V>>, start: number, stop?: number)
  -> A: Array<<V>>

Extract a portion of an array, selected from start to end inclusive.

The original array will be modified.

Examples

local arr = {10, 20, 30, 40, 50, 60, 70, 80, 90}
local spliced = table.splice(arr, 3, 7) -- {30, 40, 50, 60, 70}
log(serpent.line(arr)) -- {10, 20, 80, 90} (values were removed)

@param start — default: 1

@param stop — Stop at this index. If zero or negative, will stop n items from the end of the array (default: #arr).

@return A — new array with the extracted values.


flib_train

Functions for working with trains.

local flib_train = require("__flib__/train")

get_backer_name

function flib_train.get_backer_name(train: LuaTrain)
  -> backer_name: string?

Get the backer_name of the main locomotive in a given train.

@return backer_name — The backer_name of the primary locomotive or nil when no locomotive was found

get_composition_string

function flib_train.get_composition_string(train: LuaTrain)
  -> composition: string?
  2. TrainCompositionCounts?

Create a string representing train composition, and return a count of locomotives and wagons in the train.

@return composition — The composition string, or nil if the train was invalid.

@return

get_main_locomotive

function flib_train.get_main_locomotive(train: LuaTrain)
  -> locomotive: LuaEntity?

Get the main locomotive in a given train.

@return locomotive — The primary locomotive entity or nil when no locomotive was found

open_gui

function flib_train.open_gui(player_index: number, train: LuaTrain)
  -> boolean

Open train GUI for one player.

@returntrue if the GUI was opened.

rotate_carriage

function flib_train.rotate_carriage(entity: LuaEntity)
  -> rotated: boolean

Rotate a single carriage of a train.

@return rotatedtrue when rotation was successful.