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

A player in the game. Pay attention that a player may or may not have a character, which is the LuaEntity of the little guy running around the world doing things.

View documentation

tick

integer

32 bit unsigned integer. Ranges from 0 to 4 294 967 295, or [0, 2^32-1]


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, boolean|string|number|LuaObject|boolean|string|number|LuaObject|boolean|string|number|LuaObject|nil[]...(+1)[]...(+1)>

EventData.on_player_dictionaries_ready

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

player_index

integer

32 bit unsigned integer. Ranges from 0 to 4 294 967 295, or [0, 2^32-1]


EventData.on_player_language_changed

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

language

string

player_index

integer

32 bit unsigned integer. Ranges from 0 to 4 294 967 295, or [0, 2^32-1]


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[]|GuiElemDef|GuiElemDefClass[][]|GuiElemDef|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|GuiElemDefClass[]|GuiElemDef|GuiElemDefClass[][]|GuiElemDef|GuiElemDefClass[][]?

Children to add to this element

content

(GuiElemDefClass|GuiElemDefClass|GuiElemDefClass[]|GuiElemDef|GuiElemDefClass[][]|GuiElemDefClass|GuiElemDefClass|GuiElemDefClass[]|GuiElemDef|GuiElemDefClass[][]|GuiElemDef|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[]|GuiElemDef|GuiElemDefClass[][]|GuiElemDefClass|GuiElemDefClass|GuiElemDefClass[]|GuiElemDef|GuiElemDefClass[][]|GuiElemDef|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

integer

32 bit signed integer. Ranges from -2 147 483 648 to 2 147 483 647, or [-2^31, 2^31-1]


LuaUnit

table
table

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>

Test_ceiled

function Test_ceiled()
function Test_ceiled()

Test_clamp

function Test_clamp()
function Test_clamp()

Test_degrees

function Test_degrees()
function Test_degrees()

Test_floored

function Test_floored()
function Test_floored()

Test_lerp

function Test_lerp()
function Test_lerp()

Test_maximum

function Test_maximum()
function Test_maximum()

Test_mean

function Test_mean()
function Test_mean()

Test_midrange

function Test_midrange()
function Test_midrange()

Test_minimum

function Test_minimum()
function Test_minimum()

Test_radians

function Test_radians()
function Test_radians()

Test_range

function Test_range()
function Test_range()

Test_round

function Test_round()
function Test_round()

Test_sign

function Test_sign()
function Test_sign()

Test_sum

function Test_sum()
function Test_sum()

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>

_FAKETORIO_globals

boolean
boolean

_FAKETORIO_searcher

boolean
boolean

_G

A global variable (not a function) that holds the global environment (see §2.2). Lua itself does not use this variable; changing its value does not affect any environment, nor vice versa.

View documents

_G

_VERSION

A global variable (not a function) that holds a string containing the running Lua version.

View documents

string

__object_name

object_name:
| "LuaAISettings"
| "LuaAccumulatorControlBehavior"
| "LuaAchievementPrototype"
| "LuaAmmoCategoryPrototype"
| "LuaArithmeticCombinatorControlBehavior"
| "LuaAutoplaceControlPrototype"
| "LuaBootstrap"
| "LuaBurner"
| "LuaBurnerPrototype"
| "LuaChunkIterator"
| "LuaCircuitNetwork"
| "LuaCommandProcessor"
| "LuaConstantCombinatorControlBehavior"
| "LuaContainerControlBehavior"
| "LuaCustomChartTag"
| "LuaCustomInputPrototype"
| "LuaCustomTable"
| "LuaDamagePrototype"
| "LuaDeciderCombinatorControlBehavior"
| "LuaDecorativePrototype"
| "LuaElectricEnergySourcePrototype"
| "LuaEntity"
| "LuaEntityPrototype"
| "LuaEquipment"
| "LuaEquipmentCategoryPrototype"
| "LuaEquipmentGrid"
| "LuaEquipmentGridPrototype"
| "LuaEquipmentPrototype"
| "LuaFlowStatistics"
| "LuaFluidBox"
| "LuaFluidBoxPrototype"
| "LuaFluidEnergySourcePrototype"
| "LuaFluidPrototype"
| "LuaFontPrototype"
| "LuaForce"
| "LuaFuelCategoryPrototype"
| "LuaGameScript"
| "LuaGroup"
| "LuaGui"
| "LuaGuiElement"
| "LuaHeatBufferPrototype"
| "LuaHeatEnergySourcePrototype"
| "LuaInserterControlBehavior"
| "LuaInventory"
| "LuaItemPrototype"
| "LuaItemStack"
| "LuaLampControlBehavior"
| "LuaLazyLoadedValue"
| "LuaLogisticCell"
| "LuaLogisticContainerControlBehavior"
| "LuaLogisticNetwork"
| "LuaLogisticPoint"
| "LuaMiningDrillControlBehavior"
| "LuaModSettingPrototype"
| "LuaModuleCategoryPrototype"
| "LuaNamedNoiseExpression"
| "LuaNoiseLayerPrototype"
| "LuaParticlePrototype"
| "LuaPermissionGroup"
| "LuaPermissionGroups"
| "LuaPlayer"
| "LuaProfiler"
| "LuaProgrammableSpeakerControlBehavior"
| "LuaRCON"
| "LuaRailChainSignalControlBehavior"
| "LuaRailPath"
| "LuaRailSignalControlBehavior"
| "LuaRandomGenerator"
| "LuaRecipe"
| "LuaRecipeCategoryPrototype"
| "LuaRecipePrototype"
| "LuaRemote"
| "LuaRendering"
| "LuaResourceCategoryPrototype"
| "LuaRoboportControlBehavior"
| "LuaSettings"
| "LuaShortcutPrototype"
| "LuaStorageTankControlBehavior"
| "LuaStyle"
| "LuaSurface"
| "LuaTechnology"
| "LuaTechnologyPrototype"
| "LuaTile"
| "LuaTilePrototype"
| "LuaTrain"
| "LuaTrainStopControlBehavior"
| "LuaTransportBeltControlBehavior"
| "LuaTransportLine"
| "LuaTrivialSmokePrototype"
| "LuaUnitGroup"
| "LuaVirtualSignalPrototype"
| "LuaVoidEnergySourcePrototype"
| "LuaWallControlBehavior"
function __object_name(object: LuaObject)
-> object_name: "LuaAISettings"|"LuaAccumulatorControlBehavior"|"LuaAchievementPrototype"|"LuaAmmoCategoryPrototype"|"LuaArithmeticCombinatorControlBehavior"...(+88)

arg

Command-line arguments of Lua Standalone.

View documents

string[]

assert

Raises an error if the value of its argument v is false (i.e., nil or false); otherwise, returns all its arguments. In case of error, message is the error object; when absent, it defaults to "assertion failed!"

View documents

function assert(v?: <T>, message?: any, ...any)
-> <T>
2. ...any

bit32

View documents

bit32lib

bit32.arshift

Returns the number x shifted disp bits to the right. Negative displacements shift to the left.

This shift operation is what is called arithmetic shift. Vacant bits on the left are filled with copies of the higher bit of x; vacant bits on the right are filled with zeros.

View documents

function bit32.arshift(x: integer, disp: integer)
-> integer

bit32.band

Returns the bitwise and of its operands.

View documents

function bit32.band(...any)
-> integer

bit32.bnot

Returns the bitwise negation of x.

assert(bit32.bnot(x) ==
(-1 - x) % 2^32)

View documents

function bit32.bnot(x: integer)
-> integer

bit32.bor

Returns the bitwise or of its operands.

View documents

function bit32.bor(...any)
-> integer

bit32.btest

Returns a boolean signaling whether the bitwise and of its operands is different from zero.

View documents

function bit32.btest(...any)
-> boolean

bit32.bxor

Returns the bitwise exclusive or of its operands.

View documents

function bit32.bxor(...any)
-> integer

bit32.extract

Returns the unsigned number formed by the bits field to field + width - 1 from n.

View documents

function bit32.extract(n: integer, field: integer, width?: integer)
-> integer

bit32.lrotate

Returns the number x rotated disp bits to the left. Negative displacements rotate to the right.

View documents

function bit32.lrotate(x: integer, distp: integer)
-> integer

bit32.lshift

Returns the number x shifted disp bits to the left. Negative displacements shift to the right. In any direction, vacant bits are filled with zeros.

assert(bit32.lshift(b, disp) ==
(b * 2^disp) % 2^32)

View documents

function bit32.lshift(x: integer, distp: integer)
-> integer

bit32.replace

Returns a copy of n with the bits field to field + width - 1 replaced by the value v .

View documents

function bit32.replace(n: integer, v: integer, field: integer, width?: integer)

bit32.rrotate

Returns the number x rotated disp bits to the right. Negative displacements rotate to the left.

View documents

function bit32.rrotate(x: integer, distp: integer)
-> integer

bit32.rshift

Returns the number x shifted disp bits to the right. Negative displacements shift to the left. In any direction, vacant bits are filled with zeros.

assert(bit32.rshift(b, disp) ==
math.floor(b % 2^32 / 2^disp))

View documents

function bit32.rshift(x: integer, distp: integer)
-> integer

collectgarbage

This function is a generic interface to the garbage collector. It performs different functions according to its first argument, opt.

View documents

opt:
-> "collect" -- Performs a full garbage-collection cycle.
| "stop" -- Stops automatic execution.
| "restart" -- Restarts automatic execution.
| "count" -- Returns the total memory in Kbytes.
| "step" -- Performs a garbage-collection step.
| "isrunning" -- Returns whether the collector is running.
| "setpause" -- Set `pause`.
| "setstepmul" -- Set `step multiplier`.
function collectgarbage(opt?: "collect"|"count"|"isrunning"|"restart"|"setpause"...(+3), arg?: integer)
-> any

commands

Global Description:
Allows registration of custom commands for the in-game console.

Class Description:
Allows for the registration of custom console commands through the global object named commands. Similarly to event subscriptions, these don't persist through a save-and-load cycle.

View documentation

LuaCommandProcessor

data

data

debug

View documents

factorio.debuglib

debug.debug

Enters an interactive mode with the user, running each string that the user enters.

View documents

function debug.debug()

debug.gethook

Returns the current hook settings of the thread.

View documents

function debug.gethook()
-> hook: function
2. mask: string
3. count: integer

debug.getinfo

Returns a table with information about a function.

View documents

what:
+> "n" -- `name` and `namewhat`
+> "S" -- `source`, `short_src`, `linedefined`, `lastlinedefined`, and `what`
+> "l" -- `currentline`
+> "t" -- `istailcall`
+> "u" -- `nups`, `nparams`, and `isvararg`
+> "f" -- `func`
+> "L" -- `activelines`
+> "p" -- `currentpc`
function debug.getinfo(f: integer|fun(...any):...unknown, what?: string|"L"|"S"|"f"|"l"...(+4))
-> debuginfo

debug.getlocal

Returns the name and the value of the local variable with index local of the function at level f of the stack.

View documents

function debug.getlocal(f: integer|fun(...any):...unknown, index: integer)
-> name: string
2. value: any

debug.getmetatable

Returns the metatable of the given value.

View documents

function debug.getmetatable(object: any)
-> metatable: table

debug.getregistry

Returns the registry table.

View documents

function debug.getregistry()
-> table

debug.getupvalue

Returns the name and the value of the upvalue with index up of the function.

View documents

function debug.getupvalue(f: fun(...any):...unknown, up: integer)
-> name: string
2. value: any

debug.getuservalue

Returns the Lua value associated to u.

View documents

function debug.getuservalue(u: userdata)
-> any

debug.setcstacklimit

Deprecated in Lua 5.4.2

Sets a new limit for the C stack. This limit controls how deeply nested calls can go in Lua, with the intent of avoiding a stack overflow.

In case of success, this function returns the old limit. In case of error, it returns false.

View documents

function debug.setcstacklimit(limit: integer)
-> boolean|integer

debug.sethook

Sets the given function as a hook.

View documents


mask:
+> "c" -- Calls hook when Lua calls a function.
+> "r" -- Calls hook when Lua returns from a function.
+> "l" -- Calls hook when Lua enters a new line of code.
function debug.sethook(hook: fun(...any):...unknown, mask: string|"c"|"l"|"r", count?: integer)

debug.setlocal

Assigns the value to the local variable with index local of the function at level of the stack.

View documents

function debug.setlocal(level: integer, index: integer, value: any)
-> name: string

debug.setmetatable

Sets the metatable for the given value to the given table (which can be nil).

View documents

function debug.setmetatable(value: <T>, meta?: table)
-> value: <T>

debug.setupvalue

Assigns the value to the upvalue with index up of the function.

View documents

function debug.setupvalue(f: fun(...any):...unknown, up: integer, value: any)
-> name: string

debug.setuservalue

Sets the given value as the Lua value associated to the given udata.

View documents

function debug.setuservalue(udata: userdata, value: any)
-> udata: userdata

debug.traceback

Returns a string with a traceback of the call stack. The optional message string is appended at the beginning of the traceback.

View documents

function debug.traceback(thread: thread, message?: any, level?: integer)
-> message: string

debug.upvalueid

Returns a unique identifier (as a light userdata) for the upvalue numbered n from the given function.

View documents

function debug.upvalueid(f: fun(...any):...unknown, n: integer)
-> id: lightuserdata

debug.upvaluejoin

Make the n1-th upvalue of the Lua closure f1 refer to the n2-th upvalue of the Lua closure f2.

View documents

function debug.upvaluejoin(f1: fun(...any):...unknown, n1: integer, f2: fun(...any):...unknown, n2: integer)

defines

View Documentation

table
defines
table

defines.alert_type

table

defines.behavior_result

table

defines.build_check_type

table

defines.chain_signal_state

table

defines.chunk_generated_status

table

defines.circuit_condition_index

table

defines.circuit_connector_id

table

defines.command

table

defines.compound_command

table

defines.control_behavior

View Documentation

defines.control_behavior

defines.control_behavior.inserter

View Documentation

defines.control_behavior.inserter

defines.control_behavior.inserter.circuit_mode_of_operation

table

defines.control_behavior.inserter.hand_read_mode

table

defines.control_behavior.lamp

View Documentation

defines.control_behavior.lamp

defines.control_behavior.lamp.circuit_mode_of_operation

table

defines.control_behavior.logistic_container

View Documentation

defines.control_behavior.logistic_container

defines.control_behavior.logistic_container.circuit_mode_of_operation

table

defines.control_behavior.mining_drill

View Documentation

defines.control_behavior.mining_drill

defines.control_behavior.mining_drill.resource_read_mode

table

defines.control_behavior.transport_belt

View Documentation

defines.control_behavior.transport_belt

defines.control_behavior.transport_belt.content_read_mode

table

defines.control_behavior.type

table

defines.controllers

table

defines.deconstruction_item

View Documentation

defines.deconstruction_item

defines.deconstruction_item.entity_filter_mode

table

defines.deconstruction_item.tile_filter_mode

table

defines.deconstruction_item.tile_selection_mode

table

defines.difficulty

table

defines.difficulty_settings

View Documentation

defines.difficulty_settings

defines.difficulty_settings.recipe_difficulty

table

defines.difficulty_settings.technology_difficulty

table

defines.direction

table

defines.disconnect_reason

table

defines.distraction

table

defines.entity_status

table

defines.events

table

defines.flow_precision_index

table

defines.game_controller_interaction

table

defines.group_state

table

defines.gui_type

table

defines.input_action

table

defines.input_method

table

defines.inventory

table

defines.logistic_member_index

table

defines.logistic_mode

table

defines.mouse_button_type

table

defines.prototypes

A dictionary mapping all top-level prototypes by name to a list of their associated subtypes. This list is organized as a lookup table, meaning it maps the sub-prototype names to 0. As an example, defines.prototypes['entity'] looks like this: {furnace=0, inserter=0, container=0, ...}.

View Documentation

defines.prototypes|{ [string]: { [string]: 0 } }

defines.rail_connection_direction

table

defines.rail_direction

table

defines.relative_gui_position

table

defines.relative_gui_type

table

defines.render_mode

table

defines.rich_text_setting

table

defines.riding

View Documentation

defines.riding

defines.riding.acceleration

table

defines.riding.direction

table

defines.rocket_silo_status

table

defines.shooting

table

defines.signal_state

table

defines.train_state

table

defines.transport_line

table

defines.wire_connection_id

table

defines.wire_type

table

dofile

Opens the named file and executes its content as a Lua chunk. When called without arguments, dofile executes the content of the standard input (stdin). Returns all values returned by the chunk. In case of errors, dofile propagates the error to its caller. (That is, dofile does not run in protected mode.)

View documents

function dofile(filename?: string)
-> ...any

error

Terminates the last protected function called and returns message as the error object.

Usually, error adds some information about the error position at the beginning of the message, if the message is a string.

View documents

function error(message: any, level?: integer)

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.0|BoundingBox.1)
-> BoundingBox.0|BoundingBox.1

