Freeciv
Advertisement

Every event or action should have information about which versions of Freeciv support it. Important: Anything documented about unreleased versions can change at any time before the final release.

Legend[]

An argument with a question mark '?' is allowed to be empty. The empty value is 'nil'.

There are several contexts where scripting is used in Freeciv. Not everything documented here can be used in every context. For instance, methods to read game state can be used in most contexts, but methods to directly change it can only be used in a script running on the server.

Scope Definition
Common (all Lua instances) tolua_common_a.pkg
tolua_common_z.pkg
Signals (all current Lua instances) tolua_signal.pkg
Game (server, client, fcdb) tolua_game.pkg
Server (ruleset) only tolua_server.pkg
Client only tolua_client.pkg
FCDB (server) only tolua_fcdb.pkg

Text formatting indicates the current status of each definition:

Status
Current.
Deprecated; do not use in new code.
Internal; may disappear without notice; do not use.
Not yet implemented.

Modules[]

Module functions are accessed as members of the module:

module.function(..)

const[]

New in 2.4. This Lua constants implementation is included as const.

log[]

Logging facilities from Lua script. This is the preferred way to emit textual output from Freeciv Lua scripts. Messages emitted with these functions will be sent to an appropriate place, which will differ depending on the context. As of Freeciv 3.0 or older log.fatal() or assert() do not abort the game.

