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.
LuaPlayer
uint
string
string
string
Localised strings identified by an internal key. Keys must be unique and language-agnostic.
table<string, LocalisedString>
Called when a player's dictionaries are ready to be used. Handling this event is not required.
uint
Called when a player's language changes. Handling this event is not required.
string
uint
function GuiBase.build(player: LuaPlayer)
Build the GUI for the given player.
function GuiBase.change_mode(self: Gui, e: EventData.on_gui_checked_state_changed)
function GuiBase.clear_completed(self: Gui)
function GuiBase.hide(self: Gui)
function GuiBase.on_textfield_confirmed(self: Gui, e: EventData.on_gui_confirmed)
function GuiBase.on_textfield_text_changed(_: any, e: EventData.on_gui_confirmed)
function GuiBase.on_todo_toggled(self: Gui, e: EventData.on_gui_checked_state_changed)
function GuiBase.on_window_closed(self: Gui)
function GuiBase.show(self: Gui)
function GuiBase.toggle_pinned(self: Gui)
function GuiBase.toggle_visible(self: Gui)
function GuiBase.update_footer(self: Gui)
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[][]
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[][]?
Children to add to this element
(GuiElemDefClass|GuiElemDefClass|GuiElemDefClass[][])?
To add a tab, specify tab
and content
and leave all other fields unset.
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.
LuaGuiElement?
Modifications to make to the element itself
(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
LuaStyle?
Modifications to make to the element's style
(GuiElemDefClass|GuiElemDefClass|GuiElemDefClass[][])?
To add a tab, specify tab
and content
and leave all other fields unset.
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))>
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)
string
int
Migration code to run for specific mod version. A given function will run if the previous mod version is less than the given version.
{
["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)>
A unique identifier for a previously added task, used in on-tick-n.remove
.
number
The tasks' index in the tick's Tasks
table.
number
The tick this task is scheduled for.
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.
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>
number
The number of back-facing locomotives in the train.
number
The number of front-facing locomotives in the train.
number
The total number of rolling stocks in the train.
number
The number of wagons in the train.
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>
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")
function flib_bounding_box.ceil(box: BoundingBox)
-> BoundingBox
Return a new box expanded to the nearest tile edges.
function flib_bounding_box.center(box: BoundingBox)
-> MapPosition
Calculate the centerpoint of the box.
function flib_bounding_box.contains_box(box1: BoundingBox, box2: BoundingBox)
-> boolean
Check if the first box contains the second box.
function flib_bounding_box.contains_position(box: BoundingBox, pos: MapPosition)
-> boolean
Check if the given box contains the given position.
function flib_bounding_box.ensure_explicit(box: BoundingBox)
-> BoundingBox
Return the box in explicit form.
function flib_bounding_box.ensure_short(box: BoundingBox)
-> BoundingBox
Return the box in shorthand form.
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.
function flib_bounding_box.expand_to_contain_position(box: BoundingBox, pos: MapPosition)
-> BoundingBox
Return a new box expanded to contain the given position.
function flib_bounding_box.floor(box: BoundingBox)
-> BoundingBox
Return a new box shrunk to the nearest tile edges.
function flib_bounding_box.from_dimensions(center: MapPosition, width: number, height: number)
-> BoundingBox
Create a new box from a centerpoint and dimensions.
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.
function flib_bounding_box.height(box: BoundingBox)
-> number
Calculate the height of the box.
function flib_bounding_box.intersects_box(box1: BoundingBox, box2: BoundingBox)
-> boolean
Check if the first box intersects (overlaps) the second box.
function flib_bounding_box.move(box: BoundingBox, delta: MapPosition)
-> BoundingBox
Return a new box with the same dimensions, moved by the given delta.
function flib_bounding_box.recenter_on(box: BoundingBox, pos: MapPosition)
-> BoundingBox
Return a new box with the same dimensions centered on the given position.
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.
function flib_bounding_box.rotate(box: BoundingBox)
-> BoundingBox
Return a new box rotated 90 degrees about its center.
function flib_bounding_box.square(box: BoundingBox)
-> BoundingBox
Return a new box expanded to create a square.
function flib_bounding_box.width(box: BoundingBox)
-> number
Calculate the width of the box.
Utilities for data stage prototype manipulation.
local flib_data_util = require("__flib__/data-util")
string
A black image, for use with tool backgrounds. This image is 1x1.
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.
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
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.
string
A dark red button tileset. Used for the flib_tool_button_dark_red
style.
string
An empty image. This image is 8x8 to facilitate usage with GUI styles.
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.
string
A desaturated planner image. Tint this sprite to easily add your own planners.
Utilities for creating dictionaries of localised string translations.
local flib_dictionary = require("__flib__/dictionary-lite")
function flib_dictionary.add(dict_name: string, key: string, localised: LocalisedString)
Add the given string to the dictionary.
table
For use with __core__/lualib/event_handler
. Pass flib_dictionary
into handler.add_lib
to
handle all relevant events automatically.
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.
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.
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..
function flib_dictionary.new(name: string, initial_strings?: table<string, LocalisedString>)
Create a new dictionary. The name must be unique.
function
function flib_dictionary.on_init()
unknown
function flib_dictionary.on_player_joined_game(e: EventData.on_player_joined_game)
unknown
function flib_dictionary.on_string_translated(e: EventData.on_string_translated)
function flib_dictionary.on_tick()
Functions for working with directions.
local flib_direction = require("__flib__/direction")
integer
defines.direction.east
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
.
function flib_direction.next(direction: defines.direction, eight_way?: boolean)
-> defines.direction
Calculate the next four-way or eight-way direction.
integer
defines.direction.north
integer
defines.direction.northeast
integer
defines.direction.northwest
function flib_direction.opposite(direction: defines.direction)
-> defines.direction
Calculate the opposite direction.
function flib_direction.previous(direction: defines.direction, eight_way?: boolean)
-> defines.direction
Calculate the previous four-way or eight-way direction.
integer
defines.direction.south
integer
defines.direction.southeast
integer
defines.direction.southwest
function flib_direction.to_orientation(direction: defines.direction)
-> RealOrientation
Calculate an orientation from a direction.
function flib_direction.to_vector(direction: defines.direction, distance?: number)
-> MapPosition
Calculate a vector from a direction.
@param distance
— default: 1
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.
integer
defines.direction.west
Various string formatting functions.
local flib_format = require("__flib__/format")
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.
function flib_format.time(tick?: uint, include_leading_zeroes?: boolean)
-> string
Convert the given tick or game.tick into "[hh:]mm:ss" format.
Utilities for building GUIs and handling GUI events.
local flib_gui = require("__flib__/gui-lite")
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.
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.
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.
table
For use with __core__/lualib/event_handler
. Pass flib_gui
into handler.add_lib
to handle
all GUI events automatically.
function flib_gui.handle_events()
Handle all GUI events with flib_gui.dispatch
. Will not overwrite any existing event handlers.
Extension of the Lua 5.2 math library.
local flib_math = require("__flib__/math")
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.
function flib_math.ceiled(num: number, divisor?: number)
-> number|unknown
Ceil a number to the nearest multiple of divisor.
@param divisor
— num
will be ceiled to the nearest multiple of divisor
(default: 1).
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
number
Multiply by degrees to convert to radians.
local rad = 1 x flib_math.deg_to_rad -- 0.0174533
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.
function flib_math.floored(num: number, divisor?: number)
-> number|unknown
Floor a number to the nearest multiple of divisor.
@param divisor
— num
will be floored to the nearest multiple of divisor
(default: 1).
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
.
number
integer
2,147,483,647
integer
32,767
integer
9,007,199,254,740,991
integer
127
integer
4,294,967,295
integer
65,535
integer
255
function flib_math.maximum(set: number[])
-> number
Returns the argument with the maximum value from a set.
function flib_math.mean(set: number[])
-> number
Calculate the mean (average) of a set of numbers.
function flib_math.midrange(set: number[])
-> number
Calculate the mean of the largest and the smallest values in a set of numbers.
number
integer
-2,147,483,648
integer
-32,768
integer
-9,007,199,254,740,992
integer
-128
function flib_math.minimum(set: number[])
-> number
Returns the argument with the minimum value from a set.
number
Multiply by radians to convert to degrees.
local deg = 1 x flib_math.rad_to_deg -- 57.2958
function flib_math.range(set: number[])
-> number
Calculate the range in a set of numbers.
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 divisor
— num
will be rounded to the nearest multiple of divisor
(default: 1).
function flib_math.round_to(num: number, num_decimals: number)
-> number
Round a number to the nearest N decimal places.
From lua-users.org.
function flib_math.sign(x: number)
-> number
Return the signedness of a number as a multiplier.
function flib_math.sum(set: number[])
-> number
Calculate the sum of a set of numbers.
Mod migration and version comparison functions.
local flib_migration = require("__flib__/migration")
function flib_migration.format_version(version: string, format?: string)
-> string?
Normalize version strings for easy comparison.
migration.format_version("1.10.1234", "%04d")
migration.format_version("3", "%02d")
@param format
— default: %02d
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.
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
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.
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
.
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
.
Schedule tasks to be executed later.
local flib_on_tick_n = require("__flib__/on-tick-n")
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.
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.
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
.
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
.
Functions for working with orientations.
local flib_orientation = require("__flib__/orientation")
function flib_orientation.add(orientation1: number, orientation2: number)
-> the: number
Add two orientations together.
@return the
— orientations added together
number
number
number
number
function flib_orientation.opposite(orientation: number)
-> number
Returns the opposite orientation.
number
number
number
function flib_orientation.to_direction(orientation: number, eight_way: boolean)
-> defines.direction
Returns a 4way or 8way direction from an orientation.
number
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")
function flib_position.add(pos1: <P>, pos2: <P>)
-> <P>
Add two positions.
function flib_position.ceil(pos: <P>)
-> <P>
Ceil the given position.
function flib_position.distance(pos1: <P>, pos2: <P>)
-> number
Calculate the distance between two positions.
function flib_position.distance_squared(pos1: <P>, pos2: <P>)
-> number
Calculate the squared distance between two positions.
function flib_position.div(pos1: <P>, pos2: <P>)
-> <P>
Divide two positions.
function flib_position.ensure_explicit(pos: <P>)
-> <P>
Return the position in explicit form.
function flib_position.ensure_short(pos: <P>)
-> <P>
Return the position in shorthand form.
function flib_position.eq(pos1: <P>, pos2: <P>)
-> boolean
Test if two positions are equal.
function flib_position.floor(pos: <P>)
-> <P>
Floor the given position.
function flib_position.from_chunk(pos: ChunkPosition)
-> TilePosition
Convert a ChunkPosition
into a TilePosition
by multiplying by 32.
function flib_position.le(pos1: <P>, pos2: <P>)
-> boolean
Test if pos1
is less than or equal to pos2
.
function flib_position.lt(pos1: <P>, pos2: <P>)
-> boolean
Test if pos1
is less than pos2
.
function flib_position.mod(pos1: <P>, pos2: <P>)
-> <P>
Take the remainder (modulus) of two positions.
function flib_position.mul(pos1: <P>, pos2: <P>)
-> <P>
Multiply two positions.
function flib_position.pow(pos1: <P>, pos2: <P>)
-> <P>
Take the power of two positions. pos1^pos2
.
function flib_position.sub(pos1: <P>, pos2: <P>)
-> <P>
Subtract two positions.
function flib_position.to_chunk(pos: MapPosition|TilePosition)
-> ChunkPosition
Convert a MapPosition
or TilePosition
into a ChunkPosition
by dividing by 32 and flooring.
function flib_position.to_tile(pos: MapPosition)
-> TilePosition
Convert a MapPosition
into a TilePosition
by flooring.
Lua queue implementation.
Based on "Queues and Double Queues" from Programming in Lua.
local flib_queue = require("__flib__/queue")
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.
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
function
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.
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
function
function flib_queue.length(self: Queue<<T>>)
-> number
Get the length of the queue.
function flib_queue.new()
-> Queue
Create a new queue.
function flib_queue.pop_back(self: Queue<<T>>)
-> <T>?
Retrieve an element from the back of the queue.
function flib_queue.pop_front(self: Queue<<T>>)
-> <T>?
Retrieve an element from the front of the queue.
function
function
function flib_queue.push_back(self: Queue<<T>>, value: <T>)
Push an element into the back of the queue.
function flib_queue.push_front(self: Queue<<T>>, value: <T>)
Push an element into the front of the queue.
function
function
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")
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.
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.
function flib_table.deep_compare(tbl1: table, tbl2: table)
-> boolean
Recursively compare two tables for inner equality.
Does not compare metatables.
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.
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.
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.
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.
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.
function flib_table.find(tbl: table<<K>, <V>>, value: <V>)
-> key: <K>?
Find and return the first key containing the given value.
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.
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.
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.
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.
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.
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.
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()
.
local tbl = {"foo", "bar", "baz", set = "baz"}
local inverted = table.invert(tbl) -- {foo = 1, bar = 2, baz = "set"}
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.
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}
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.
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.
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.
function
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.
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.
function
Retrieve the size of a table.
Uses Factorio's built-in table_size
function.
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.
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.
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.
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.
Functions for working with trains.
local flib_train = require("__flib__/train")
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
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.
<L<
, >L>
: LocomotivesC
: Cargo wagonF
: Fluid wagonA
: Artillery wagon@return composition
— The composition string, or nil
if the train was invalid.
@return
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
function flib_train.open_gui(player_index: number, train: LuaTrain)
-> boolean
Open train GUI for one player.
@return — true
if the GUI was opened.
function flib_train.rotate_carriage(entity: LuaEntity)
-> rotated: boolean
Rotate a single carriage of a train.
@return rotated
— true
when rotation was successful.