Return a new box expanded to the nearest tile edges.

center

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

Calculate the centerpoint of the box.

contains_box

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

Check if the first box contains the second box.

contains_position

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

Check if the given box contains the given position.

ensure_explicit

function flib_bounding_box.ensure_explicit(box: BoundingBox.0|BoundingBox.1)
-> BoundingBox.0|BoundingBox.1

Return the box in explicit form.

ensure_short

function flib_bounding_box.ensure_short(box: BoundingBox.0|BoundingBox.1)
-> BoundingBox.0|BoundingBox.1

Return the box in shorthand form.

expand_to_contain_box

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

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.0|BoundingBox.1, pos: MapPosition.0|MapPosition.1)
-> BoundingBox.0|BoundingBox.1

Return a new box expanded to contain the given position.

floor

function flib_bounding_box.floor(box: BoundingBox.0|BoundingBox.1)
-> BoundingBox.0|BoundingBox.1

Return a new box shrunk to the nearest tile edges.

from_dimensions

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

Create a new box from a centerpoint and dimensions.

from_position

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

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

height

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

Calculate the height of the box.

intersects_box

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

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

move

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

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

recenter_on

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

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

resize

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

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.0|BoundingBox.1)
-> BoundingBox.0|BoundingBox.1

Return a new box rotated 90 degrees about its center.