Module log
(return) type function name / variable arguments ver comments
nil log.base (level, format, ...) 2.4 Do not call this function directly but use the functions below for the different log levels.
nil log.fatal (format, ...) 2.4 Log message at appropriate level with printf-like formatting (Lua's string.format).
nil log.error (format, ...) 2.4
nil log.warn (format, ...) 3.1
nil log.normal (format, ...) 2.4
nil log.verbose (format, ...) 2.4
nil log.debug (format, ...) 2.4
nil log.deprecation_warning() (method, replacement, deprecated_since) 2.6 Notify scripting engine that deprecated lua function, or other construct, has been used

game[]

This module is used for game related information.

Module game
(return) type function name / variable arguments ver comments
int game.current_turn () 3.0
int game.turn () Deprecated in 3.0. Use game.current_turn instead. This gives current turn as if game started from turn 0. In freeciv-3.0 and later first turn is turn 1.
int game.current_year () 3.0
int game.current_fragment () 3.0 Year fragment
String game.current_year_text () 3.0 Textual representation of current calendar time
String game.rulesetdir () 3.0 Unique name of the ruleset
String game.ruleset_name () 3.0 Human readable name of the ruleset
Number game.autoupgrade_veteran_loss 3.1 Value of civstyle.autoupgrade_veteran_loss
Number game.upgrade_veteran_loss 3.1 Value of civstyle.upgrade_veteran_loss

find[]

Functions in this module are used to acquire objects for further manipulation, given various kinds of identifying information. Functions are overloaded so that a given object can be identified in several ways.

Module find
(return) type function name / variable arguments ver comments
Player find.player (player_id)
Player find.leader (nation_name) - Missing.
Player find.player (player_name) 3.1
City find.city (player?, city_id)
City find.city (player, city_name) - Missing.
Unit find.unit (player?, unit_id) If player is specified, restricts search to units of that player and returns nil if the unit exists but belongs to someone else.
Tile find.tile (nat_x, nat_y) Native coordinates.
Tile find.tile (tile_id) 2.2.1
Government find.government (government_id)
Government find.government (name)
Nation_Type find.nation_type (nation_type_id)
Nation_Type find.nation_type (name)
Building_Type find.building_type (building_type_id)
Building_Type find.building_type (name)
Unit_Type find.unit_type (unit_type_id)
Unit_Type find.unit_type (name)
Unit_Type find.role_unit_type (role_name, player?) 2.2 If player is not nil, role_unit_type returns the best suitable unit this player can build. If player is nil, returns first unit for that role.
From 2.6.0, role_name can be a unit type flag name, as well as a role name.
Unit find.transport_unit (player, unit_type, tile) 2.3 Return an existing unit that can transport unit_type at tile. Intended to be used with create_unit_full.
Unit_Type find.a_unit_type (role, role_tech) - Missing.
Tech_Type find.tech_type (tech_type_id)
Tech_Type find.tech_type (name)
Terrain find.terrain (terrain_id)
Terrain find.terrain (name)
Action find.action (id) 3.1 Action by id. For use in loops etc. Warning: An action's id may change after saving and reloading the game.
Action find.action (name) 3.1 Action by rule name
Direction find.direction (id) 3.1 Direction by inner number (0 to 7)
Direction find.direction (name) 3.1 Direction by rule name ("Northwest" to "Southeast")
Achievement find.achievement (id) 3.1 Achievement by id
Achievement find.achievement (name) 3.1 Achievement by rule name
Disaster find.disaster (id) 3.1 Disaster by id
Disaster find.disaster (name) 3.1 Disaster by rule name
String find.signal (index) 2.4 Can be used to iterate over all defined signals (until nil is returned).
String find.signal_callback (signal_name, index) 2.4 Can be used to iterate over all callbacks currently associated with a given signal.

effects[]

Calculate the current value of a ruleset effect. Effect names are the same as in rulesets, e.g., "Upkeep_Free".

Module effects
(return) type function name / variable arguments ver comments
Number effects.world_bonus (effect_type_name) 2.3
Number effects.player_bonus (player, effect_type_name) 2.3
Number effects.city_bonus (city, effect_type_name) 2.3

direction[]

Module direction
(return) type function name / variable arguments ver comments
Direction direction.str2dir (str) 2.4 Turns a string like "north", "southwest", etc into a Direction object.
Direction direction.next_ccw (Direction) 2.6 Return next counterclockwise direction in current topology.
Direction direction.next_cw (Direction) 2.6 Return next clockwise direction in current topology.
Direction direction.opposite (Direction) 2.6 Return opposite direction.

datafile[]

Datafile support is added in freeciv-3.1. Ruleset can supply single section file format datafile, with freely selectable content. This lua module is meant for lua implementations that want to parse contents of that datafile.

Module datafile
(return) type function name / variable arguments ver comments
String luadata.get_str (entrykey) 3.1

notify[]

event is an event type from the E module, for example E.SCRIPT. These correspond to the categories that the client can filter on, and are defined in common/events.c.

Module notify
(return) type function name / variable arguments ver comments
nil notify.embassies_msg (player, tile, event, message) Basic function for events. Do not call direct!
nil notify.event_msg (player, tile, event, message) Basic function for events. Do not call direct!
nil notify.all (message) Send all players a message with type E.SCRIPT.
nil notify.player (player?, message) Send a specific player a message with type E.SCRIPT.
nil notify.event (player?, tile?, event, message) Send a specific player or all players (player nil) a message with an arbitrary type, optionally drawing attention to a particular tile.
nil notify.research (player, selfmsg, event, message) 2.6 Send all players sharing research with specific player a message with an arbitrary type. selfmsg is a boolean telling if player should be included to the receivers, or excluded. Setting it to false can be useful if you want to send different message to one actually getting the tech for the team.
nil notify.embassies (player, tile?, event, message) Send a message to all players who have an embassy with player.
nil notify.research_embassies (player, event, message) 2.6 Send a message to all players who have an embassy with someone sharing research with player, that is; to everyone who sees someone gaining a tech when player gains it.

server[]

Module server
(return) type function name / variable arguments ver comments
nil server.save (filename?) 2.4 As with the /save command, if filename is empty, the server chooses an appropriate filename.
Boolean server.started () 2.4
Number server.civilization_score (player) 2.4 Added in 2.3 as (Player).civilization_score()
String server.setting.get (name) 2.4 Return the value of a server setting as a string.
Boolean server.play_music (player, tag) 2.6 Request player's client to play certain track.

edit[]

The edit module was added in 2.4; previously, most of these functions were available with unqualified names (e.g., player_victory()). For these, the "ver" column shows when the original, unadorned function appeared in Freeciv.

Module edit
(return) type function name / variable arguments ver comments
Unit edit.create_unit (player, tile, unit_type, veteran_level, homecity?, moves_left) moves_left: in internal units (3 = a single move), or -1 for the unit's full movement points. veteran_level: 0-3, 0 = "green".
Unit edit.create_unit_full (player, tile, unit_type, veteran_level, homecity?, moves_left, hp_left, transport?) (2.3) More complex version of create_unit() allowing creation of unit already loaded on the Unit passed as transport (use find.transport_unit() to locate suitable transport).
hp_left: -1 means full HP for the unit.
Boolean edit.unit_move (unit, moveto, movecost) 2.4 movecost is in internal units, where 3 = a single move.
Returns false if unit died.
Very few checks -- be careful!
nil edit.movement_disallow (unit) 3.0 Prohibit unit from moving from the spot it's at
nil edit.movement_allow (unit) 3.0 Allow unit to move again
Boolean edit.unit_teleport (unit, dest) 2.4 Moves unit without subtracting move points, then checks if it landed in inhospitable terrain or among enemies.
Returns false if unit died.
nil edit.unit_turn (unit, direction) 2.4 Change unit orientation to face direction.
nil edit.unit_kill (unit, reason, killer) 2.6 Kill unit for reason. If this reason affects scoring credit player killer. See #Unit loss reasonsf or valid values of reason.
New in 3.0.1: reason "editor" allows removing Gameloss units without their owner losing the game.
nil edit.create_base (tile, name, owner) (2.2) Deprecated in 3.0. Use edit.create_owned_extra() instead.
nil edit.create_road (tile, name) 2.5 Deprecated in 2.6. Use edit.create_extra() instead.
nil edit.create_extra (tile, name) 2.6
nil edit.create_owned_extra (tile, name, owner) 3.0 This will claim ownership of any other ownable extras on the tile too.
nil edit.remove_extra (tile, name) 2.6
nil edit.tile_set_label (tile, labelstring) 2.5 Set a textual label for the tile.
nil edit.change_terrain (tile, terrain) 3.0 Set tile terrain
3.1: Boolean, earlier nil edit.create_city (player, tile, name?) If name is nil, one is randomly selected as appropriate for the player's nation.
Player edit.create_player (username, Nation_Type, ai_type?) (2.3) The new player has no units or cities.
ai_type was added in 2.4; it is a string name for an AI module, and in most case should be left as 'nil'.
nil edit.change_gold (player, amount)
Tech_Type edit.give_tech (player, technology?, cost, notify, reason) 2.6 Returns nil if player already has technology. You may pass nil for technology to grant a random tech.
reason is passed to the "tech_researched" script signal.
cost gives percentage from tech's cost applied to the bulb store, or '-1' for normal freecost, '-2' for conquercost, '-3' for diplbulbcost. If notify is set, all parties get notified about the gained tech automatically.
Tech_Type edit.give_technology (player, technology?, reason) Deprecated in 2.6. Use edit.give_tech() instead. Returns nil if player already has technology. You may pass nil for technology to grant a random tech.
reason is passed to the "tech_researched" script signal.
Boolean edit.trait_mod (player, trait, amount) 2.5 Change value of player's trait (a string) by amount. This modification replaces any previous Lua modification, but is relative to the trait value that the player was created with.
Current AI traits are 'Expansionist', 'Trader', 'Aggressive'; see Traits.
Returns false for failure, such as illegal trait name.
nil edit.player_victory (player) 2.4 New in 2.2 as (Player):victory().
Boolean edit.unleash_barbarians (tile) (2.2) Return value is false if any units on the tile were killed (or would have been killed, if there were no units).
nil edit.place_partisans (tile, player, count, sq_radius) (2.3)
Player edit.civil_war (player, probability) 2.4 Possibly throw a player into civil war.
probability is the percentage chance of the civil war occurring (use 100 for certainty), or if it is zero, the normal calculation is used (affected by government, happiness, etc).
Takes no account of the 'civilwarsize' server option (but the player must have at least two cities).
If the chance is not met, nothing happens.
If the chance is met, civil war happens as usual, with appropriate messages sent to the players.
Returns the new AI player, or nil.
nil edit.climate_change (climate_change_type, effect) 2.4 Cause global climate change.
type can be edit.GLOBAL_WARMING or edit.NUCLEAR_WINTER.
effect is the magnitude of the effect (approximately, the number of tiles affected). Does not print any messages, or affect the counters for pollution/fallout-related climate change.
Works regardless of 'global_warming' and 'nuclear_winter' server options.
nil edit.add_player_history (player, amount) 2.6 Add amount of history to player
nil edit.add_city_history (city, amount) 2.6 Add amount of history to city
Boolean edit.perform_action (actor, action[, target[, sub_target]]) 3.1 Force the specified actor to try to perform the specified enabler controlled action. Respects the ruleset rules about when an action is enabled and what consequences performing the action has. May, depending on the action, require a target or a target and a sub_target. The type of actor, target and sub target depends on the action. See doc/README.actions
nil edit.tile_show (tile, player) 3.1 Reveal tile's current map, does not affect fog
Boolean edit.tile_hide (tile, player) 3.1 Completely hide tile from player. Can't hide tiles that are actively seen (not fogged)
void edit.remove_city (city) 3.1
void edit.create_building (city, building) 3.1 Create a building to the city
void edit.remove_building (city, building) 3.1 Remove a building from the city
void edit.give_bulbs (player, amount) 3.1 Give amount bulbs to a player. Might result in a new technology being discovered.
void edit.player_lose (player, looter) 3.2 Kill player. If looter is set, that player gets to loot the former imperium before it's completely removed.

signal[]

Signals are emitted by the server when certain events occurs (see #Events for a list of specific signals).

Signal emission invokes all associated callbacks in the order they were connected. A callback can stop the current signal emission, preventing callbacks connected after it from being invoked, by returning true.

Module signal
(return) type function name / variable arguments ver comments
nil signal.connect (signal_name, callback_name)
nil signal.remove (signal_name, callback_name) 2.4
nil signal.defined (signal_name, callback_name) 2.4
nil signal.replace (signal_name, callback_name) 2.4
nil signal.list () 2.4 List all signals as well as any callbacks, via log.normal(). Intended for debugging.

chat[]

Module chat
(return) type function name / variable arguments ver comments
nil chat.base (message) 2.4 Do not call directly.
nil chat.msg (format, ...) 2.4 Add a message to the local chat window, using string.format to interpolate the rest of the arguments into format.
Does not send anything to the server.

auth[]

See doc/README.fcdb for the use of this module.

Module auth
(return) type function name / variable arguments ver comments
String auth.get_username (Connection) 2.4
String auth.get_ipaddr (Connection) 2.4
Boolean auth.set_password (Connection, password) 2.4
String auth.get_password (Connection) 2.4

fcdb[]

The Freeciv database (fcdb) module.

See doc/README.fcdb for the use of this module.

Module fcdb
(return) type function name / variable arguments ver comments
String fcdb.option (type) 2.4 Use it to get the value of a fcdb option.
In 2.4, this must be one of the parameters fcdb.param.HOST, USER, PORT, PASSWORD, DATABASE, TABLE_USER, TABLE_LOG, BACKEND.
From 2.5, it can be any string (fcdb.param.* mappings are provided for backward compatibility).)

Types[]

Types functions are accessed as members of the module (=type)

module.function(..)

or as a function of a variable of the given type

type t
t:function()

Player[]

Type Player
(return) type function name / variable arguments ver comments
String (Player).name
Nation_Type (Player).nation
Boolean (Player).ai_controlled was ai_data in 2.2, ai in 2.1.
Boolean (Player).is_alive 2.4
Number (Player).id Removed in 2.2.0, restored in 2.2.1.
Government (Player).government 3.1
Boolean (Player):is_human () Same information as ai_controlled.
String (Player):controlling_gui () 3.0
Number (Player):num_cities ()
Number (Player):num_units ()
Boolean (Player):has_wonder (building) 2.2
Boolean (Player):knows_tech (tech) 2.3
Number (Player):gold () 2.3
Iterator (Unit) (Player):units_iterate () 2.3
Iterator (City) (Player):cities_iterate () 2.3
Boolean (Player):exists () 2.4
Boolean (Player):shares_research (Player) 2.5 Not in 2.5.0-beta1.
String (Player):research_rule_name () 2.6
String (Player):research_name_translation () 2.6 Names the set of players who share research (may be an individual player or a team name).
Number (Player):culture () 2.6 Current culture score (total of city and nation history and performance).
Unit_Type (Player):can_upgrade (Unit_Type) 3.1 A unit type to which the player in general can upgrade the given one ("Unit_Upgrade" action enablers are not regarded), or nil if no upgrade is possible.
Boolean (Player):can_build_direct (Building_Type) 3.1 Does the player in general can build the improvement, including hardcoded rules (like, number of spaceship parts that can be placed).
Boolean (Player):can_build_direct (Unit_Type) 3.1 Does the player in general can build the unit, at least after building a necessary improvement. Considers unit flags and roles but not if the type is obsoleted by another one.
Unit (Player):create_unit (tile, unit_type, veteran_level, homecity?, moves_left) 2.4 See edit.create_unit().
Unit (Player):create_unit_full (tile, unit_type, veteran_level, homecity?, moves_left, hp_left, transport?) 2.4 See edit.create_unit_full().
3.1: Boolean, earlier nil (Player):create_city (tile, name) 2.4 See edit.create_city().
nil (Player):change_gold (amount) 2.4 See edit.change_gold().
Tech_Type (Player):give_tech (technology?, cost, reason) 2.6 See edit.give_tech().
Tech_Type (Player):give_technology (technology?, reason) 2.4 Deprecated in 2.6. Use Player:give_tech() instead. See edit.give_technology().
Player (Player):civil_war (probability) 2.4 See edit.civil_war().
nil (Player):victory () 2.2 See edit.player_victory().
Number (Player):civilization_score () 2.3 See server.civilization_score().
Number (Player):trait (trait) 2.6 Return current numeric value of AI trait trait in effect for player. This is usually trait_base()+trait_current_mod(). See edit.trait_mod for traits.
Number (Player):trait_base (trait) 2.6 Return base value of trait for player (chosen at game start, before any trait_mod)
Number (Player):trait_current_mod (trait) 2.6 Return current value of trait modification set by trait_mod().
Boolean (Player):trait_mod (trait, amount) 2.5 Adjust AI trait value. See edit.trait_mod.
nil (Player):add_history (amount) 2.6 See edit.add_player_history
nil (Player):give_bulbs (amount) 3.1 See edit.give_bulbs
nil (Player):lose (Player looter) 3.2 See edit.player_lose

City[]

Type City
(return) type function name / variable arguments ver comments
String (City).name
Player (City).owner
Player (City).original 2.3 The player who originally built the city.
Tile (City).tile 2.4 was variable up to 2.3
Number (City).size 2.4 was variable in 2.3
Number (City).id
Boolean (City):has_building (building) 2.2
Boolean (City):exists () 2.2.1
Number (City):map_sq_radius () 2.3
Number (City):inspire_partisans (inspirer) 2.5 Returns whether the city would produce partisans if conquered from player inspirer, taking into account original owner, nationality, and the 'Inspire_Partisans' effect.
The default 'city_transferred' (in case of freeciv-2.5 and earlier: 'city_lost') handler treats the return from this as boolean (greater than zero gives partisans), but a custom handler and ruleset could give different behaviour with different values of the 'Inspire_Partisans' effect.
Number (City):culture () 2.6 Current total culture score (sum of history and performance).
nil (City):add_history (amount) 2.6 See edit.add_city_history
Boolean (City):is_happy () 2.6
Boolean (City):is_unhappy () 2.6
Boolean (City):is_celebrating () 2.6
Boolean (City):is_capital () 2.6
Boolean (City):is_primary_capital () 3.1
Boolean (City):is_gov_center () 2.6
String (City):link_text () 3.1 Link string fragment to add to messages sent to client. If city is going to be removed, use tile_link_text() instead.
String (City):tile_link_text () 3.1 Link string fragment to add to messages sent to client.
nil (City):remove () 3.1 See edit.remove_city
nil (City):create_building (building) 3.1 See edit.create_building
nil (City):remove_building (building) 3.1 See edit.remove_building

Unit[]

Type Unit
(return) type function name / variable arguments ver comments
Unit_Type (Unit).utype
Player (Unit).owner
Number (Unit).homecity was (Unit).homecity_id in 2.1.
Number (Unit).veteran 3.1 Veteran rank number, starts at 0.
Tile (Unit).tile 2.4 was variable up to 2.3.
Number (Unit).id
City (Unit):get_homecity () Same information as homecity.
Was (Unit):homecity() in 2.1.
Boolean (Unit):is_on_possible_city_tile () 2.2 Could a settler unit build a city here?
Unit (Unit):transporter () 2.6 Unit that this one is loaded on, or nil
Iterator (Unit) (Unit):cargo_iterate () 2.6 Iterates over units directly transported by this one, if any. Does not include nested units.
Boolean (Unit):exists () 2.2.1
Direction (Unit):facing () 2.4 The current unit orientation.
String (Unit):link_text () 3.1 Link string fragment to add to messages sent to client. If unit is going to be removed, use tile_link_text() instead.
String (Unit):tile_link_text () 3.1 Link string fragment to add to messages sent to client.
Unit_Type (Unit):can_upgrade (Unit, is_free = true) 3.1 Returns potential upgrade target type for the unit, or nil if it can't upgrade. If is_free is false, regards the owner's treasury and that the unit is in domestic city, otherwise returns the latest unit type obsoleting current one that the owner can build.
String (Unit):transform_problem (Unit_Type) 3.1 If the unit may be transformed right now to the type, returns nil, otherwise names a factor that prevents transformation: "cargo", "transport" or "terrain".
Boolean (Unit):move (moveto, movecost) 2.4 See edit.unit_move().
nil (Unit):movement_disallow () 3.0 See edit.movement_disallow().
nil (Unit):movement_allow () 3.0 See edit.movement_allow().
Boolean (Unit):teleport (dest) 2.4 See edit.unit_teleport().
Boolean (Unit):perform_action (action[, target[, sub_target]]) 3.1 See edit.perform_action().
nil (Unit):turn (direction) 2.4 See edit.unit_turn().
nil (Unit):kill (reason, killer) 2.6 See edit.unit_kill().
Boolean (Unit):upgrade (vet_loss = 0) 3.1 Works like self:transform(self:can_upgrade(), vet_loss) if the unit can be upgraded, does not change the owner's gold.
Boolean (Unit):transform (Unit_Type utype, int vet_loss = 0) 3.1 Transforms the unit to utype, returns true iff it is possible. Health and move rate are scaled proportionally. Veteran rank is if necessary truncated to the new veteran system size, and then it may be reduced at vet_loss levels (may be negative).

Tile[]

Type Tile
(return) type function name / variable arguments ver comments
Number (Tile).nat_x Native coordinate.
Number (Tile).nat_y Native coordinate.
Number (Tile).x 2.4 Map coordinate.
Number (Tile).y 2.4 Map coordinate.
Terrain (Tile).terrain
Number (Tile).id
Player (Tile).owner 3.1
Player (Tile):extra_owner (extra_name) 3.1 Returns the owner of the extra specified as a string in extra_name. Will return the owner of the first extra if extra_name is nil.
Boolean (Tile):city_exists_within_city_radius (may_be_on_center) Deprecated in 2.3; use the next one instead.
Boolean (Tile):city_exists_within_max_city_map (may_be_on_center) 2.3 Returns true if there is a city within the maximum radius a city map can ever have in Freeciv (not necessarily possible in the current ruleset) -- currently within 5 tiles.
City (Tile):city () 2.3
Number (Tile):num_units () 2.3
Number (Tile):sq_distance (Tile) 2.3 Returns squared distance between tiles.
bool (Tile):has_base (name) 2.4 name may be either 'Fortress', 'Airbase', 'Buoy', or any base type defined in the ruleset.
bool (Tile):has_road (name) 2.5 name may be either 'Road', 'Railroad', 'River', or any road type defined in the ruleset.
bool (Tile):has_extra (name) 2.6 name may be either the name of any extra type (base, road, special; from 3.0 also resource).
bool (Tile):is_enemy (against) 3.0 Is there enemies of the against on the tile
Iterator (Unit) (Tile):units_iterate () 2.3
Iterator (Tile) (Tile):square_iterate (radius) 2.3 square_iterate(1) returns 9 tiles
Iterator (Tile) (Tile):circle_iterate (sq_radius) 2.3 circle_iterate(1) returns 5 tiles
nil (Tile):create_base (name, player) 2.4 Deprecated in 3.0. Use (Tile):create_owned_extra() instead.
nil (Tile):create_road (name) 2.5 Deprecated in 2.6. See edit.create_road().
nil (Tile):create_extra (name) 2.6 See edit.create_extra().
nil (Tile):create_owned_extra (name) 3.0 See edit.create_owned_extra().
nil (Tile):remove_extra (name) 2.6 See edit.remove_extra().
Boolean (Tile):unleash_barbarians () 2.4 See edit.unleash_barbarians().
nil (Tile):place_partisans (player, count, sq_radius) 2.4 See edit.place_partisans().
nil (Tile):set_label (labelstring) 2.5 See edit.tile_set_label().
nil (Tile):change_terrain (terrain) 3.0 See edit.change_terrain().
nil (Tile):show (player) 3.1 See edit.tile_show().
Boolean (Tile):hide (player) 3.1 See edit.tile_hide().

Government[]

Type Government
(return) type function name / variable arguments ver comments
Number (Government).id
String (Government):rule_name () 2.2
String (Government):name_translation () 2.2

Nation_Type[]

Type Nation_Type
(return) type function name / variable arguments ver comments
Number (Nation_Type).id
String (Nation_Type):rule_name () 2.2
String (Nation_Type):name_translation () 2.2 Adjective for nation.
String (Nation_Type):plural_translation () 2.2 Plural name for nation.
Number (Nation_Type):trait_min (trait) 2.6 Return minimum possible start value of AI trait for nation. See Traits.
Number (Nation_Type):trait_max (trait) 2.6 Return maximum possible start value of AI trait for nation.
Number (Nation_Type):trait_default (trait) 2.6 Return default start value of AI trait for nation used when server option 'traitdistribution' is FIXED.

Building_Type[]

Type Building_Type
(return) type function name / variable arguments ver comments
Number (Building_Type).build_cost
Number (Building_Type).id
Number (Building_Type):build_shield_cost () Same information as build_cost.
Boolean (Building_Type):is_wonder ()
Boolean (Building_Type):is_great_wonder ()
Boolean (Building_Type):is_small_wonder ()
Boolean (Building_Type):is_improvement ()
String (Building_Type):rule_name () 2.2
String (Building_Type):name_translation () 2.2

Unit_Type[]

Type Unit_Type
(return) type function name / variable arguments ver comments
Number (Unit_Type).build_cost
Unit_Type (Unit_Type).obsoleted_by 3.1 Immediate obsoleting type.
Number (Unit_Type).id
Boolean (Unit_Type):has_flag (flag_name)
Boolean (Unit_Type):has_role (role_name)
Boolean (Unit_Type):can_exist_at_tile (tile) 2.3
Number (Unit_Type):build_shield_cost () Same information as build_cost.
String (Unit_Type):rule_name () 2.2
String (Unit_Type):name_translation () 2.2

Tech_Type[]

Type Tech_Type
(return) type function name / variable arguments ver comments
Number (Tech_Type).id
String (Tech_Type):rule_name () 2.2
String (Tech_Type):name_translation () 2.2

Terrain[]

Type Terrain
(return) type function name / variable arguments ver comments
Number (Terrain).id
String (Terrain):rule_name () 2.2
String (Terrain):name_translation () 2.2
String (Terrain):class_name () 2.6

Disaster[]

Type Disaster
(return) type function name / variable arguments ver comments
Number (Disaster).id 2.5
String (Disaster):rule_name () 2.5
String (Disaster):name_translation () 2.5

Achievement[]

Type Achievement
(return) type function name / variable arguments ver comments
Number (Achievement).id 2.6
String (Achievement):rule_name () 2.6
String (Achievement):name_translation () 2.6

Connection[]

Type Connection
(return) type function name / variable arguments ver comments
Number (Connection).id 2.4

Direction[]

Note: Direction support was partially broken before v.2.6.3: freeing a direction Lua object made applications to crash. Also, the same direction retrieved several times produced different objects not equal in == operator.

Type Direction
(return) type function name / variable arguments ver comments
Direction (Direction):next_ccw () 3.1 Return next counterclockwise direction in current topology.
Direction (Direction):next_cw () 3.1 Return next clockwise direction in current topology.
Direction (Direction):opposite () 3.1 Return opposite direction.
int (Direction).id () 3.1 Returns direction number (0 to 7).
string (Direction).name () 3.1 Returns direction name ("Northwest" to "Southeast").

Action[]

Type Action
(return) type function name / variable arguments ver comments
Number (Action).id 2.6
String (Action):rule_name () 2.6
String (Action):name_translation () 2.6 Possible values - "Establish Embassy", "Investigate City", "Poison City", "Steal Gold", "Sabotage City", "Targeted Sabotage City", "Steal Tech", "Targeted Steal Tech", "Incite City", "Establish Trade Route", "Enter Marketplace", "Help Wonder", "Bribe Unit", "Sabotage Unit"
String (Action):target_kind () 3.1 Main target type returned as a string.

Nonexistent[]

Type Nonexistent
(return) type function name / variable arguments ver comments
Boolean (Nonexistent):exists () 2.2.1

Functions[]

Internationalization[]

String translation functions are used for localizable event scripts included with Freeciv (ruleset and tutorial). See Internationalization for what these functions do.

Functions Internationalization
(return) type function name / variable arguments ver comments
String _ (msg)
String N_ (msg)
String Q_ (msg)
String PL_ (singular, plural, n)

Utilities[]

Functions Utilities
(return) type function name / variable arguments ver comments
Number random (min, max) Returns a random number using Freeciv's random number generator and random seeds. This allows reproducible games given the same initial conditions and inputs. Use this rather than Lua's math.random.
String fc_version () 2.4
nil error_log (message) 2.2 Deprecated since 2.4. Use log.error instead.
nil debug_log (message) 2.2 Deprecated since 2.4. Use log.debug instead.
Iterator (Player) players_iterate () 2.3
Iterator (Tile) whole_map_iterate () 2.3
Direction str2direction (str) 2.4 See direction.str2dir().

Script debugging[]

The following functions are helpful in debugging lua scripts:

Functions debugging
(return) type function name / variable arguments ver comments
nil listenv () 2.4 List all defined lua variables and functions.
String _freeciv_state_dump () Dump the state of user scalar variables to a Lua code string.
This is used internally when saving a game file. It can be used interactively to see what will and won't be saved.
nil signal.list () 2.4 See signals
String fc_version () 2.4 See utilities
String _VERSION Lua language version, a global variable treated as constant.
... assert (value ,message?) Basic Lua function; creates only a log.fatal() message for a false or nil value in server scripts (game not aborted).

Editing actions[]

These unqualified function names are deprecated as of 2.4. Use the equivalent functions in the edit module instead.

Functions Edit
(return) type function name / variable arguments ver comments
Unit create_unit (player, tile, unit_type, veteran_level, homecity?, moves_left) Deprecated in 2.4. Use edit.create_unit() instead.
Unit create_unit_full (player, tile, unit_type, veteran_level, homecity?, moves_left, hp_left, transport?) 2.3 Deprecated in 2.4. Use edit.create_unit_full() instead.
nil create_base (tile, name, player) 2.2 Deprecated in 2.4. Use edit.create_base() instead.
nil create_city (player, tile, name) Deprecated in 2.4. Use edit.create_city() instead.
Player create_player (username, Nation_Type) 2.3 Deprecated in 2.4. Use edit.create_player() instead (although note that it has an extra argument).
nil change_gold (player, amount) Deprecated in 2.4. Use edit.change_gold() instead.
Tech_Type give_technology (player, technology?, reason) Deprecated in 2.4. Use edit.give_tech() in 2.6 or later, edit.give_technology() in 2.4 or 2.5.
Boolean unleash_barbarians (tile) 2.2 Deprecated in 2.4. Use edit.unleash_barbarians() instead.
nil place_partisans (tile, player, count, sq_radius) 2.3 Deprecated in 2.4. Use edit.place_partisans() instead.
Boolean trait_mod (player, trait, amount) 2.5 Deprecated. Use edit.trait_mod() instead.

Events[]

Connect to an event signal using

signal.connect(signal_name, callback_name)

Currently, signals are only sent to ruleset scripts running on the server. The set of signals is defined in server/scripting/script_server.c (search for "script_server_signals_create").

Signals server
(return) type function name / variable arguments ver comments
Boolean turn_begin (Number turn, Number year) 3.0 In freeciv-3.0 and later this gives first turn as 1.
Boolean turn_started (Number turn, Number year) Deprecated in 3.0. Use turn_begin instead. This gives first turn as 0.
Boolean unit_moved (Unit unit, Tile src_tile, Tile dst_tile) Emitted at the end of a unit_move()
Boolean city_built (City city)
Boolean city_size_change (City city, Number change, String reason) 2.6 Reason is one of "growth", "famine", "bombard", "attack", "upkeep_failure", "unit_built", "plague", "conquest", "migration_from", "migration_to", "disaster", "poison", "incited", or "nuke"
Boolean city_growth (City city, Number city_size) Deprecated in 2.6. Use city_size_change instead.
Boolean unit_built (Unit unit, City city)
Boolean building_built (Building_Type type, City city)
Boolean city_transferred (City city, Player loser, Player winner, String reason) 2.6 Reason is one of "conquest", "trade", "incited", "civil_war", "death-back_to_original", or "death-barbarians_get"
Boolean city_lost (City city, Player loser, Player winner) 2.2 Deprecated in 2.6. Use city_transferred instead.
Boolean city_destroyed (City city, Player loser, Player destroyer) 2.2
Boolean unit_lost (Unit unit, Player loser, String reason) 2.2 reason added in 2.4. See #Unit loss reasons
Boolean unit_cant_be_built (Unit unit, City city, String reason) reason may be: "need_tech", "pop_cost", "never", "unavailable"
Boolean building_cant_be_built (Building_Type type, City city, String reason) reason may be: "need_tech", "need_building", "need_special", "need_terrain", "need_government", "need_nation", "need_minsize", "need_ai_level", "need_terrainclass", "need_minyear", "never", "unavailable".
Boolean building_lost (City city, Building_Type type, String reason, Unit destroyer) 3.0 reason may be: "landlocked", "cant_maintain", "obsolete", "sold", "disaster", "sabotaged", "razed", "city_destroyed", "conquered" (applicable for Small Wonders only). destroyer is applicable for "sabotaged" only.
Boolean nuke_exploded (Tile tile, Player player) 3.0
Boolean tech_researched (Tech_Type type, Player player, String source) source may be: "researched", "traded", "stolen", "hut".
Boolean hut_enter (Unit unit, New in 3.0 Extra name) 2.6.0: Generated for any extra of category "Bonus" after it is removed if some extra on the tile has cause "Hut".
Boolean hut_frighten (Unit unit, Extra name) 3.0
Boolean map_generated () 2.5
Boolean disaster_occurred (Disaster disaster, City city, Boolean had_internal_effect) 2.6
Boolean disaster (Disaster disaster, City city) 2.5 Deprecated in 2.6. Use disaster_occurred instead.
Boolean pulse () 2.6 Time between pulses is not constant - this can't be used to measure time.
Boolean achievement_gained (Achievement achievement, Player gainer, Boolean first) 2.6 first indicates whether player is first one to reach the achievement.
Boolean action_started_unit_city (Action action, Unit actor, City target) 2.6 Action started signals are called after it is known that an action is legal but before it is known whether it succeeds.
See file ...doc/README.actions for more info about Actions.
This specific signal is called when a unit acts against a city. Possible values for action are "Establish Embassy", "Establish Embassy Stay", "Investigate City", "Investigate City Spend Unit", "Sabotage City", "Sabotage City Escape", "Targeted Sabotage City", "Targeted Sabotage City Escape", "Poison City", "Poison City Escape", "Steal Tech", "Steal Tech Escape Expected", "Targeted Steal Tech", "Targeted Steal Tech Escape Expected", "Incite City", "Incite City Escape", "Steal Gold", "Steal Gold Escape", "Steal Maps", "Steal Maps Escape", "Suitcase Nuke", "Suitcase Nuke Escape", "Destroy City", "Establish Trade Route", "Enter Marketplace", "Help Wonder" , "Recycle Unit", "Join City", "Home City", "Upgrade Unit", "Airlift Unit", "Conquer City"
Boolean action_started_unit_unit (Action action, Unit actor, Unit target) 2.6 Called when a unit acts against another single unit. Possible values for action are "Sabotage Unit", "Sabotage Unit Escape", "Bribe Unit", "Expel Unit", "Heal Unit".
Boolean action_started_unit_units (Action action, Unit actor, Tile target) 3.0 Called when a unit acts against all (one or more) units on a tile. Possible values for action are "Capture Units", "Bombard", "Attack".
Boolean action_started_unit_tile (Action action, Unit actor, Tile target) 3.0 Called when a unit acts against a tile. Possible values for action are "Found City", "Explode Nuclear", "Paradrop Unit".
Boolean action_started_unit_extras (Action action, Unit actor, Tile target) 3.1 Called when a unit acts against a tile's extras.
Boolean action_started_unit_self (Action action, Unit actor) 3.0 Called when a unit acts on itself. Possible value for action is "Disband Unit".
Boolean action_finished_unit_city (Action action, Boolean result, Unit actor, City target) 3.1 When action finshed signals are called, action might have already destroyed actor or target. Those are nil in that case.
See file ...doc/README.actions for more info about Actions. Possible values for action are same as for matching action started signal
This specific signal is called when a unit acts against a city.
Boolean action_finished_unit_unit (Action action, Boolean result, Unit actor, Unit target) 3.1 Called when a unit acts against another single unit.
Boolean action_finished_unit_units (Action action, Boolean result, Unit actor, Tile target) 3.1 Called when a unit acts against all (one or more) units on a tile.
Boolean action_finished_unit_tile (Action action, Boolean result, Unit actor, Tile target) 3.1 Called when a unit acts against a tile.
Boolean action_finished_unit_extras (Action action, Boolean result, Unit actor, Tile target) 3.1 Called when a unit acts against a tile's extras.
Boolean action_finished_unit_self (Action action, Boolean result, Unit actor) 3.1 Called when a unit acts on itself.
Boolean player_phase_begin (Player player, Boolean new_phase) 3.1 Beginning of player's phase (before units perform random and pre-ordered moving). new_phase can be FALSE if the game is just starting from a saved game.
Boolean player_alive_phase_end (Player player) 3.1 End of alive player's phase (before units' hp/mp restoration)
Boolean player_phase_end (Player player) 3.1 End of any player's phase (after all phase end processing and before advisors/AI end phase analysis).
Signals client
(return) type function name / variable arguments ver comments
Boolean new_tech () 2.4 Placeholder, no effect

