FANDOM


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.

LegendEdit

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.

ModulesEdit

Module functions are accessed as members of the module:

module.function(..)

const Edit

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

log Edit

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 Edit

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

find Edit

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) - Missing.
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.
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)
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 Edit

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 Edit

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.

datafile Edit

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 Edit

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 Edit

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 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.
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 the unit_lost() signal for valid values of reason.
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
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

signal Edit

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 Edit

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 Edit

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 Edit

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 Edit

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 Edit

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.
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 (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().
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

City Edit

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_gov_center () 2.6

Unit Edit

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.
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.
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().
nil (Unit):turn (direction) 2.4 See edit.unit_turn().
nil (Unit):kill (reason, killer) 2.6 See edit.unit_kill().

Tile Edit

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
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
Iterator (Tile) (Tile):circle_iterate (sq_radius) 2.3
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().

Government Edit

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 Edit

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 Edit

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 Edit

Type Unit_Type
(return) type function name / variable arguments ver comments
Number (Unit_Type).build_cost
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 Edit

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 Edit

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 Edit

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 Edit

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 Edit

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

Direction Edit

Type Direction
(return) type function name / variable arguments ver comments
Direction (Direction):next_ccw () 2.6 Return next counterclockwise direction in current topology.
Direction (Direction):next_cw () 2.6 Return next clockwise direction in current topology.
Direction (Direction):opposite () 2.6 Return opposite direction.

Action Edit

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

Nonexistent Edit

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

Functions Edit

Internationalization Edit

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 Edit

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 Edit

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 Edit

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 Edit

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
Boolean turn_started (Number turn, Number year) Deprecated in 3.0. Use turn_begin instead. This gives turn number as if first turn was turn 0. In freeciv-3.0 and later first turn is turn 1.
Boolean unit_moved (Unit unit, Tile src_tile, Tile dst_tile)
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. Can be one of: "killed", "retired", "disbanded", "barb_unleash", "city_lost", "starved", "sold", "used", "executed", "eliminated", "editor", "nonnative_terr", "player_died", "armistice", "sdi", "detonated", "missile", "nuke", "hp_loss", "fuel", "stack_conflict", "bribed", "captured", "caught" or "transport_lost"
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: "pop_cost", "need_tech", "need_building", "need_special", "need_terrain", "need_government", "need_nation", "need_minsize", "need_ai_level", "need_terrainclass", "need_minyear", "never", "unavailable".
Boolean tech_researched (Tech_Type type, Player player, String source) source may be: "researched", "traded", "stolen", "hut".
Boolean hut_enter (Unit unit) From 2.6 this is generated for any extra of category "Bonus".
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 signals are called after it is known that an action is legal but before it is known whether it succeeds.
This specific signal is called when a unit acts against a city.
Boolean action_started_unit_unit (Action action, Unit actor, Unit target) 2.6 Called when a unit acts against another single unit.
Boolean action_started_unit_units (Action action, Unit actor, Tile target) 3.0 Called when a unit acts against several units on a tile.
Boolean action_started_unit_tile (Action action, Unit actor, Tile target) 3.0 Called when a unit acts against a tile.
Boolean action_started_unit_self (Action action, Unit actor) 3.0 Called when a unit acts on itself.
Signals client
(return) type function name / variable arguments ver comments
Boolean new_tech () 2.4 Placeholder, no effect

ExamplesEdit

Simple examplesEdit

  • 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 Edit

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.

CaveatsEdit

  • 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 Edit

Lua

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 Edit

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 Edit

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.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 Edit

How to update from an old to the next...
tileset 1.14 to 2.0 2.0 to 2.1 2.1 to 2.2 2.2 to 2.3 2.3 to 2.4 2.4 to 2.5 2.5 to 2.6 2.6 to 3.0 3.0 to 3.1
ruleset n/a n/a n/a 2.2 to 2.3 2.3 to 2.4 2.4 to 2.5 2.5 to 2.6 2.6 to 3.0 3.0 to 3.1
script.lua n/a n/a n/a n/a n/a n/a 2.5 to 2.6 2.6 to 3.0 3.0 to 3.1

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.