square

function flib_bounding_box.square(box: BoundingBox.0|BoundingBox.1)
-> BoundingBox.0|BoundingBox.1

Return a new box expanded to create a square.

width

function flib_bounding_box.width(box: BoundingBox.0|BoundingBox.1)
-> 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.0|MapPosition.1, filename?: string, size?: Vector.0|Vector.1, 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: boolean|string|number|LuaObject|boolean|string|number|LuaObject|boolean|string|number|LuaObject|nil[]...(+1)[]...(+1))

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: integer, 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: integer)
-> 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, boolean|string|number|LuaObject|boolean|string|number|LuaObject|boolean|string|number|LuaObject|nil[]...(+1)[]...(+1)>)

Create a new dictionary. The name must be unique.

on_configuration_changed

function

on_init

function flib_dictionary.on_init()

on_player_dictionaries_ready

integer

32 bit unsigned integer. Ranges from 0 to 4 294 967 295, or [0, 2^32-1]

on_player_joined_game

function flib_dictionary.on_player_joined_game(e: EventData.on_player_joined_game)

on_player_language_changed

integer

32 bit unsigned integer. Ranges from 0 to 4 294 967 295, or [0, 2^32-1]

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.0|MapPosition.1, target: MapPosition.0|MapPosition.1, 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)
-> number