Unit loss reasons[]

Loss reasons are supplied to show in what case an event of destroying a unit happens; also, specifying different reasons in (Unit):kill() has different side effects, predominantly on the loser's "units lost" score and the killer's "units killed" score (if the killer is specified).

Reason Game event Loser score Killer score
"killed" a) Unit loses a battle
b) Paradropped on enemy unit tile (killer player not specified)
Yes Yes
"executed" Since 2.6: never; before: when establishing embassy to a "No_Diplomacy" affected nation Yes Yes
"retired" Happens to barbarians with no targets around No No
"disbanded" a) Killed by shields upkeep
b) Disbanded by user request
No No
"barb_unleash" Killed in a barbarian uprising on its tile from a hut or by script Yes No
"city_lost" a) An unique unit is transferred with a city to a player having such one
b) A unit from a lost city can't be rehomed to another city
c) Destruction of a city left a unit on its tile on unsuitable terrain, or deprived an adjacent city or a cascade of cities of sea connection.

Cargo of a transport wiped for this reason won't be evacuated to the transport's home city.

Yes No
"starved", Killed for food upkeep Yes No
"sold" Killed by gold upkeep Yes No
"used" Spent in a successful action (except disbanding, nuking and suicide attack, or diplomatic actions) No No
"eliminated" Lost in a diplomatic battle Yes Yes
"editor" Edited out

