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.

|- style="background:#EEE;color:black"

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:

|- style="background:#EEE;color:black"

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.

Module log
(return) type function name / variable arguments ver comments
- log.base (level, message) 2.4 Do not call this function directly but use the functions below for the different log levels.
- log.fatal (message) 2.4
- log.error (message) 2.4
- log.normal (message) 2.4
- log.verbose (message) 2.4
- log.debug (message) 2.4

game

This module is used for game related information.

Module game
(return) type function name / variable arguments ver comments
int game.turn ()

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

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:opposite (dir) 2.6 Returns opposite direction.
Direction direction:next_cw (dir) 2.6 Returns next direction clockwise.
Direction direction:next_ccw (dir) 2.6 Returns next direction counter clockwise.

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
- notify.embassies_msg (player, tile, event, message) Basic function for events. Do not call direct!
- notify.event_msg (player, tile, event, message) Basic function for events. Do not call direct!
- notify.all (message) Send all players a message with type E.SCRIPT.
- notify.player (player?, message) Send a specific player a message with type E.SCRIPT.
- 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.
- notify.embassies (player, tile?, event, message) Send a message to all players who have an embassy with player.

server

Module server
(return) type function name / variable arguments ver comments
- 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.
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!
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.
- edit.unit_turn (unit, direction) 2.4 Change unit orientation to face direction.
- edit.create_base (tile, name, player?) (2.2) player is the owner for territory-claiming base types.
- edit.create_road (tile, name) 2.5
- edit.create_extra (tile, name) 2.6
- edit.tile_set_label (tile, labelstring) 2.5 Set a textual label for the tile.
- 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'.
- edit.change_gold (player, amount)
Tech_Type edit.give_technology (player, technology?, reason) 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, mod) 2.5 Change value of player's trait by amount mod. 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.
- 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).
- 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.
- 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.
- edit.add_player_history (player, amount) 2.6 Add amount of history to player
- edit.add_city_history (city, amount) 2.6 Add amount of history to city

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
- signal.connect (signal_name, callback_name)
- signal.remove (signal_name, callback_name) 2.4
- signal.defined (signal_name, callback_name) 2.4
- signal.replace (signal_name, callback_name) 2.4
- 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
- chat.base (message) 2.4 Do not call directly.
- 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.
Boolean (Player):is_human () Same information as ai_controlled.
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.
Number (Player):culture  () 2.6
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().
- (Player):create_city (tile, name) 2.4 See edit.create_city().
- (Player):change_gold (amount) 2.4 See edit.change_gold().
Tech_Type (Player):give_technology (technology?, reason) 2.4 See edit.give_technology().
Player (Player):civil_war (probability) 2.4 See edit.civil_war().
- (Player):victory () 2.2 See edit.player_victory().
Number (Player):civilization_score () 2.3 See server.civilization_score().
- (Player):add_history (amount) 2.6 See edit.add_player_history

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_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
- (City):add_history (amount) 2.6 See edit.add_city_history

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.
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?
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().
Boolean (Unit):teleport (dest) 2.4 See edit.unit_teleport().
- (Unit):turn (direction) 2.4 See edit.unit_turn().

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
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 a base or a road type. See (Tile):has_base() and (Tile):has_road().
Iterator (Unit) (Tile):units_iterate () 2.3
Iterator (Tile) (Tile):square_iterate (radius) 2.3
Iterator (Tile) (Tile):circle_iterate (sq_radius) 2.3
- (Tile):create_base (name, player) 2.4 See edit.create_base().
- (Tile):create_road (name) 2.5 See edit.create_road().
Boolean (Tile):unleash_barbarians () 2.4 See edit.unleash_barbarians().
- (Tile):place_partisans (player, count, sq_radius) 2.4 See edit.place_partisans().
- (Tile):set_label (labelstring) 2.5 See edit.tile_set_label().

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
String (Nation_Type):plural_translation () 2.2

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
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 (Achivement):name_translation () 2.6

Connection

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


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

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
- error_log (message) 2.2 Deprecated since 2.4. Use log.error instead.
- 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().

Actions

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

Functions Action
(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.
- create_base (tile, name, player) 2.2 Deprecated in 2.4. Use edit.create_base() instead.
- 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).
- 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_technology() instead.
Boolean unleash_barbarians (tile) 2.2 Deprecated in 2.4. Use edit.unleash_barbarians() instead.
- place_partisans (tile, player, count, sq_radius) 2.3 Deprecated in 2.4. Use edit.place_partisans() 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 script_server.c (search for "script_server_signal_create").

Signals server
(return) type function name / variable arguments ver comments
Boolean turn_started (Number turn, Number year)
Boolean unit_moved (Unit unit, Tile src_tile, Tile dst_tile)
Boolean city_built (City city)
Boolean city_growth (City city, Number city_size)
Boolean unit_built (Unit unit, City city)
Boolean building_built (Building_Type type, City city)
Boolean city_lost (City city, Player loser, Player winner) 2.2
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"
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)
Boolean map_generated () 2.5
Boolean disaster (Disaster disaster, City city) 2.5
Boolean achievement_gained (Achievement achievement, Player gainer, Boolean first) 2.6 first indicated whether player is first one to reach the achievement.
Boolean action_started_unit_city (Action action, Unit actor, City target) 2.6
Boolean action_started_unit_unit (Action action, Unit actor, Unit target) 2.6

Script debugging

The following functions are helpful in debugging lua scripts:

Functions debugging
(return) type function name / variable arguments ver comments
- 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.

Examples

Simple example

The example code below should 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')

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 default/default.lua and default/script.lua in Freeciv's data directory. (You can also look at the current SVN version of these files)

Lua

The language used for Freeciv event scripts is Lua. As of Freeciv 2.2, we use Lua 5.1. In Freeciv 2.5 Lua is updated to 5.2.

Lua External Links:

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 matching
  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
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
Advertisement