Calculate an orientation from a direction.

to_vector

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

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.0|MapPosition.1)?

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?: integer, 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[]|GuiElemDef|GuiElemDefClass[][]|GuiElemDefClass|GuiElemDefClass|GuiElemDefClass[]|GuiElemDef|GuiElemDefClass[][]|GuiElemDef|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

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

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.0|ChunkPosition.1)
-> TilePosition.0|TilePosition.1

Convert a ChunkPosition into a TilePosition by multiplying by 32.

ge

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

Test if pos1 is greater than or equal to pos2.

gt

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

Test if pos1 is greater than pos2.

le

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

Test if pos1 is less than or equal to pos2.

lerp

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

Linearly interpolate between two positions. For example, an amount of 0.5 will return the midpoint.

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.0|MapPosition.1|TilePosition.0|TilePosition.1)
-> ChunkPosition.0|ChunkPosition.1

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

to_tile

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

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.


game

Global Description:
The main scripting interface through which most of the API is accessed.

Class Description:
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.

View documentation

LuaGameScript

getfenv

Returns the current environment in use by the function. f can be a Lua function or a number that specifies the function at that stack level.

View documents

function getfenv(f?: integer|fun(...any):...unknown)
-> table

getmetatable

If object does not have a metatable, returns nil. Otherwise, if the object's metatable has a __metatable field, returns the associated value. Otherwise, returns the metatable of the given object.

View documents

function getmetatable(object: any)
-> metatable: table

global

table

global.__flib

table
table
table
table
table
table
table
table

global.__flib.dictionary

flib_dictionary_global
table
flib_dictionary_global
flib_dictionary_global

global.__flib.on_tick_n

{ [number]: table<number, any> }
{ [number]: table<number, any> }

global.__flib.translation

table
table

global.guis

table
table

ipairs

Returns three values (an iterator function, the table t, and 0) so that the construction

    for i,v in ipairs(t) do body end

will iterate over the key–value pairs (1,t[1]), (2,t[2]), ..., up to the first absent index.

View documents

function ipairs(t: <T:table>)
-> fun(table: <V>[], i?: integer):integer, <V>
2. <T:table>
3. i: integer

load

Loads a chunk.

If chunk is a string, the chunk is this string. If chunk is a function, load calls it repeatedly to get the chunk pieces. Each call to chunk must return a string that concatenates with previous results. A return of an empty string, nil, or no value signals the end of the chunk.

View documents

mode:
| "b" -- Only binary chunks.
| "t" -- Only text chunks.
-> "bt" -- Both binary and text.
function load(chunk: string|function, chunkname?: string, mode?: "b"|"bt"|"t", env?: table)
-> function?
2. error_message: string?

loadfile

Loads a chunk from file filename or from the standard input, if no file name is given.

View documents

mode:
| "b" -- Only binary chunks.
| "t" -- Only text chunks.
-> "bt" -- Both binary and text.
function loadfile(filename?: string, mode?: "b"|"bt"|"t", env?: table)
-> function?
2. error_message: string?

loadstring

Loads a chunk from the given string.

View documents

function loadstring(text: string, chunkname?: string)
-> function?
2. error_message: string?

localised_print

localised_print() allows printing LocalisedString to stdout without polluting the Factorio log file. This is primarily useful when communicating with external tools that launch Factorio as a child process.

View Documentation

function localised_print(string: boolean|string|number|LuaObject|boolean|string|number|LuaObject|boolean|string|number|LuaObject|nil[]...(+1)[]...(+1))

log

log() can print LocalisedStrings to the Factorio log file. This, in combination with the serpent library, makes debugging in the data stage easier because it allows the inspection of entire prototype tables. For example, printing all properties of the sulfur item prototype can be done like so: log(serpent.block(data.raw["item"]["sulfur"]))

View Documentation

function _ENV.log(...any)
function log(string: boolean|string|number|LuaObject|boolean|string|number|LuaObject|boolean|string|number|LuaObject|nil[]...(+1)[]...(+1))
function _ENV.log(...any)

math

View documents

factorio.mathlib

math.abs

Returns the absolute value of x.

View documents

function math.abs(x: number)
-> number

math.acos

Returns the arc cosine of x (in radians).

View documents

function math.acos(x: number)
-> number

math.asin

Returns the arc sine of x (in radians).

View documents

function math.asin(x: number)
-> number

math.atan

Returns the arc tangent of x (in radians).

View documents

function math.atan(y: number)
-> number

math.atan2

Returns the arc tangent of y/x (in radians).

View documents

function math.atan2(y: number, x: number)
-> number

math.ceil

Returns the smallest integral value larger than or equal to x.

View documents

function math.ceil(x: number)
-> integer

math.cos

Returns the cosine of x (assumed to be in radians).