Gameloss unit removed with this cause won't make its owner losing the game

No No
"nonnative_terr" a) Got to a nonnative terrain by edit.unit_teleport or paradropping
b) Could not be bounced from a terrain change
Yes No
"player_died" All what has remained of a nation of a lost player is wiped completely No No
"armistice" A military unit stays in a peaceful territory at turn end Yes No
"sdi" A nuke was unsuccessful against SDI defense Yes Yes
"detonated" A nuke was successfully exploded No No
"missile" A suicide attack or wiping units is performed No No
"nuke" Killed by a nuclear blast Yes Yes
"hp_loss" Lost all hitpoints in the open Yes No
"fuel" Lost all fuel in the open Yes No
"stack_conflict" a) Could not bounce out of a tile with non-allied units or city
b) Moved to non-allied city or unit tile by edit.unit_teleport()
Yes No
"bribed" Bribed by enemy diplomat. At v.3.1 and earlier, when a signal is called thus to an old unit, new one is created. Yes Yes*
"captured" Captured by enemy unit. At v.3.1 and earlier, when a signal is called thus to an old unit, new one is created. Yes Yes*
"caught" a) A diplomatic action failed from the beginning
b) A diplomat could not escape after performing an action
Yes Yes**
"transport_lost" Transport of a unit is destroyed and it could not be rescued Yes Yes