View documents

function math.cos(x: number)
-> number

math.cosh

Returns the hyperbolic cosine of x (assumed to be in radians).

View documents

function math.cosh(x: number)
-> number

math.deg

Converts the angle x from radians to degrees.

View documents

function math.deg(x: number)
-> number

math.exp

Returns the value e^x (where e is the base of natural logarithms).

View documents

function math.exp(x: number)
-> number

math.floor

Returns the largest integral value smaller than or equal to x.

View documents

function math.floor(x: number)
-> integer

math.fmod

Returns the remainder of the division of x by y that rounds the quotient towards zero.

View documents

function math.fmod(x: number, y: number)
-> number

math.frexp

Decompose x into tails and exponents. Returns m and e such that x = m * (2 ^ e), e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero).

View documents

function math.frexp(x: number)
-> m: number
2. e: number

math.ldexp

Returns m * (2 ^ e) .

View documents

function math.ldexp(m: number, e: number)
-> number

math.log

Returns the logarithm of x in the given base.

View documents

function math.log(x: number, base?: integer)
-> number

math.log10

Returns the base-10 logarithm of x.

View documents

function math.log10(x: number)
-> number

math.max

Returns the argument with the maximum value, according to the Lua operator <.

View documents

function math.max(x: <Number:number>, ...<Number:number>)
-> <Number:number>

math.min

Returns the argument with the minimum value, according to the Lua operator <.

View documents

function math.min(x: <Number:number>, ...<Number:number>)
-> <Number:number>

math.modf

Returns the integral part of x and the fractional part of x.

View documents

function math.modf(x: number)
-> integer
2. number

math.pow

Returns x ^ y .

View documents

function math.pow(x: number, y: number)
-> number

math.rad

Converts the angle x from degrees to radians.

View documents

function math.rad(x: number)
-> number

math.random

math.random() is reimplemented within Factorio to be deterministic, both in the data stage and during runtime.

In the data stage, it is seeded with a constant number. During runtime, it uses the map's global random generator which is seeded with the map seed. The map's global random generator is shared between all mods and the core game, which all affect the random number that is generated. If this behaviour is not desired, LuaRandomGenerator can be used to create a random generator that is completely separate from the core game and other mods.

This method can't be used outside of events or during loading. Calling it with non-integer arguments will floor them instead of resulting in an error.

function math.random(m: number, n: number)
-> integer

math.randomseed

Using math.randomseed() in Factorio has no effect on the random generator, the function does nothing. If custom seeding or re-seeding is desired, LuaRandomGenerator can be used instead of math.random(). See: LuaRandomGenerator

function math.randomseed(x: integer)

math.sin

Returns the sine of x (assumed to be in radians).

View documents

function math.sin(x: number)
-> number

math.sinh

Returns the hyperbolic sine of x (assumed to be in radians).

View documents

function math.sinh(x: number)
-> number

math.sqrt

Returns the square root of x.

View documents

function math.sqrt(x: number)
-> number

math.tan

Returns the tangent of x (assumed to be in radians).

View documents

function math.tan(x: number)
-> number

math.tanh

Returns the hyperbolic tangent of x (assumed to be in radians).

View documents

function math.tanh(x: number)
-> number

math.tointeger

If the value x is convertible to an integer, returns that integer.

View documents

function math.tointeger(x: any)
-> integer?

math.type

Returns "integer" if x is an integer, "float" if it is a float, or nil if x is not a number.

View documents

return #1:
| "integer"
| "float"
| 'nil'
function math.type(x: any)
-> "float"|"integer"|'nil'

math.ult

Returns true if and only if m is below n when they are compared as unsigned integers.

View documents

function math.ult(m: integer, n: integer)
-> boolean

mods

See: LuaBootstrap.active_mods

{ [string]: string }

module

Creates a module.

View documents

function module(name: string, ...any)

newproxy

function newproxy(proxy: boolean|table|userdata)
-> userdata

next

Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. A call to next returns the next index of the table and its associated value. When called with nil as its second argument, next returns an initial index and its associated value. When called with the last index, or with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t) to check whether a table is empty.

The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numerical order, use a numerical for.)

The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may set existing fields to nil.

View documents

function next(table: table<<K>, <V>>, index?: <K>)
-> <K>?
2. <V>?

os.exit

function os.exit(...any)
function os.exit(...any)

package

factorio.packagelib

package.path

string
string

pairs

If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.

Otherwise, returns three values: the next function, the table t, and nil, so that the construction

    for k,v in pairs(t) do body end

will iterate over all key–value pairs of table t.

See function next for the caveats of modifying the table during its traversal.

View documents

function pairs(t: <T:table>)
-> fun(table: table<<K>, <V>>, index?: <K>):<K>, <V>
2. <T:table>

pcall

Calls the function f with the given arguments in protected mode. This means that any error inside f is not propagated; instead, pcall catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall also returns all results from the call, after this first result. In case of any error, pcall returns false plus the error object.

View documents

function pcall(f: fun(...any):...unknown, arg1?: any, ...any)
-> success: boolean
2. result: any
3. ...any

print

Receives any number of arguments and prints their values to stdout, converting each argument to a string following the same rules of tostring. The function print is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use string.format and io.write.

View documents

function print(...any)

rawequal

Checks whether v1 is equal to v2, without invoking the __eq metamethod.

View documents

function rawequal(v1: any, v2: any)
-> boolean

rawget

Gets the real value of table[index], without invoking the __index metamethod.

View documents

function rawget(table: table, index: any)
-> any

rawlen

Returns the length of the object v, without invoking the __len metamethod.

View documents

function rawlen(v: string|table)
-> len: integer

rawset

Sets the real value of table[index] to value, without using the __newindex metavalue. table must be a table, index any value different from nil and NaN, and value any Lua value. This function returns table.

View documents

function rawset(table: table, index: any, value: any)
-> table

rcon

Global Description:
Allows printing messages to the calling RCON instance, if any.

Class Description:
An interface to send messages to the calling RCON interface through the global object named rcon.

View documentation

LuaRCON

remote

Global Description:
Allows registration and use of functions to communicate between mods.

Class Description:
Registry of interfaces between scripts. An interface is simply a dictionary mapping names to functions. A script or mod can then register an interface with LuaRemote, after that any script can call the registered functions, provided it knows the interface name and the desired function name. An instance of LuaRemote is available through the global object named remote.

View documentation

Example

Will register a remote interface containing two functions. Later, it will call these functions through remote.

remote.add_interface("human interactor",
             {hello = function() game.player.print("Hi!") end,
              bye = function(name) game.player.print("Bye " .. name) end})
-- Some time later, possibly in a different mod...
remote.call("human interactor", "hello")
remote.call("human interactor", "bye", "dear reader")
LuaRemote

rendering

Global Description:
Allows rendering of geometric shapes, text and sprites in the game world.

Class Description:
Allows rendering of geometric shapes, text and sprites in the game world through the global object named rendering. Each render object is identified by an id that is universally unique for the lifetime of a whole game.

Note: If an entity target of an object is destroyed or changes surface, then the object is also destroyed.

View documentation

LuaRendering

require

Due to the changes to package, the functionality of require() changes. When using absolute paths, the path starts at the mod root. Additionally, .. is disabled as a path variable. This means that it is not possible to load arbitrary files from outside the mod directory.

Factorio does however provide two ways to load files from other mods:

require() can not be used in the console, in event listeners or during a remote.call(). The function expects any file to end with the .lua extension.

function require(modname: string)
-> unknown

script

Global Description:
Provides an interface for registering game event handlers.

Class Description:
Entry point for registering event handlers. It is accessible through the global object named script.

View documentation

LuaBootstrap

select

If index is a number, returns all arguments after argument number index; a negative number indexes from the end (-1 is the last argument). Otherwise, index must be the string "#", and select returns the total number of extra arguments it received.

View documents

index:
| "#"
function select(index: integer|"#", ...any)
-> any

serpent

Lua serializer and pretty printer.
Author: Paul Kulchenko
https://github.com/pkulchenko/serpent

local serpent = require("serpent")
local a = {1, nil, 3, x=1, ['true'] = 2, [not true]=3}
a[a] = a -- self-reference with a table as key and value

print(serpent.dump(a)) -- full serialization
print(serpent.line(a)) -- single line, no self-ref section
print(serpent.block(a)) -- multi-line indented, no self-ref section

local fun, err = loadstring(serpent.dump(a))
if err then error(err) end
local copy = fun()


local ok, copy = serpent.load(serpent.dump(a))
print(ok and copy[3] == a[3])


Note that line and block functions return pretty-printed data structures and if you want to deserialize them, you need to add return before running them through loadstring. For example:

loadstring('return '..require('mobdebug').line("foo"))() == "foo"


If a table or a userdata value has __tostring or __serialize method, the method will be used to serialize the value.
If __serialize method is present, it will be called with the value as a parameter. if __serialize method is not present, but __tostring is, then tostring will be called with the value as a parameter. In both cases, the result will be serialized, so __serialize method can return a table, that will be serialized and replace the original value.

Limitations:
Doesn't handle userdata (except filehandles in io.* table).
Threads, function upvalues/environments, and metatables are not serialized.

serpent

serpent.block

multi-line indented pretty printing, no self-ref section; sets indent, sortkeys, and comment options.

function serpent.block(value: any, options?: serpent.options)
-> string

serpent.dump

Full serialization; sets name, compact and sparse options

function serpent.dump(value: any, options?: serpent.options)
-> string

serpent.line

Single line pretty printing, no self-ref section; sets sortkeys and comment options;

function serpent.line(value: any, options?: serpent.options)
-> string

serpent.load

loads serialized fragment; you need to pass {safe = false} as the second value if you want to turn safety checks off.
Similar to pcall and loadstring calls, load returns status as the first value and the result or the error message as the second value.

function serpent.load(str: string, options?: serpent.load_options)
-> boolean
2. any

setfenv

Sets the environment to be used by the given function.

View documents

function setfenv(f: fun(...any):...integer|unknown, table: table)
-> function

setmetatable

Sets the metatable for the given table. If metatable is nil, removes the metatable of the given table. If the original metatable has a __metatable field, raises an error.

This function returns table.

To change the metatable of other types from Lua code, you must use the debug library (§6.10).

View documents

function setmetatable(table: table, metatable?: table|metatable)
-> table

settings

Global Description:
Provides access to the current mod settings.

Class Description:
Object containing mod settings of three distinct types: startup, global, and player. An instance of LuaSettings is available through the global object named settings.

View documentation

table
LuaSettings
table

string

View documents

stringlib

string.byte

Returns the internal numeric codes of the characters s[i], s[i+1], ..., s[j].

View documents

function string.byte(s: string|number, i?: integer, j?: integer)
-> ...integer

string.char

Returns a string with length equal to the number of arguments, in which each character has the internal numeric code equal to its corresponding argument.

View documents

function string.char(byte: integer, ...integer)
-> string

string.dump

Returns a string containing a binary representation (a binary chunk) of the given function.

View documents

function string.dump(f: fun(...any):...unknown)
-> string

string.find

Looks for the first match of pattern (see §6.4.1) in the string.

View documents

@return start

@return end

@return ... — captured

function string.find(s: string|number, pattern: string|number, init?: integer, plain?: boolean)
-> start: integer|nil
2. end: integer|nil
3. ...any

string.format

Returns a formatted version of its variable number of arguments following the description given in its first argument.

View documents

function string.format(s: string|number, ...any)
-> string

string.gmatch

Returns an iterator function that, each time it is called, returns the next captures from pattern (see §6.4.1) over the string s.

As an example, the following loop will iterate over all the words from string s, printing one per line:

    s =
"hello world from Lua"
for w in string.gmatch(s, "%a+") do
print(w)
end

View documents

function string.gmatch(s: string|number, pattern: string|number)
-> fun():string, ...unknown

string.gsub

Returns a copy of s in which all (or the first n, if given) occurrences of the pattern (see §6.4.1) have been replaced by a replacement string specified by repl.

View documents

function string.gsub(s: string|number, pattern: string|number, repl: string|number|function|table, n?: integer)
-> string
2. count: integer

string.len

Returns its length.