* - At v.3.1 and earlier, the killer can be specified only by a script.

** - Killer submitted only if the action was failed

Examples[]

Simple examples[]

  • Send the message 'Hello, World!' to all the players upon each new turn:
  function hello_callback(turn, year)
      notify.all('Hello, World!')
      return false
  end
  
  signal.connect('turn_started', 'hello_callback')


  • Get Lua and Freeciv version; show connected signals:
  notify.event( nil, nil, E.CHAT_MSG, '[c fg="#006400"].lua: %s with %s[/c]', fc_version(), _VERSION )
  signal.list()


  • Show some visible output at all costs (verbatim .. is concatenation, ... is varargs ):
  function radius_info( msg, ... )     -- command echo green #006400
    msg = "radius: " .. msg            -- radius is the ruleset name
    log.verbose( msg, ... )            -- verbose log output (-d 3)
    print( string.format( msg, ... ))  -- stdout (standalone server)
    msg = "[c fg=\"#006400\"]" .. msg .. "[/c]"
    notify.event( nil, nil, E.CHAT_MSG, msg, ... )
  end

Advanced Examples[]

Please read the Events Tutorial for examples of the most important concepts.

Part of Freeciv's ruleset is implemented in Lua. It can serve as an advanced example. Look at the files data/default/default.lua and (for example) data/civ2civ3/script.lua in Freeciv's data directory.