View documents

function string.len(s: string|number)
-> integer

string.lower

Returns a copy of this string with all uppercase letters changed to lowercase.

View documents

function string.lower(s: string|number)
-> string

string.match

Looks for the first match of pattern (see §6.4.1) in the string.

View documents

function string.match(s: string|number, pattern: string|number, init?: integer)
-> ...any

string.pack

Returns a binary string containing the values v1, v2, etc. packed (that is, serialized in binary form) according to the format string fmt (see §6.4.2) .

View documents

function string.pack(fmt: string, v1: string|number, v2?: string|number, ...string|number)
-> binary: string

string.packsize

Returns the size of a string resulting from string.pack with the given format string fmt (see §6.4.2) .

View documents

function string.packsize(fmt: string)
-> integer

string.rep

Returns a string that is the concatenation of n copies of the string s separated by the string sep.

View documents

function string.rep(s: string|number, n: integer, sep?: string|number)
-> string

string.reverse

Returns a string that is the string s reversed.

View documents

function string.reverse(s: string|number)
-> string

string.sub

Returns the substring of the string that starts at i and continues until j.

View documents

function string.sub(s: string|number, i: integer, j?: integer)
-> string

string.unpack

Returns the values packed in string according to the format string fmt (see §6.4.2) .

View documents

function string.unpack(fmt: string, s: string, pos?: integer)
-> ...any
2. offset: integer

string.upper

Returns a copy of this string with all lowercase letters changed to uppercase.

View documents

function string.upper(s: string|number)
-> string

table

View documents

tablelib

table.compare

Compares a table for shallow equality

function table.compare(tbl1: any, tbl2: any)
-> boolean

table.concat

Given a list where all elements are strings or numbers, returns the string list[i]..sep..list[i+1] ··· sep..list[j].

View documents

function table.concat(list: table, sep?: string, i?: integer, j?: integer)
-> string

table.deepcopy

Deep copies a table

function table.deepcopy(object: <T>)
-> <T>

table.foreach

Executes the given f over all elements of table. For each element, f is called with the index and respective value as arguments. If f returns a non-nil value, then the loop is broken, and this value is returned as the final value of foreach.

View documents

function table.foreach(list: any, callback: fun(key: string, value: any):<T>|nil)
-> <T>|nil

table.foreachi

Executes the given f over the numerical indices of table. For each index, f is called with the index and respective value as arguments. Indices are visited in sequential order, from 1 to n, where n is the size of the table. If f returns a non-nil value, then the loop is broken and this value is returned as the result of foreachi.

View documents

function table.foreachi(list: any, callback: fun(key: string, value: any):<T>|nil)
-> <T>|nil

table.getn

Returns the number of elements in the table. This function is equivalent to #list.

View documents

function table.getn(list: <T>[])
-> integer

table.insert

Inserts element value at position pos in list.

View documents

function table.insert(list: table, pos: integer, value: any)

table.maxn

Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices.

View documents

function table.maxn(table: table)
-> integer

table.move

Moves elements from table a1 to table a2.

a2[t],··· =
a1[f],···,a1[e]
return a2

View documents

function table.move(a1: table, f: integer, e: integer, t: integer, a2?: table)
-> a2: table

table.pack

Returns a new table with all arguments stored into keys 1, 2, etc. and with a field "n" with the total number of arguments.

View documents

function table.pack(...any)
-> table

table.remove

Removes from list the element at position pos, returning the value of the removed element.

View documents

function table.remove(list: table, pos?: integer)
-> any

table.sort

Sorts list elements in a given order, in-place, from list[1] to list[#list].

View documents

function table.sort(list: <T>[], comp?: fun(a: <T>, b: <T>):boolean)

table.unpack

Returns the elements from the given list. This function is equivalent to

    return list[i], list[i+1], ···, list[j]

By default, i is 1 and j is #list.

View documents

function table.unpack(list: <T>[], i?: integer, j?: integer)
-> ...<T>

table_size

@return

Factorio provides the table_size() function as a simple way to determine the size of tables with non-continuous keys, as the standard # operator does not work correctly for these. The function is a C++ implementation of the following Lua code, which is faster than doing the same in Lua:

local function size(t)
local count = 0
for k,v in pairs(t) do
count = count + 1
end
return count
end

Note that table_size() does not work correctly for LuaCustomTable, their size has to be determined with LuaCustomTable::length_operator instead.

View Documentation

function _ENV.table_size(tbl: any)
-> unknown
function table_size(table: table)
-> integer
function _ENV.table_size(tbl: any)
-> unknown

testNames

Run all test functions or tables provided as input.

    Input: a list of { name, instance }
instance can either be a function or a table containing test functions starting with the prefix "test"

return the number of failures and errors, 0 meaning success

parse the command-line arguments

unknown
unknown
unknown
unknown

tonumber

When called with no base, tonumber tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns this number; otherwise, it returns fail.

The conversion of strings can result in integers or floats, according to the lexical conventions of Lua (see §3.1). The string may have leading and trailing spaces and a sign.

View documents

function tonumber(e: any)
-> number?

tostring

Receives a value of any type and converts it to a string in a human-readable format.

If the metatable of v has a __tostring field, then tostring calls the corresponding value with v as argument, and uses the result of the call as its result. Otherwise, if the metatable of v has a __name field with a string value, tostring may use that string in its final result.

For complete control of how numbers are converted, use string.format.

View documents

function tostring(v: any)
-> string

type

Returns the type of its only argument, coded as a string. The possible results of this function are "nil" (a string, not the value nil), "number", "string", "boolean", "table", "function", "thread", and "userdata".

View documents

type:
| "nil"
| "number"
| "string"
| "boolean"
| "table"
| "function"
| "thread"
| "userdata"
function type(v: any)
-> type: "boolean"|"function"|"nil"|"number"|"string"...(+3)

unpack

Returns the elements from the given list. This function is equivalent to

    return list[i], list[i+1], ···, list[j]

View documents

function unpack(list: <T>[], i?: integer, j?: integer)
-> ...<T>

util

util

util.add_shift

function util.add_shift(a: Vector.1, b: Vector.1)
-> Vector.1

util.add_shift_offset

function util.add_shift_offset(offset_: Vector.1, table_: <T:table>)
-> <T:table>

util.by_pixel

function util.by_pixel(x: number, y: number)
-> Vector.1

util.by_pixel_hr

function util.by_pixel_hr(x: number, y: number)
-> Vector.1

util.clamp

function util.clamp(x: <X:number>, lower: <Lower:number>, upper: <Upper:number>)
-> <Lower:number>|<Upper:number>|<X:number>

util.color

supports 'rrggbb', 'rgb', 'rrggbbaa', 'rgba', 'ww', 'w'

function util.color(hex: string)
-> Color.0|Color.1

util.combine_icons

This function takes 2 icons tables, and adds the second to the first, but applies scale, shift and tint to the entire second set.
This allows you to manipulate the entire second icons table in the same way as you would manipulate a single icon when adding to the icons table.

function util.combine_icons(icons1: table, icons2: table, inputs: { ["scale"]: number?, ["shift"]: Vector.1?, ["tint"]: (Color.0|Color.1)? }, default_icon_size: integer)
-> table

util.conditional_return

If both value and data are truthy, returns data, otherwise returns false

return #1:
| false
function util.conditional_return(value: any, data: <D:any>)
-> <D:any>|false

util.copy

function

util.distance

The distance between two MapPositions

function util.distance(position1: MapPosition.0|MapPosition.1, position2: MapPosition.0|MapPosition.1)
-> number

util.draw_as_glow

function util.draw_as_glow(layer: <L:table>)
-> <L:table>

util.empty_sprite

function util.empty_sprite(animation_length: integer)
-> table

util.foreach_sprite_definition

function util.foreach_sprite_definition(table_: <T:table>, fun_: fun(t: <T:table>))
-> <T:table>

util.format_number

function util.format_number(amount: number, append_suffix: boolean)
-> string

util.formattime

function util.formattime(ticks: integer)
-> string

util.get_color_with_alpha

function util.get_color_with_alpha(color: Color.0|Color.1, alpha: number, normalized_alpha: boolean)
-> Color.0|Color.1

util.get_walkable_tile

function util.get_walkable_tile()
-> string

util.increment

function util.increment(t: { [<K:boolean|string|number|table>]: number }, k: <K:boolean|string|number|table>, v?: number)

util.insert_safe

function util.insert_safe(entity?: LuaEntity, item_dict?: ItemStackDefinition)

util.list_to_map

function util.list_to_map(list: any[])
-> { [any]: true }

util.merge

Recursively merges and/or deep-copies tables. Entries in later tables override entries in earlier ones, unless both entries are themselves tables, in which case they are recursively merged. Non-merged tables are deep-copied, so that the result is brand new.

function util.merge(tables: table[])
-> table

util.mix_color

Mixes two colors together

function util.mix_color(c1: Color.0|Color.1, c2: Color.0|Color.1)
-> Color.0|Color.1

util.moveposition

function util.moveposition(position: Vector.1, direction: defines.direction, distance: number)
-> Vector.1

util.mul_shift

function util.mul_shift(shift: <T:Vector.1>, scale: number)
-> <T:Vector.1>|Vector.1

util.multiply_color

function util.multiply_color(c1: Color.0|Color.1, n: number)
-> Color.0|Color.1

util.multiplystripes

function util.multiplystripes(count: integer, stripes: table)
-> table

util.online_players

function util.online_players()
-> LuaPlayer[]

util.oppositedirection

function util.oppositedirection(direction: defines.direction)
-> defines.direction

util.parse_energy

function util.parse_energy(energy: string)
-> number

util.positiontostr

function util.positiontostr(pos: MapPosition.0|MapPosition.1)
-> string

util.premul_color

Multiplies all color channels by alpha

function util.premul_color(color: <T:Color.0|Color.1>)
-> <T:Color.0|Color.1>

util.product_amount

function util.product_amount(product: table)
-> number

util.remove_from_list

Remove the first occurance of value from the array

function util.remove_from_list(list: any[], value: any)

util.remove_safe

function util.remove_safe(entity?: LuaEntity, item_dict?: ItemStackDefinition)

util.remove_tile_references

Does not handle:

@param data — Seriously pass the global data

function util.remove_tile_references(data: table, array_of_tiles_to_remove: string[])

util.split

function util.split(inputstr: string, sep: string)
-> string[]

util.split_whitespace

function util.split_whitespace(string: string)
-> string[]

util.string_starts_with

function util.string_starts_with(str: string, start: string)
-> boolean

util.table.compare

function

util.table.deepcopy

function

util.technology_icon_constant_braking_force

function util.technology_icon_constant_braking_force(technology_icon: string)
-> table[]

util.technology_icon_constant_capacity

function util.technology_icon_constant_capacity(technology_icon: string)
-> table[]

util.technology_icon_constant_damage

function util.technology_icon_constant_damage(technology_icon: string)
-> table[]

util.technology_icon_constant_equipment

function util.technology_icon_constant_equipment(technology_icon: string)
-> table[]

util.technology_icon_constant_followers

function util.technology_icon_constant_followers(technology_icon: string)
-> table[]

util.technology_icon_constant_mining

function util.technology_icon_constant_mining(technology_icon: string)
-> table[]

util.technology_icon_constant_movement_speed

function util.technology_icon_constant_movement_speed(technology_icon: string)
-> table[]

util.technology_icon_constant_productivity

function util.technology_icon_constant_productivity(technology_icon: string)
-> table[]

util.technology_icon_constant_range

function util.technology_icon_constant_range(technology_icon: string)
-> table[]

util.technology_icon_constant_speed

function util.technology_icon_constant_speed(technology_icon: string)
-> table[]

util.technology_icon_constant_stack_size

function util.technology_icon_constant_stack_size(technology_icon: string)
-> table[]

warn

Emits a warning with a message composed by the concatenation of all its arguments (which should be strings).

View documents

function warn(message: string, ...any)

xpcall

Calls function f with the given arguments in protected mode with a new message handler.

View documents

function xpcall(f: fun(...any):...unknown, msgh: function, arg1?: any, ...any)
-> success: boolean
2. result: any
3. ...any