Caveats[]

  • A ruleset with syntax errors in script.lua or the default script cannot be loaded, and the position of the syntax error is not reported.
  • The state of structured variables including tables and signals is not saved, only (simple) strings, numbers, and booleans are recorded.
  • Runtime errors incl. assert(false) do not terminate the game.
  • In boolean expressions only nil and false are interpreted as false; everything else including 0 and true is interpreted as true.
  • For a server started implicitly by the client in single-user games print() output ends up nowhere on Windows, use something like notify.all() for printf-debugging.
  • The client Lua window is basically pointless, the only working output method is chat.msg() ending up in the chat window.
  • File access functions do not work, the Lua io and os libraries are disabled to get a mostly harmless sandbox.

Lua[]

Lua.png

The language used for Freeciv event scripts is Lua. A Lua language version string is available as global variable _VERSION:

Lua manuals are available online and as tarballs for offline reading, e.g., http://www.lua.org/ftp/refman-5.3.tar.gz (April 2017). Various tutorials are offered by lua-users.org. An older Lua 5.0 manual is also available as PDF.

Lua Builtins[]

Some Lua builtin functions and modules are also available in Freeciv (some functionality is intentionally left out by policy). It is not our intention to document Lua builtins here, but just to mention a selection of the useful parts.

Functions

  Boolean, [Results]       pcall(f, arg1, ...)
  Iterator (Key, Object)   pairs(table)
  Iterator (Index, Object) ipairs(table)

Variables

  Table   _G   -- The global environment (all variables) as a table.

Modules

  math         -- math.sqrt and other useful functions
               -- Important: never use math.random. Always use freeciv's random(min, max)
  string       -- string handling incl. regular expressions
  table        -- table.sort can sort an array-like table

Reference Links[]

The Scripting API is defined in *.pkg files, and that must be the canonical reference to this API.

Links for the current development code (trunk) can be found at #Legend. For older/stable branches, see the following table. Please see these links for future updates, or if you suspect something in this Reference is wrong.

Version scriptcore server events client fcdb
common_a common_z game signal
3.1 pkg pkg pkg pkg pkg c pkg pkg
3.0 pkg pkg pkg pkg pkg c pkg pkg
2.6 pkg pkg pkg pkg pkg c pkg pkg
2.5 pkg pkg pkg pkg pkg c pkg pkg
2.4 pkg pkg pkg pkg pkg c pkg pkg
2.3 api.pkg c N/A
2.2 api.pkg c
2.1 api.pkg c

See also[]

Event Scripting
Lua Reference ManualTutorial Scenario
Update from 2.5 to 2.62.6 to 3.03.0 to 3.1
Advertisement