Lua Scripting

All Lua code for a ruleset currently goes in the game/script.lua file.

-- Place Ruins at the location of the destroyed city.
function city_destroyed_callback(city, loser, destroyer)
  city.tile:create_extra("Ruins", nil)
  -- continue processing
  return false
end

signal.connect("city_destroyed", "city_destroyed_callback")

In this example, we have a callback handler for the Events.city_destroyed() signal that creates a Ruins extra on the site of the destroyed city.

Defaults

To avoid having to copy large amounts of standard functionality across to every ruleset, there is a data/default/default.lua file containing signal handlers that are included automatically.

Signal Handlers

_deflua_hut_get_gold(unit: any, gold: any)

Get gold from entering a hut.

_deflua_hut_consolation_prize(unit: any)

Defaults to _deflua_hut_get_gold() if intended hut behaviour was not possible.

_deflua_hut_get_tech(unit: any): boolean

Get a tech from entering a hut.

_deflua_hut_get_mercenaries(unit: any): boolean

Get a mercenary unit from entering a hut.

_deflua_hut_get_city(unit: any): boolean

Get new city from hut, or settlers (nomads) if terrain is poor.

_deflua_hut_get_barbarians(unit: any): boolean

Get barbarians from hut, unless close to a city, king enters, or barbarians are disabled Unit may die: returns true if unit is alive

_deflua_hut_enter_callback(unit: any): boolean

Randomly choose a hut event

Connected to hut_enter

_deflua_hut_frighten_callback(unit: any, extra: any): boolean

Informs that the tribe has run away seeing your plane

Connected to hut_frighten

_deflua_make_partisans_callback(city: any, loser: any, winner: any, reason: any)

Make partisans around conquered city

If requirements to make partisans when a city is conquered is fulfilled this routine makes a lot of partisans based on the city`s size. To be candidate for partisans the following things must be satisfied: * The loser of the city is the original owner. * The Inspire_Partisans effect must be larger than zero.

If these conditions are ever satisfied, the ruleset must have a unit with the Partisan role.

In the default ruleset, the requirements for inspiring partisans are: * Guerilla warfare must be known by atleast 1 player * The player must know about Communism and Gunpowder * The player must run either a democracy or a communist society.

Connected to city_transferred

_deflua_harmless_disaster_message(disaster: any, city: any, had_internal_effect: any)

Notify player about the fact that disaster had no effect if that is the case

Connected to disaster_occurred

_deflua_city_conquer_gold_loot(city: any, looterunit: any): boolean

Transfer gold from the previous owner of a conquered city to the new owner.

Connected to city_loot

Disable a Default Signal Handler

Disabling a default signal handler is as simple as calling the signal.remove() function with the same signal and handler function that created it. E.g.

signal.remove("city_loot", "_deflua_city_conquer_gold_loot")

This disables gold loot on city capture completely.

Override a Default Signal Handler

You can also change the default behaviour for a specific handler by overriding the function.

function _deflua_city_conquer_gold_loot(city, looterunit)
  local loot = 25
  looterunit.owner:change_gold(loot)
  notify.event(looterunit.owner, city.tile, E.UNIT_WIN_ATT,
    string.format(
      PL_("Your lootings from %s accumulate to %d gold!",
          "Your lootings from %s accumulate to %d gold!",
          loot),
      city:link_text(), loot
    )
  )
end

signal.replace("city_loot", "_deflua_city_conquer_gold_loot")

This just grants a flat 25 gold to the attacker and doesn’t take anything from the defender.

Alternatively, you can just signal.remove() the default handler as above, and implement your own signal handler using signal.connect().

API Reference

Modules

const

Flexible “constant” implementation. Define your constants once and they then become unchangeable. E.g.

const.test = 'Hello World!'
log.normal("%s", const.test) -- prints "Hello World!"

const.test = 'Not with me Dude!' -- prints error for that line

const.inner_test = {'Hello','World'}
log.normal("%s %s!", const.inner_test[1], const.inner_test[2])

const.inner_test[2] = 'Superman' -- prints error for that line
log

Logging facilities from Lua script. This is the preferred way to emit textual output from Freeciv21 Lua scripts. Messages emitted with these functions will be sent to an appropriate place, which will differ depending on the context.

fatal(fmt: string, ...: unknown)

Log message at Fatal level with printf-like formatting (Lua’s string.format). Note that Fatal level warnings DO NOT abort the game.

error(fmt: string, ...: unknown)

Log message at Error level with printf-like formatting (Lua’s string.format).

warn(fmt: string, ...: unknown)

Log message at Warn level with printf-like formatting (Lua’s string.format).

normal(fmt: string, ...: unknown)

Log message at Normal level with printf-like formatting (Lua’s string.format).

verbose(fmt: string, ...: unknown)

Log message at Verbose level with printf-like formatting (Lua’s string.format).

debug(fmt: string, ...: unknown)

Log message at Debug level with printf-like formatting (Lua’s string.format).

game

This module is used for game related information.

current_turn(): (turn: int)
Returns:

turn (int) – The current turn number, starting from 1.

current_year(): (year: int)
Returns:

year (int) – The current game year.

current_fragment(): (year-fragment: int)
Returns:

year-fragment (int) – The current game year fragment. E.g. 8 = August.

current_year_text(): (year-text: string)
Returns:

year-text (string) – Textual representation of current calendar time.

rulesetdir(): (ruleset-name: string)
Returns:

ruleset-name (string) – Unique name of the ruleset.

ruleset_name(): (ruleset-name: string)
Returns:

ruleset-name (string) – Human readable name of the ruleset.

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.

player(player_id_or_name: string | int): (player: Player)
Parameters:

player_id_or_name (string | int) – The unique ID or name of the player to search for.

Returns:

player (Player) – The player with the given ID or name if they exist, or nil.

team(team_id_or_name: string | int): (team: Team)
Parameters:

team_id_or_name (string | int) – The unique ID or name of the player to search for.

Returns:

team (Team) – The team with the given ID or name if they exist, or nil.

teams_iterate()

Safe iteration over each Team in the game.

city(player: Player, city_id: int): (city: City)
Parameters:
  • player (Player) – The player who owns the city, or nil for any player

  • city_id (int) – The unique ID for the city to search for

Returns:

city (City) – The city if it exists and belongs to player, or nil

unit(player: Player, unit_id: int): (unit: Unit)
Parameters:
  • player (Player) – The player who owns the unit, or nil for any player

  • unit_id (int) – The unique ID for the unit to search for

Returns:

unit (Unit) – The unit if it exists and belongs to player, or nil

transport_unit(player: Player, unit_type: Unit_Type, tile: Tile): (unit: Unit)

Looks for an existing unit that can transport unit_type at tile. Intended to be used with create_unit_full, to spawn it directly into the hold of the transport.

Parameters:
  • player (Player) – The player who owns the transport unit

  • unit_type (Unit_Type) – The unit type to search for a transport for

  • tile (Tile) – The tile to search in

Returns:

unit (Unit) – The transport unit found, or nil

tile(nat_x: int, nat_y: int): (tile: Tile)

Finds a tile based on natural coordinates.

Parameters:
  • nat_x (int) – The natural x-coordinate.

  • nat_y (int) – The natural y-coordinate.

Returns:

tile (Tile) – The found tile.

government(name: string): (government: Government)

Finds a government by its name.

Parameters:

name (string) – The ruleset name of the government.

Returns:

government (Government) – The found government.

nation_type(name: string): (nation: Nation_Type)

Finds a nation type by its name.

Parameters:

name (string) – The ruleset name of the nation type.

Returns:

nation (Nation_Type) – The found nation type.

action(name: string): (action: Action)

Finds an action by its ID. For use in loops etc.

Attention

An action’s ID may change after saving and reloading the game.

Parameters:

name (string) – The ruleset name of the action.

Returns:

action (Action) – The found action.

building_type(name: string): (building: Building_Type)

Finds a building type by its name.

Parameters:

name (string) – The ruleset name of the building type.

Returns:

building (Building_Type) – The found building type.

unit_type(name: string): (unit-type: Unit_Type)

Finds a unit type by its name.

Parameters:

name (string) – The ruleset name of the unit type.

Returns:

unit-type (Unit_Type) – The found unit type.

unit_types_iterate()

Safe iteration over each Unit_Type in the game.

unit_class(name: string): (unit-class: Unit_Class)

Finds a unit class by its name.

Parameters:

name (string) – The ruleset name of the unit class.

Returns:

unit-class (Unit_Class) – The found unit class.

unit_classes_iterate()

Safe iteration over each Unit_Class in the game.

role_unit_type(role_name: string, pplayer: Player): (unit-type: Unit_Type)

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.

Parameters:
  • role_name (string) – The name of the role or unit type flag.

  • pplayer (Player) – The owner of the unit, or nil for any player.

Returns:

unit-type (Unit_Type) – The found role unit type.

tech_type(name: string): (tech: Tech_Type)

Finds a tech type by its name.

Parameters:

name (string) – The ruleset name of the tech type.

Returns:

tech (Tech_Type) – The found tech type.

terrain(name: string): (terrain: Terrain)

Finds a terrain by its name.

Parameters:

name (string) – The ruleset name of the terrain.

Returns:

terrain (Terrain) – The found terrain.

signal(index: any): (signal: string)

Can be used to iterate over all defined signals (until nil is returned).

Returns:

signal (string) – The Events signal name.

signal_callback(signal_name: any, index: any): (func: string)

Can be used to iterate over all callbacks currently associated with a given signal.

Returns:

func (string) – The name of the global Lua function that receives the callback for this signal.

effects

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

world_bonus(effect_type: Effect_Type): (value: int)

Calculates a world effect bonus.

Parameters:

effect_type (Effect_Type) – The type of effect to calculate.

Returns:

value (int) – The value of the world effect.

player_bonus(pplayer: Player, effect_type: Effect_Type): (value: int)

Calculates a player effect bonus.

Parameters:
  • pplayer (Player) – The player to calculate the bonus for.

  • effect_type (Effect_Type) – The type of effect to calculate.

Returns:

value (int) – The value of the player effect.

city_bonus(pcity: City, effect_type: Effect_Type): (value: int)

Calculates a city effect bonus.

Parameters:
  • pcity (City) – The city to calculate the bonus for.

  • effect_type (Effect_Type) – The type of effect to calculate.

Returns:

value (int) – The value of the city effect.

direction
str2dir(str: string): (direction: Direction)

Turns a string like “north”, “southwest”, etc., into a Direction object.

Parameters:

str (string) – The string representation of the direction.

Returns:

direction (Direction) – The corresponding Direction object.

next_ccw(direction: Direction): (direction: Direction)

Returns the next counterclockwise direction in the current topology.

Parameters:

direction (Direction) – The current Direction.

Returns:

direction (Direction) – The next counterclockwise Direction.

next_cw(direction: Direction): (direction: Direction)

Returns the next clockwise direction in the current topology.

Parameters:

direction (Direction) – The current Direction.

Returns:

direction (Direction) – The next clockwise Direction.

opposite(direction: Direction): (direction: Direction)

Returns the opposite direction.

Parameters:

direction (Direction) – The current Direction.

Returns:

direction (Direction) – The opposite Direction.

class E

The E module contains a set of event types, for example E.SCRIPT. These correspond to the categories that the client can filter on.

name: string

The player’s name.

TECH_GAIN: enum

Acquired New Tech.

TECH_LEARNED: enum

Learned New Tech.

TECH_GOAL: enum

Selected New Goal.

TECH_LOST: enum

Lost a Tech.

TECH_EMBASSY: enum

Other Player Gained/Lost a Tech.

IMP_BUY: enum

Bought.

IMP_BUILD: enum

Built.

IMP_AUCTIONED: enum

Forced to Sell.

IMP_AUTO: enum

New Improvement Selected.

IMP_SOLD: enum

Sold.

CITY_CANTBUILD: enum

Building Unavailable Item.

CITY_LOST: enum

Captured/Destroyed.

CITY_LOVE: enum

Celebrating.

CITY_DISORDER: enum

Civil Disorder.

CITY_FAMINE: enum

Famine.

CITY_FAMINE_FEARED: enum

Famine Feared.

CITY_GROWTH: enum

Growth.

CITY_MAY_SOON_GROW: enum

May Soon Grow.

CITY_AQUEDUCT: enum

Needs Aqueduct.

CITY_AQ_BUILDING: enum

Needs Aqueduct Being Built.

CITY_NORMAL: enum

Normal.

CITY_NUKED: enum

Nuked.

CITY_CMA_RELEASE: enum

Released from citizen governor.

CITY_GRAN_THROTTLE: enum

Suggest Growth Throttling.

CITY_TRANSFER: enum

Transfer.

CITY_BUILD: enum

Was Built.

CITY_PLAGUE: enum

Has Plague.

CITY_RADIUS_SQ: enum

City Map changed.

WORKLIST: enum

Worklist Events.

CITY_PRODUCTION_CHANGED: enum

Production changed.

DISASTER: enum

Disaster.

MY_DIPLOMAT_BRIBE: enum

Bribe.

DIPLOMATIC_INCIDENT: enum

Caused Incident.

MY_DIPLOMAT_ESCAPE: enum

Escape.

MY_DIPLOMAT_EMBASSY: enum

Embassy.

MY_DIPLOMAT_FAILED: enum

Failed.

MY_DIPLOMAT_INCITE: enum

Incite.

MY_DIPLOMAT_POISON: enum

Poison.

MY_DIPLOMAT_SABOTAGE: enum

Sabotage.

MY_DIPLOMAT_THEFT: enum

Theft.

MY_SPY_STEAL_GOLD: enum

Gold Theft.

MY_SPY_STEAL_MAP: enum

Map Theft.

MY_SPY_NUKE: enum

Suitcase Nuke.

ENEMY_DIPLOMAT_BRIBE: enum

Bribe.

ENEMY_DIPLOMAT_EMBASSY: enum

Embassy.

ENEMY_DIPLOMAT_FAILED: enum

Failed.

ENEMY_DIPLOMAT_INCITE: enum

Incite.

ENEMY_DIPLOMAT_POISON: enum

Poison.

ENEMY_DIPLOMAT_SABOTAGE: enum

Sabotage.

ENEMY_DIPLOMAT_THEFT: enum

Theft.

ENEMY_SPY_STEAL_GOLD: enum

Gold Theft.

ENEMY_SPY_STEAL_MAP: enum

Map Theft.

ENEMY_SPY_NUKE: enum

Suitcase Nuke.

GLOBAL_ECO: enum

Eco-Disaster.

NUKE: enum

Nuke Detonated.

HUT_BARB: enum

Barbarians in a Hut Roused.

HUT_CITY: enum

City Founded from Hut.

HUT_GOLD: enum

Gold Found in Hut.

HUT_BARB_KILLED: enum

Killed by Barbarians in a Hut.

HUT_MERC: enum

Mercenaries Found in Hut.

HUT_SETTLER: enum

Settler Found in Hut.

HUT_TECH: enum

Tech Found in Hut.

HUT_BARB_CITY_NEAR: enum

Unit Spared by Barbarians.

ACHIEVEMENT: enum

Achievements.

UPRISING: enum

Barbarian Uprising.

CIVIL_WAR: enum

Civil War.

ANARCHY: enum

Collapse to Anarchy.

FIRST_CONTACT: enum

First Contact.

NEW_GOVERNMENT: enum

Learned New Government.

LOW_ON_FUNDS: enum

Low Funds.

POLLUTION: enum

Pollution.

REVOLT_DONE: enum

Revolution Ended.

REVOLT_START: enum

Revolution Started.

SPACESHIP: enum

Spaceship Events.

TREATY_ALLIANCE: enum

Alliance.

TREATY_BROKEN: enum

Broken.

TREATY_CEASEFIRE: enum

Cease-fire.

TREATY_EMBASSY: enum

Embassy.

TREATY_PEACE: enum

Peace.

TREATY_SHARED_VISION: enum

Shared Vision.

UNIT_LOST_ATT: enum

Attack Failed.

UNIT_WIN_ATT: enum

Attack Succeeded.

UNIT_BUY: enum

Bought.

UNIT_BUILT: enum

Built.

UNIT_LOST_DEF: enum

Defender Destroyed.

UNIT_WIN_DEF: enum

Defender Survived.

UNIT_BECAME_VET: enum

Promoted to Veteran.

UNIT_LOST_MISC: enum

Lost outside battle.

UNIT_UPGRADED: enum

Production Upgraded.

UNIT_RELOCATED: enum

Relocated.

UNIT_ORDERS: enum

Orders / goto events.

UNIT_BUILT_POP_COST: enum

Built unit with population cost.

UNIT_WAS_EXPELLED: enum

Was Expelled.

UNIT_DID_EXPEL: enum

Did Expel.

UNIT_ACTION_FAILED: enum

Action failed.

VOTE_NEW: enum

New vote.

VOTE_RESOLVED: enum

Vote resolved.

VOTE_ABORTED: enum

Vote canceled.

WONDER_BUILD: enum

Finished.

WONDER_OBSOLETE: enum

Made Obsolete.

WONDER_STARTED: enum

Started.

WONDER_STOPPED: enum

Stopped.

WONDER_WILL_BE_BUILT: enum

Will Finish Next Turn.

AI_DEBUG: enum

AI Debug messages.

BROADCAST_REPORT: enum

Broadcast Report.

CARAVAN_ACTION: enum

Caravan actions.

CHAT_ERROR: enum

Chat error messages.

CHAT_MSG: enum

Chat messages.

CONNECTION: enum

Connect/disconnect messages.

DIPLOMACY: enum

Diplomatic Message.

BAD_COMMAND: enum

Error message from bad command.

GAME_END: enum

Game Ended.

GAME_START: enum

Game Started.

NATION_SELECTED: enum

Nation Selected.

DESTROYED: enum

Player Destroyed.

REPORT: enum

Report.

LOG_FATAL: enum

Server Aborting.

LOG_ERROR: enum

Server Problems.

MESSAGE_WALL: enum

Message from server operator.

SETTING: enum

Server settings changed.

TURN_BELL: enum

Turn Bell.

SCRIPT: enum

Scenario/ruleset script message.

NEXT_YEAR: enum

Year Advance.

DEPRECATION_WARNING: enum

Deprecated Modpack syntax warnings.

SPONTANEOUS_EXTRA: enum

Extra Appears or Disappears.

UNIT_ILLEGAL_ACTION: enum

Unit Illegal Action.

UNIT_ESCAPED: enum

Unit escaped.

BEGINNER_HELP: enum

Help for beginners.

MY_UNIT_DID_HEAL: enum

Unit did heal.

MY_UNIT_WAS_HEALED: enum

Unit was healed.

MULTIPLIER: enum

Multiplier changed.

UNIT_ACTION_ACTOR_SUCCESS: enum

Your unit did.

UNIT_ACTION_ACTOR_FAILURE: enum

Your unit failed.

UNIT_ACTION_TARGET_HOSTILE: enum

Unit did to you.

UNIT_ACTION_TARGET_OTHER: enum

Unit did.

INFRAPOINTS: enum

Infrapoints.

HUT_MAP: enum

Map found from a hut.

TREATY_SHARED_TILES: enum

Tiles shared.

notify

Send event notifications to players.

See the E for a list of possible event types.

all(message: String, ...: any)

Send all players a message with type E.SCRIPT.

Parameters:
  • message (String) – A string.format-style message.

  • ... (any) – A set of values to insert into the string template.

player(player: Player, message: String, ...: any)

Send a player a message with type E.SCRIPT.

Parameters:
  • player (Player) – The player to send the event message to.

  • message (String) – A string.format-style message.

  • ... (any) – A set of values to insert into the string template.

event(
    player: Player,
    tile: Tile,
    event: E,
    message: String,
    ...: any
)

Send a specific player or all players (if player is nil) a message with an arbitrary type, optionally drawing attention to a particular tile.

Parameters:
  • player (Player) – The player to send the event message to, or nil for all players.

  • tile (Tile) – The tile to highlight, or nil for no tile.

  • event (E) – The event category.

  • message (String) – A string.format-style message.

  • ... (any) – A set of values to insert into the string template.

embassies(
    player: Player,
    ptile: any,
    event: E,
    message: String,
    ...: any
)

Send a message to all players who have an embassy with the given player.

Parameters:
  • player (Player) – The player to send the event message about.

  • event (E) – The event category.

  • message (String) – A string.format-style message.

  • ... (any) – A set of values to insert into the string template.

research(
    player: Player,
    selfmsg: boolean,
    event: E,
    message: String,
    ...: any
)

Send all players sharing research with specific player a message with an arbitrary type.

Setting selfmsg to false can be useful if you want to send different message to one actually getting the tech for the team.

Parameters:
  • player (Player) – The player to send the event message about.

  • selfmsg (boolean) – True, if the player should also receive the event.

  • event (E) – The event category.

  • message (String) – A string.format-style message.

  • ... (any) – A set of values to insert into the string template.

research_embassies(player: Player, event: E, message: String, ...: any)

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.

Parameters:
  • player (Player) – The player to send the event message about.

  • event (E) – The event category.

  • message (String) – A string.format-style message.

  • ... (any) – A set of values to insert into the string template.

server

The server module is for interacting with the server, and getting configuration details and settings.

save(filename: string)

Instructs the server to save the game. As with the /save command, if filename is empty, the server chooses an appropriate filename.

Parameters:

filename (string) – The filename to use, or nil to use a default.

started(): (started: boolean)
Returns:

started (boolean) – True, if the game has been started.

civilization_score(player: Player): (score: int)

Same as Player:civilization_score

play_music(player: Player, tag: string): (played: boolean)

Request player’s client to play certain track.

Parameters:
  • player (Player) – The player who should play the track.

  • tag (string) – The tag of the track to play.

Returns:

played (boolean) – True, if it played.

setting

The server settings module is for querying and modifying server settings.

get(name: any): (value: String)
Returns:

value (String) – The value of a server setting as a string.

edit

The edit module contains all of the functions for modifying game state.

create_unit(
    player: Player,
    tile: Tile,
    unit_type: Unit_Type,
    veteran_level: int,
    home_city: City,
    moves_left: int
): (unit: Unit)

Creates a unit.

Parameters:
  • player (Player) – The player who will own the unit.

  • tile (Tile) – The tile where the unit will be created.

  • unit_type (Unit_Type) – The type of the unit.

  • veteran_level (int) – The veteran level of the unit.

  • home_city (City) – The city that the unit will belong to, or nil for unhomed.

  • moves_left (int) – The initial number of moves left for the unit. -1 for max.

Returns:

unit (Unit) – The created unit.

create_unit_full(
    player: Player,
    tile: Tile,
    unit_type: Unit_Type,
    veteran_level: int,
    home_city: City,
    moves_left: int,
    hp_left: int,
    transport: Unit
): (unit: Unit)

Creates a unit with full parameters.

Parameters:
  • player (Player) – The player who will own the unit.

  • tile (Tile) – The tile where the unit is created.

  • unit_type (Unit_Type) – The type of the unit.

  • veteran_level (int) – The veteran level of the unit.

  • home_city (City) – The city that the unit belongs to, or nil for unhomed.

  • moves_left (int) – The number of moves left for the unit. -1 for max.

  • hp_left (int) – The current hit points of the unit. -1 for max.

  • transport (Unit) – The transport unit it starts in, or nil for not in a transport.

Returns:

unit (Unit) – The created unit.

unit_teleport(unit: Unit, dest: Tile): (True: bool)

Teleports a unit to a destination tile without consuming move points. If it lands in inhospitable terrain or among non-friendly units, it dies.

Parameters:
  • unit (Unit) – The unit to be teleported.

  • dest (Tile) – The destination tile.

Returns:

True (bool) – if the teleportation was successful, false if it died.

unit_kill(unit: Unit, reason: string, killer: Player)

Kills a unit with a reason. This affects how scoring is applied for the death.

Parameters:
  • unit (Unit) – The unit to be killed.

  • reason (string) – The reason for killing the unit.

  • killer (Player) – The player who killed the unit, or nil.

unit_damage_hp(unit: Unit, amount: int, reason: string, killer: Player): (surived: bool)

Damages a unit’s HP. Automatically killing the unit if it drops to zero or below. See edit.unit_kill() for loss reasons.

Parameters:
  • unit (Unit) – The unit to be damaged.

  • amount (int) – The amount of damage to apply.

  • reason (string) – The reason for the damage. See reason

  • killer (Player) – The player responsible for the damage, or nil.

Returns:

surived (bool) – True if the unit survived.

unit_recover_hp(unit: Unit, amount: int)

Recovers a unit’s HP, capped at the max.

Parameters:
  • unit (Unit) – The unit to recover HP for.

  • amount (int) – The amount of HP to recover.

unit_set_hp(unit: Unit, amount: int)

Sets a unit’s HP. Capped between 1 and the max for the unit type.

Parameters:
  • unit (Unit) – The unit whose HP is to be set.

  • amount (int) – The new HP amount.

unit_activity_count_set(unit: Unit, work_points: int)

Note

If this is set above the required number of work points for the current activity, this will complete the activity immediately.

See Unit:activity_count_set() and Unit:activity_count_add()

Parameters:
  • unit (Unit) – The unit to modify.

  • work_points (int) – The total number of work points that have been put into the current activity.

unit_nationality_set(unit: Unit, nationality: Player)

See Unit:nationality_set()

Parameters:
  • unit (Unit) – The unit to modify.

  • nationality (Player) – The nationality of the people in the unit.

unit_moves_left_set(unit: Unit, moves_left: int)

Note

This may exceed the max Unit_Type.move_rate, but cannot be lower then zero.

See Unit:moves_left_set() and Unit:moves_left_add()

Parameters:
  • unit (Unit) – The unit to modify.

  • moves_left (int) – The number of move fragments remaining.

unit_veteran_level_set(unit: Unit, veteran: int)

Note

This cannot be less than zero or exceed Unit_Type.max_veteran_level.

Note

This does not automatically notify the Player who owns the unit.

See Unit:veteran_level_set() and Unit:veteran_level_add()

Parameters:
  • unit (Unit) – The unit to modify.

  • veteran (int) – The veterancy level of the unit.

unit_fuel_set(unit: Unit, fuel: int)

Note

This cannot exceed the max Unit_Type.fuel, and cannot be lower then zero.

See Unit:fuel_set() and Unit:fuel_add()

Parameters:
  • unit (Unit) – The unit to modify.

  • fuel (int) – The amount of fuel remaining.

change_terrain(tile: Tile, terrain: Terrain): (success: bool)

Changes the terrain of a tile. If the terrain change would destroy a city, the change fails. You need to edit.remove_city() first to change it anyway.

Parameters:
  • tile (Tile) – The tile whose terrain is to be changed.

  • terrain (Terrain) – The new terrain type.

Returns:

success (bool) – True if the terrain change was successful, false otherwise.

create_city(player: Player, tile: Tile, name: string)

Creates a new city at size 1.

Parameters:
  • player (Player) – The player who owns the city.

  • tile (Tile) – The tile where the city is created.

  • name (string) – The name of the city, or nil for random.

resize_city(city: City, size: int, reason: string)

Resizes a city. The reason is a user-defined value that will show up in city_size_change signal events.

Parameters:
  • city (City) – The city to resize.

  • size (int) – The new size of the city.

  • reason (string) – The reason for resizing the city.

remove_city(city: City)

Removes a city.

Parameters:

city (City) – The city to be removed.

create_owned_extra(tile: Tile, name: string, player: Player)

Creates an owned extra on a tile. This will claim ownership of any other ownable extras on the tile too.

Parameters:
  • tile (Tile) – The tile where the extra is created.

  • name (string) – The name of the extra.

  • player (Player) – The player who owns the extra.

create_extra(tile: Tile, name: string)

Creates an extra on a tile. Note that this does not affect the primary resource of a tile. If you want to change the primary resource, use edit.set_primary_resource instead.

Parameters:
  • tile (Tile) – The tile where the extra is created.

  • name (string) – The name of the extra.

remove_extra(tile: Tile, name: string)

Removes an extra from a tile. Note that this does not affect the primary resource of a tile. If you want to change the primary resource, use edit.set_primary_resource instead.

Parameters:
  • tile (Tile) – The tile from which the extra is removed.

  • name (string) – The name of the extra to remove.

tile_primary_resource_set(tile: Tile, name: string)

Changes the primary resource for a tile. The primary resource persists even if the terrain changes to an incompatible type, and can be recovered if the terrain is changed to a compatible type again. Unlike resources created by create_extra() which disappear forever.

Parameters:
  • tile (Tile) – The tile to set the primary resource for.

  • name (string) – The name of the resource, or nil to remove.

tile_set_label(tile: Tile, label: string)

Sets a textual label for a tile.

Parameters:
  • tile (Tile) – The tile to label.

  • label (string) – The label to set for the tile.

create_player(username: string, nation: Nation_Type, ai: string): (player: Player)

Creates a player. The new player has no units or cities.

Parameters:
  • username (string) – The username of the player.

  • nation (Nation_Type) – The nation type of the player.

  • ai (string) – The AI type for the player, or nil for human.

Returns:

player (Player) – The created player.

change_gold(player: Player, amount: int)

Adds the given amount to the player’s treasury.

Parameters:
  • player (Player) – The player whose gold amount is to be changed.

  • amount (int) – The amount to add (can be positive or negative).

give_tech(
    player: Player,
    tech: Tech_Type,
    cost: int,
    notify: bool,
    reason: string
): (tech: Tech_Type)

Gives a technology to a player.

Cost is a percentage of the tech’s cost to be deducted from the bulb store, or ‘-1’ for normal freecost, ‘-2’ for conquercost, ‘-3’ for diplbulbcost

The reason is a user-defined value that is passed to the tech_researched() signal event.

Parameters:
  • player (Player) – The player receiving the technology.

  • tech (Tech_Type) – The technology to give, or nil for random.

  • cost (int) – The cost to apply.

  • notify (bool) – True to notify all parties as normal.

  • reason (string) – The reason for giving the technology.

Returns:

tech (Tech_Type) – The technology that was given, or nil if they already had the tech.

trait_mod(player: Player, trait_name: string, mod: int): (success: bool)

Modifies an AI player’s personality trait value. This is a modifier for the trait value that the player was created with. Subsequent calls override the modifier, they are not additive.

The trait_name can be one of: “Expansionist”, “Trader”, “Aggressive”, or “Builder”.

Parameters:
  • player (Player) – The AI player whose trait is to be modified.

  • trait_name (string) – The name of the trait to modify.

  • mod (int) – The modification value to apply to the trait.

Returns:

success (bool) – True if the modification was successful, false otherwise.

unleash_barbarians(tile: Tile): (survived: bool)

Unleashes barbarians on a tile.

Parameters:

tile (Tile) – The tile where barbarians are unleashed.

Returns:

survived (bool) – False if any units on the tile were killed (or would have been killed, if there were no units).

place_partisans(tile: Tile, player: Player, count: int, sq_radius: int)

Places partisans in a radius around a tile.

Parameters:
  • tile (Tile) – The tile where partisans are placed near.

  • player (Player) – The player who owns the partisans.

  • count (int) – The number of partisans to place.

  • sq_radius (int) – The square radius around the tile to place partisans.

climate_change_type: table

Enum for climate change types.

Table 12 Climate Change Types

Enum

Description

GLOBAL_WARMING

Global Warming is caused by the accumulation of pollution.

NUCLEAR_WINTER

Nuclear Winter is caused by the accumulation of nuclear fallout.

climate_change(cctype: edit.climate_change_type, effect: int)

Applies a wave of global climate change effects. Unlike regular climate change, this does not automatically generate any messages or affect the counters for pollution/fallout-related climate change. It will trigger even if global_warming or nuclear_winter options are disabled.

Parameters:
  • cctype (edit.climate_change_type) – The type of climate change to apply.

  • effect (int) – The magnitude of the effect (approximately the number of tiles affected.)

civil_war(player: Player, probability: int): (rebel: Player)

Possibly throw a player into civil war. 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.

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

Parameters:
  • player (Player) – The player who may experience a civil war.

  • probability (int) – The probability of civil war occurring.

Returns:

rebel (Player) – The new rebel AI player, or nil if it failed.

unit_turn(unit: Unit, direction: Direction)

Change unit orientation to face in direction.

Parameters:
  • unit (Unit) – The unit to change the orientation of.

  • direction (Direction) – The direction in which the unit will face.

player_victory(player: Player)

Marks a player as victorious and ends the game.

Parameters:

player (Player) – The player to mark as the winner.

unit_move(unit: Unit, move_to: Tile, move_cost: int): (survived: bool)

Moves a unit to a new tile and deducts the cost from the units move points. If the tile is inhospitable terrain, or there are non-friendly units present, the unit dies. Very few checks are applied. Be careful!

Parameters:
  • unit (Unit) – The unit to be moved.

  • move_to (Tile) – The tile to move the unit to.

  • move_cost (int) – The cost of the move (in move fragments).

Returns:

survived (bool) – True if the move was successful, false it died.

movement_disallow(unit: Unit)

Prohibits the unit from moving from the spot it is at.

Parameters:

unit (Unit) – The unit to disallow movement for.

movement_allow(unit: Unit)

Allows movement for a unit again following a edit.movement_disallow() call.

Parameters:

unit (Unit) – The unit to allow movement for.

add_city_history(city: City, amount: int)

Adds history a.k.a. culture to a city. This affects civilisation score.

Parameters:
  • city (City) – The city to which history points are to be added.

  • amount (int) – The amount of history points to add.

add_player_history(player: Player, amount: int)

Adds history a.k.a. culture to a player. This affects civilisation score.

Parameters:
  • player (Player) – The player to which history points are to be added.

  • amount (int) – The amount of history points to add.

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.cpp (search for “script_server_signals_create”).

If false is returned from a signal handler function, the signal will not propagate to any subsequent signal handlers.

turn_begin(turn: Number, year: Number)

A signal for the beginning of a turn.

Parameters:
  • turn (Number) – The turn number, starting at 1.

  • year (Number) – The calendar year number

unit_moved(unit: Unit, tile_from: Tile, tile_to: Tile)

A signal for when a unit has moved. Emitted at the end of a unit_move().

Parameters:
  • unit (Unit) – The unit that moved.

  • tile_from (Tile) – The tile the unit moved from.

  • tile_to (Tile) – The tile the unit moved to.

city_built(city: City)

A signal for when a city is built.

Parameters:

city (City) – The city that was built.

city_size_change(city: City, size: Number, reason: String)

A signal for changes in city size.

Reason is one of: “unit_added”, “growth”, “poison”, “incited”, “upkeep_failure”, “famine”, “unit_built”, “migration_from”, “migration_to”, “disaster”, “plague”, “conquest”, “nuke”, “bombard”, “attack”, or a user-defined value set in edit.resize_city()

Parameters:
  • city (City) – The city whose size changed.

  • size (Number) – The new size of the city.

  • reason (String) – The reason for the size change.

unit_built(unit: Unit, city: City)

A signal for when a unit is built in a city.

Parameters:
  • unit (Unit) – The unit that was built.

  • city (City) – The city where the unit was built.

building_built(building: Building_Type, city: City)

A signal for when a building is built in a city.

Parameters:
  • building (Building_Type) – The type of building that was built.

  • city (City) – The city where the building was built.

unit_cant_be_built(unit_type: Unit_Type, city: City, reason: String)

A signal for when a unit cannot be built.

The reason is one of: “need_tech”, “need_techflag”, “need_building”, “have_building”, “need_building_genus”, “have_building_genus”, “need_government”, “have_government”, “need_achievement”, “need_extra”, “have_extra”, “need_good”, “have_good”, “need_terrain”, “have_terrain”, “need_nation”, “have_nation”, “need_nationgroup”, “have_nationgroup”, “need_style”, “have_style”, “need_nationality”, “have_nationality”, “need_diplrel”, “have_diplrel”, “need_minsize”, “have_minsize”, “need_minculture”, “need_minforeignpct”, “have_minforeignpct”, “need_mintechs”, “need_tileunits”, “have_tileunits”, “need_terrainclass”, “have_terrainclass”, “need_terrainflag”, “have_terrainflag”, “need_baseflag”, “have_baseflag”, “need_roadflag”, “have_roadflag”, “need_extraflag”, “have_extraflag”, “need_minyear”, “need_mincalfrag”, “have_mincalfrag”, “need_topo”, “need_setting”, “need_age”, “never”, “unavailable”, or “pop_cost”

Note

At the moment, ruleset doesn’t allow full requirements for units, but as soon as it does a lot of these will automatically come into play.

Parameters:
  • unit_type (Unit_Type) – The type of unit that cannot be built.

  • city (City) – The city where the unit cannot be built.

  • reason (String) – The reason why the unit cannot be built.

building_cant_be_built(
    building_type: Building_Type,
    city: City,
    reason: String
)

A signal for when a building cannot be built.

The reason is one of: “need_tech”, “need_techflag”, “need_building”, “have_building”, “need_building_genus”, “have_building_genus”, “need_government”, “have_government”, “need_achievement”, “need_extra”, “have_extra”, “need_good”, “have_good”, “need_terrain”, “have_terrain”, “need_nation”, “have_nation”, “need_nationgroup”, “have_nationgroup”, “need_style”, “have_style”, “need_nationality”, “have_nationality”, “need_diplrel”, “have_diplrel”, “need_minsize”, “have_minsize”, “need_minculture”, “need_minforeignpct”, “have_minforeignpct”, “need_mintechs”, “need_tileunits”, “have_tileunits”, “need_terrainclass”, “have_terrainclass”, “need_terrainflag”, “have_terrainflag”, “need_baseflag”, “have_baseflag”, “need_roadflag”, “have_roadflag”, “need_extraflag”, “have_extraflag”, “need_minyear”, “need_mincalfrag”, “have_mincalfrag”, “need_topo”, “need_setting”, “need_age”, “never”, or “unavailable”.

Parameters:
  • building_type (Building_Type) – The type of building that cannot be built.

  • city (City) – The city where the building cannot be built.

  • reason (String) – The reason why the building cannot be built.

building_lost(
    city: City,
    building: Building_Type,
    reason: String,
    destroyer: Unit
)

A signal for when a building is lost.

The reason is one of: “razed”, “conquered” (applicable for Small Wonders only), “city_destroyed”, “disaster”, “attacked”, “sabotaged”, “landlocked”, “sold”, “obsolete”, or “cant_maintain”

destroyer is applicable for “sabotaged” only.

Parameters:
  • city (City) – The city where the building was lost.

  • building (Building_Type) – The type of building that was lost.

  • reason (String) – The reason for the loss.

  • destroyer (Unit) – The unit responsible for the loss (if applicable).

tech_researched(tech_type: Tech_Type, player: Player, source: String)

A signal for when a technology is researched.

source may be: “researched”, “traded”, “stolen”, “hut”, or a user-defined value passed to the edit.give_tech() function.

Parameters:
  • tech_type (Tech_Type) – The type of technology that was researched.

  • player (Player) – The player who researched the technology.

  • source (String) – The source of the research.

city_destroyed(city: City, owner: Player, enemy: Player)

A signal for when a city is destroyed.

enemy may be nil if city was disbanded.

Parameters:
  • city (City) – The city that was destroyed.

  • owner (Player) – The player who owned the city.

  • enemy (Player) – The player who destroyed the city.

city_loot(city: City, unit: Unit)

A signal for when loot is taken from a captured city. This occurs before the city is captured so still belongs to the original owner, however it is after spaceship is lost if it was the capital.

See _deflua_city_conquer_gold_loot() for default implementation.

Parameters:
  • city (City) – The city from which loot was taken.

  • unit (Unit) – The unit that took the loot.

city_transferred(
    city: City,
    former_owner: Player,
    new_owner: Player,
    reason: String
)

A signal for when a city is transferred to another nation.

Reason is one of: “conquest”, “trade”, “incited”, “civil_war”, “death-back_to_original”, or “death-barbarians_get”

Parameters:
  • city (City) – The city that was transferred.

  • former_owner (Player) – The former owner of the city.

  • new_owner (Player) – The new owner of the city.

  • reason (String) – The reason for the transfer.

hut_enter(unit: Unit, extra: String)

A signal for when a unit enters a hut. Generated for any extra of category “Bonus” after it is removed if some extra on the tile has cause “Hut”.

Parameters:
  • unit (Unit) – The unit that entered the hut.

  • extra (String) – The rule name of the hut extra.

hut_frighten(unit: Unit, extra: String)

A signal for when a hut is frightened by a unit. Generated for any extra of category “Bonus” after it is removed if some extra on the tile has cause “Hut”, and the unit’s hut behaviour is “frighten”.

Parameters:
  • unit (Unit) – The unit that entered the hut.

  • extra (String) – The rule name of the hut extra.

unit_lost(unit: Unit, player: Player, reason: String)

A signal for when a unit is lost.

See Unit Loss Reasons.

Parameters:
  • unit (Unit) – The unit that was lost.

  • player (Player) – The player who lost the unit.

  • reason (String) – The reason for the loss.

disaster_occurred(disaster: Disaster, city: City)

A signal for when a disaster occurs.

Parameters:
  • disaster (Disaster) – The type of disaster that occurred.

  • city (City) – The city affected by the disaster.

nuke_exploded(tile: Tile, player: Player)

A signal for when a nuclear explosion occurs.

Parameters:
  • tile (Tile) – The tile where the explosion occurred.

  • player (Player) – The player responsible for the explosion.

achievement_gained(
    achievement: Achievement,
    player: Player,
    first: Boolean
)

A signal for when an achievement is gained.

Parameters:
  • achievement (Achievement) – The type of achievement gained.

  • player (Player) – The player who gained the achievement.

  • first (Boolean) – Indicates whether player is first one to reach the achievement.

map_generated()

A signal for when a map is generated.

pulse()

A signal for a pulse event. Pulses occur at approximately one second intervals. The time between pulses is not constant — this cannot be used to measure time.

action_started_unit_unit(action: Action, actor: Unit, target: Unit)

A signal for when a unit performs an act on another single unit.

For valid actions, see Actions Done by a Unit Against Another Unit

Parameters:
  • action (Action) – The action that is starting.

  • actor (Unit) – The unit that is performing the action.

  • target (Unit) – The unit the action is being performed on.

action_started_unit_units(action: Action, actor: Unit, tile: Tile)

A signal for when a unit performs an act on a stack of units.

For valid actions, see Actions Done by a Unit Against All Units at a Tile

Parameters:
  • action (Action) – The action that is starting.

  • actor (Unit) – The unit that is performing the action.

  • tile (Tile) – The tile where the unit stack is located.

action_started_unit_city(action: Action, actor: Unit, city: City)

A signal for when a unit performs an act on a city.

For valid actions, see Actions Done by a Unit Against a City

Parameters:
  • action (Action) – The action that is starting.

  • actor (Unit) – The unit that is performing the action.

  • city (City) – The city involved in the action.

action_started_unit_tile(action: Action, actor: Unit, tile: Tile)

A signal for when a unit performs an act on a tile.

For valid actions, see Actions Done by a Unit Against a Tile

Parameters:
  • action (Action) – The action that is starting.

  • actor (Unit) – The unit that is performing the action.

  • tile (Tile) – The tile involved in the action.

action_started_unit_self(action: Action, actor: Unit)

A signal for when a unit performs an act on itself.

For valid actions, see Actions Done by a Unit to Itself

Parameters:
  • action (Action) – The action that is starting.

  • actor (Unit) – The unit that is performing the action.

signal

Signals are emitted by the server when certain events occur.

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.

connect(signal_name: string, callback_name: string)

Register this Lua function to receive the given signal.

Parameters:
  • signal_name (string) – The Events signal name to receive callbacks for.

  • callback_name (string) – The global Lua function to call when this signal is emitted

remove(signal_name: string, callback_name: string)

Remove an existing registration of this Lua function to receive the given signal.

Parameters:
  • signal_name (string) – The Events signal name it should no longer receive callbacks for.

  • callback_name (string) – The global Lua function that should no longer receive this signal callback.

defined(signal_name: string, callback_name: string): (defined: boolean)

Check for an existing registration of this Lua function to receive the given signal.

Parameters:
  • signal_name (string) – The Events signal name to check if it receives callbacks for.

  • callback_name (string) – The global Lua function to check if it receives this signal callback.

Returns:

defined (boolean) – True, if this signal handler is defined.

list()

List all signals as well as any callbacks, via log.normal(). Intended for debugging.

replace(signal_name: string, callback_name: string)

Refreshes an existing registration of this Lua function to receive the given signal. This is intended for debugging purposes, and can be used for modifying a callback handler function while the server is running.

Parameters:
  • signal_name (string) – The Events signal name to receive callbacks for.

  • callback_name (string) – The global Lua function to call when this signal is emitted.

Types

class Player

Represents a nation in the game controlled by a specific player.

Note

In clients, functions that need full information about other players consider technologies status of which for specific player is not known to be unknown. Research information about players to which the client has no direct or indirect embassy access is initialized with zeros and nils. However, if embassy data source for some reason ceases to exist during playing session, currently the latest data get stuck, see #2770

name: string

The player’s name.

nation: Nation_Type

The nation from the nation list.

is_alive: boolean

If the nation is currently considered alive based on the ruleset.

id: int

The unique ID for this player.

team: Team

The player’s team.

num_cities(self: Player): (cities: int)
Returns:

cities (int) – The number of cities currently owned by this player.

num_units(self: Player): (units: int)
Returns:

units (int) – The number of units currently owned by this player.

has_wonder(self: Player, building: Building_Type): (present: boolean)
Parameters:

building (Building_Type) – The wonder to check for.

Returns:

present (boolean) – True if the player has this wonder in any city.

gold(self: Player): (gold: int)
Returns:

gold (int) – The amount of gold currently in this player’s treasury.

knows_tech(self: Player, tech: Tech_Type): (known: boolean)
Parameters:

tech (Tech_Type) – The advance to check for.

Returns:

known (boolean) – True if the player has this advance.

shares_research(self: Player, tech: any): (shares: boolean)
Returns:

shares (boolean) – True if this player shares research with the given player

research_rule_name(self: Player): (name: string)

This will either be the name of this player or the name of their team if team_pooled_research is enabled.

Returns:

name (string) – The name of the research owner.

research_name_translation(self: Player): (name: string)
Returns:

name (string) – As Player:research_rule_name but translated.

culture(self: Player): (culture: int)
Returns:

culture (int) – The player’s current culture score.

has_flag(self: Player): (present: boolean)
Table 13 Player Flags

Flag

Description

“ai”

Same as Player:ai_controlled.

“ScenarioReserved”

Not listed on game starting screen.

Returns:

present (boolean) – True if the player has this flag.

is_human(self: Player): (human: boolean)
Returns:

human (boolean) – True if this nation is controlled by a human player.

exists(self: Player): (exists: boolean)
Returns:

exists (boolean) – True if this nation (still) exists in the game.

units_iterate(self: Player)

Safe iteration over each Unit that belongs to a Player.

cities_iterate(self: Player)

Safe iteration over each City that belongs to a Player.

create_unit(
    self: Player,
    tile: Tile,
    utype: any,
    veteran_level: int,
    homecity: any,
    moves_left: int
): (unit: Unit)

See edit.create_unit()

create_unit_full(
    self: Player,
    tile: Tile,
    utype: any,
    veteran_level: int,
    homecity: any,
    moves_left: int,
    hp_left: int,
    ptransport: any
): (unit: Unit)

See edit.create_unit_full()

civilization_score(self: Player): (score: int)
Returns:

score (int) – The player’s current score.

create_city(self: Player, tile: Tile, name: string)

See edit.create_city()

change_gold(self: Player, amount: int)

See edit.change_gold()

give_tech(
    self: Player,
    tech: Tech_Type,
    cost: int,
    notify: bool,
    reason: string
): (tech: Tech_Type)

See edit.give_tech()

trait_mod(self: Player, trait: any, mod: int): bool

See edit.trait_mod()

civil_war(self: Player, probability: int): (rebel: Player)

See edit.civil_war()

victory(self: Player)

See edit.player_victory()

add_history(self: Player, amount: int)

See edit.add_player_history()

trait(self: Player, trait_name: string): (value: int)

Gets the 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.

Parameters:

trait_name (string) – The name of the trait to retrieve.

Returns:

value (int) – The value of the specified trait.

trait_base(self: Player, trait_name: string): (base: int)

Gets the base trait value (chosen at game start, before any trait_mod) for a player.

Parameters:

trait_name (string) – The name of the trait to retrieve.

Returns:

base (int) – The base value of the specified trait.

trait_current_mod(self: Player, trait_name: string): (modifier: int)

Gets the current modifier of a trait for a player.

Parameters:

trait_name (string) – The name of the trait to retrieve the current modifier for.

Returns:

modifier (int) – The current modification value of the specified trait.

class Team

Represents a Team of players that are locked together as allies.

id: int

The unique ID for this team

name: string

The name of the team

members_iterate(self: Team)

Safe iteration over each Player in the team.

class City

Represents a city on the world map.

name: string

The name of the city.

owner: Player

The current owner of the city.

original: Player

The original founder of the city.

id: int

The unique ID for the city.

size: int

The number of citizens in this city.

tile: Tile

The tile this city is on.

has_building(self: City, building: Building_Type): (present: boolean)
Parameters:

building (Building_Type) – The building type to check.

Returns:

present (boolean) – True if the given building type is in this city.

map_sq_radius(self: City): (sq-radius: int)
Returns:

sq-radius (int) – The square radius of the city working area.

inspire_partisans(self: City, inspirer: any): (partisans: int)

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

Returns:

partisans (int) – Positive if it would inspire partisans.

culture(self: City): (culture: int)
Returns:

culture (int) – Current total culture score for this city.

is_happy(self: City): (happy: boolean)

Note

A city can be both happy and celebrating at the same time.

Returns:

happy (boolean) – True if the city has more happy citizens than content and no unhappy or angry citizens.

is_celebrating(self: City): (celebrating: boolean)

Note

A city can be both happy and celebrating at the same time.

Returns:

celebrating (boolean) – True if the city is currently celebrating due to being happy for more than one turn.

is_unhappy(self: City): (unhappy: boolean)
Returns:

unhappy (boolean) – True if the city has fewer happy citizens than unhappy, with angry citizens counting as two unhappy.

is_gov_center(self: City): (gov-center: boolean)
Returns:

gov-center (boolean) – True if the city is a center of government for the purpose of distance to government center calculations.

is_capital(self: City): (capital: boolean)
Returns:

capital (boolean) – True if the city is the nation’s capital.

exists(self: City): (exists: boolean)
Returns:

exists (boolean) – True if the city (still) exists.

resize(self: City, size: int, reason: string)

See edit.resize_city()

remove(self: City)

See edit.remove_city()

add_history(self: City, amount: int)

See edit.add_city_history()

class Unit

Represents a unit on the world map.

utype: Unit_Type

The type of unit this is.

unit_class: Unit_Class

The class of this unit.

owner: Player

The player who owns the unit.

id: int

The unique ID for this unit.

tile: Tile

The tile the unit is currently on.

hp: int

The number of hitpoints the unit currently has left.

activity_name: string

The activity that the unit is currently performing.

activity_count: int

The number of work points that have been put into the current activity.

activity_target_name: string

The extra that is currently under construction, or nil.

nationality: Player

The nationality of the people in the unit.

moves_left: int

The number of move fragments remaining.

veteran: int

The veterancy level of the unit.

veteran_move_bonus: int

The additional move (and work) points granted by the unit’s veterancy level.

fuel: int

The amount of fuel remaining.

transporter(self: Unit): (unit: Unit)
Returns:

unit (Unit) – The unit that this one is loaded on, or nil.

is_on_possible_city_tile(self: Unit): (settleable: boolean)
Returns:

settleable (boolean) – True, if a settler unit can build a city here.

facing(self: Unit): (direction: Direction)
Returns:

direction (Direction) – The current unit orientation.

Attention

Warning: If unit is going to be removed, you must use Unit:tile_link_text instead.

Returns:

link-text (string) – Link string fragment to add to messages sent to client.

Returns:

link-text (string) – Link string fragment to add to messages sent to client.

exists(self: Unit): (exists: boolean)
Returns:

exists (boolean) – True, if the unit (still) exists.

get_homecity(self: Unit): (home: City)
Returns:

home (City) – The home city of this unit, or nil.

hp_pct(self: Unit): (hp-pct: Number)
Returns:

hp-pct (Number) – The percentage of the unit’s maximum hitpoints that remain.

cargo_iterate(self: Unit)

Safe iteration over the units transported by this unit. Only iterates over units directly transported by this one, if any. Does not include nested units.

veteran_power_bonus(self: Unit): (power: Number)
Returns:

power (Number) – The multiplier to attack and defense power granted by the unit’s veterancy level.

upkeep_food(self: Unit): (food: int)
Returns:

food (int) – The total amount of food consumed per turn in the home city.

upkeep_shields(self: Unit): (shields: int)
Returns:

shields (int) – The total amount of shields consumed per turn in the home city.

upkeep_gold(self: Unit): (gold: int)
Returns:

gold (int) – The total amount of gold consumed per turn.

happy_cost(self: Unit): (citizens: int)
Returns:

citizens (int) – The total amount of unhappiness caused in the home city.

birth_turn(self: Unit): (turn_number: int)
Returns:

turn_number (int) – The turn that the unit was first created.

teleport(self: Unit, dest: Tile): bool

See edit.unit_teleport()

turn(self: Unit, direction: Direction)

See edit.unit_turn()

kill(self: Unit, reason: string, killer: Player)

See edit.unit_kill()

damage_hp(self: Unit, amount: int, reason: string, killer: Player): bool

See edit.unit_damage_hp()

damage_hp_pct(self: Unit, amount: int, reason: string, killer: Player): bool

Damages a unit by a percentage of its max hitpoints. See edit.unit_damage_hp()

recover_hp(self: Unit, amount: int)

See edit.unit_recover_hp()

recover_hp_pct(self: Unit, amount: int)

The unit recovers by a percentage of its max hitpoints. See edit.unit_recover_hp()

set_hp(self: Unit, amount: int)

See edit.unit_set_hp()

set_hp_pct(self: Unit, amount: int)

The unit is set to a percentage of its max hitpoints. See edit.unit_set_hp()

move(self: Unit, moveto: Tile, movecost: int): bool

See edit.unit_move()

movement_disallow(self: Unit)

See edit.movement_disallow()

movement_allow(self: Unit)

See edit.movement_allow()

activity_count_set(self: Unit, work_points: int)

Note

If this is set above the required number of work points for the current activity, it will complete immediately.

Parameters:

work_points (int) – The total number of work points that have been put into the current activity.

activity_count_add(self: Unit, work_points: int)

Note

If this is set above the required number of work points for the current activity, it will complete immediately.

Parameters:

work_points (int) – The number of work points to add to the current activity.

nationality_set(self: Unit, nationality: Player)
Parameters:

nationality (Player) – The nationality of the people in the unit.

moves_left_set(self: Unit, moves_left: int)

Note

This may exceed the max for the Unit_Type.move_rate type, but cannot be lower then zero.

Parameters:

moves_left (int) – The number of move fragments remaining.

moves_left_add(self: Unit, moves_left: int)

Note

This may exceed the max for the Unit_Type.move_rate type, but gets capped at zero when adding negative amounts.

Parameters:

moves_left (int) – The number of move fragments to add.

veteran_level_set(self: Unit, veteran: int)

Note

This cannot be less than zero or exceed Unit_Type.max_veteran_level.

Note

This does not automatically notify the Player who owns the unit.

Parameters:

veteran (int) – The veterancy level of the unit.

veteran_level_add(self: Unit, veteran: int): (changed: boolean)

Note

This will be capped between zero and Unit_Type:max_veteran_level.

Note

This does not automatically notify the Player who owns the unit.

Parameters:

veteran (int) – The number of veterancy levels to add to the unit.

Returns:

changed (boolean) – True, if the veteran level changed as a result.

fuel_set(self: Unit, fuel: int)

Note

This cannot exceed the max Unit_Type.fuel, and cannot be lower then zero.

Parameters:

fuel (int) – The amount of fuel remaining.

fuel_add(self: Unit, fuel: int): (changed: boolean)

Note

This will be capped at the max Unit_Type.fuel, and capped at zero for negative amounts.

Parameters:

fuel (int) – The amount of fuel to add.

Returns:

changed (boolean) – True, if the fuel level changed as a result.

class Tile

Represents a tile on the world map.

Note

The native coordinate system represents the internal coordinates for a tile on the server. The map coordinate system is how it appears in the client based on the chosen topology. You can see both in the tile info panel.

terrain: Terrain

The terrain type of this tile.

owner: Player

The player who owns this tile, or nil.

id: int

The unique ID of this tile.

continent: int

The ID of the continent this tile is on.

nat_x: int

The X position of this tile on the native coordinate system.

nat_y: int

The Y position of this tile on the native coordinate system.

x: int

The X position of this tile on the map coordinate system.

y: int

The Y position of this tile on the map coordinate system.

Link string fragment to add to messages sent to client.

city(self: Tile): (city: City)
Returns:

city (City) – The city that is on this tile, or nil.

city_exists_within_max_city_map(self: Tile, center: boolean): (exists: boolean)
Parameters:

center (boolean) – True, if the center tile should be checked also.

Returns:

exists (boolean) – True if there is a city within the maximum radius a city map can ever have in Freeciv21 (not necessarily possible in the current ruleset) – currently within 5 tiles.

has_extra(self: Tile, name: boolean): (present: boolean)
Parameters:

name (boolean) – The ruleset name of any type of terrain extra.

Returns:

present (boolean) – True, if the extra is present on this tile.

has_base(self: Tile, name: boolean): (True: boolean, the: if)
Parameters:

name (boolean) – The ruleset name of any base-type extra.

Returns:
  • True (boolean) – base is present on this tile.

  • the (if) – base is present on this tile.

has_road(self: Tile, name: boolean): (True: boolean, the: if)
Parameters:

name (boolean) – The ruleset name of any road-type extra.

Returns:
  • True (boolean) – road-type is present on this tile.

  • the (if) – road-type is present on this tile.

primary_resource_name(self: Tile): (name: string)

The primary tile resource persists even if the terrain is changed to an incompatible type, and can be recovered if the terrain is changed back. This will report the name of the hidden resource in this case. Whereas Tile:has_extra will only report whether the resource is currently visible.

Returns:

name (string) – The ruleset name of the primary tile resource, or nil.

is_enemy(self: Tile, against: Player): (enemy: boolean)
Parameters:

against (Player) – The player to check against.

Returns:

enemy (boolean) – True, if the given player has enemies on this tile.

num_units(self: Tile): (units: int)
Returns:

units (int) – The total number of units on this tile.

sq_distance(self: Tile, other: Tile): (dist: int)
Parameters:

other (Tile) – A different tile to check against.

Returns:

dist (int) – The squared distance between these two tiles.

units_iterate(self: Tile)

Safe iteration over each Unit on the tile.

square_iterate(self: Tile, radius: any): (iterator: function)

This function returns an iterator that yields tiles in a square pattern, expanding outward from the current tile up to the specified radius.

In a square topology, square_iterate(1) returns 9 tiles.

Returns:

iterator (function) – An iterator function.

circle_iterate(self: Tile, sq_radius: any): (iterator: function)

This function returns an iterator that yields tiles in a circular pattern, expanding outward from the current tile up to the specified squared radius.

In a square topology, circle_iterate(1) returns 5 tiles.

Returns:

iterator (function) – An iterator function.

create_owned_extra(self: Tile, name: string, player: Player)

See edit.create_owned_extra()

create_extra(self: Tile, name: string)

See edit.create_extra()

remove_extra(self: Tile, name: string)

See edit.remove_extra()

change_terrain(self: Tile, terrain: Terrain_Type)

See edit.change_terrain()

set_primary_resource(self: Tile, resource: string)

See edit.tile_primary_resource_set()

unleash_barbarians(self: Tile): bool

See edit.unleash_barbarians()

place_partisans(self: Tile, player: Player, count: int, sq_radius: int)

See edit.place_partisans()

set_label(self: Tile, label: string)

See edit.tile_set_label()

class Government

Represents a government type for this ruleset.

id: int

The unique ID of this government type.

rule_name(self: Government): (name: string)
Returns:

name (string) – The name given by the ruleset.

name_translation(self: Government): (name: string)
Returns:

name (string) – The localised translation of the name.

class Nation_Type

Represents a nation type for this ruleset.

id: int

The unique ID of this nation type.

rule_name(self: Nation_Type): (name: string)
Returns:

name (string) – The name given by the ruleset.

name_translation(self: Nation_Type): (name: string)
Returns:

name (string) – The localised translation of the name.

plural_translation(self: Nation_Type): (name: string)
Returns:

name (string) – The translation of the name in plural form.

trait_min(self: Nation_Type, trait_name: string): (min: int)

Gets the minimum start value of an AI trait for a nation type.

Parameters:

trait_name (string) – The name of the AI trait.

Returns:

min (int) – The minimum value of the specified trait.

trait_max(self: Nation_Type, trait_name: string): (max: int)

Gets the maximum start value of an AI trait for a nation type.

Parameters:

trait_name (string) – The name of the AI trait.

Returns:

max (int) – The maximum value of the specified trait.

trait_default(self: Nation_Type, trait_name: string): (default: int)

Gets the default start value of an AI trait for a nation type. Used when server option traitdistribution is FIXED.

Parameters:

trait_name (string) – The name of the AI trait.

Returns:

default (int) – The default value of the specified trait.

class Building_Type

Represents a type of building that can be constructed in a city in this ruleset.

build_cost: int

The number of shields required to construct.

id: int

The unique ID of the building type.

is_wonder(self: Building_Type): (wonder: boolean)
Returns:

wonder (boolean) – True, if this can be built once in the world or once per nation.

is_great_wonder(self: Building_Type): (great-wonder: boolean)
Returns:

great-wonder (boolean) – True, if this can be built once in the world.

is_small_wonder(self: Building_Type): (small-wonder: boolean)
Returns:

small-wonder (boolean) – True, if this can be built once per nation.

is_improvement(self: Building_Type): (improvement: boolean)
Returns:

improvement (boolean) – True, if this can be built multiple times by a nation.

rule_name(self: Building_Type): (name: string)
Returns:

name (string) – The name given by the ruleset.

name_translation(self: Building_Type): (name: string)
Returns:

name (string) – The localised translation of the name.

build_shield_cost(self: Building_Type): (cost: int)
Returns:

cost (int) – The number of shields needed to construct this building.

class Unit_Type

Represents a type of unit available in this ruleset.

id: int

The unique ID of the unit type.

unit_class: Unit_Class

The class of this unit type.

build_cost: int

The number of shields required to make.

pop_cost: int

The number of citizens consumed to make.

attack: int

Base attack strength (0 = cannot attack.)

defense: int

Base defence strength (0 = cannot defend.)

hp: int

The maximum number of hitpoints.

firepower: int

Number of enemy hitpoints removed per successful round of combat.

bombard_rate: int

The number of rounds of bombardment.

move_rate: int

The base number of move fragments that can be employed each turn.

max_veteran_level: int

The maximum veteran level that units of this type can achieve.

vision_radius_sq: int

The base squared vision radius.

transport_cap: int

The number of passengers that can be held at once.

fuel: int

The maximum fuel that can be held.

paratroopers_range: int

The maximum range of a paradrop.

upkeep_food: int

The base amount of food consumed per turn in the home city.

upkeep_shields: int

The base amount of shields consumed per turn in the home city.

upkeep_gold: int

The base amount of gold consumed per turn.

happy_cost: int

The base amount of unhappiness caused in the home city.

city_slots: int

The number of unit maintenance slots taken up in the home city.

city_size: int

The initial number of citizens provided when founding a city.

vision_layer_name: string

The layer at which this unit is visible. Can be “Main”, “Stealth”, or “Subsurface”.

has_flag(self: Unit_Type, flag_name: string): (present: boolean)
Parameters:

flag_name (string) – The name of the unit type flag to check for.

Returns:

present (boolean) – True, if this unit type has the given flag.

has_role(self: Unit_Type, role_name: string): (present: boolean)
Parameters:

role_name (string) – The name of the unit type role to check for.

Returns:

present (boolean) – True, if this unit type has the given role.

rule_name(self: Unit_Type): (name: string)
Returns:

name (string) – The name given by the ruleset.

name_translation(self: Unit_Type): (name: string)
Returns:

name (string) – The localised translation of the name.

can_exist_at_tile(self: Unit_Type, tile: Tile): (safe: boolean)
Parameters:

tile (Tile) – The tile to check.

Returns:

safe (boolean) – True, if the unit type can normally exist on the given tile.

build_shield_cost(self: Unit_Type): (cost: int)
Returns:

cost (int) – The total shield cost to build this unit type. Same as Unit_Type.build_cost.

class Unit_Class

Represents a class of unit types.

id: int

The unique ID of the unit class.

min_speed: int

The minimum speed that units of this class can move at.

hp_loss_pct: int

The percentage of hitpoints lost each turn that the unit is not in a city or airbase.

non_native_def_pct: int

Defense power multiplier percentage when defending on non-native terrain (such as ship in harbour.)

rule_name(self: Unit_Class): (name: string)
Returns:

name (string) – The name given by the ruleset.

name_translation(self: Unit_Class): (name: string)
Returns:

name (string) – The localised translation of the name.

has_flag(self: Unit_Class, flag_name: string): (present: boolean)
Parameters:

flag_name (string) – The name of the unit class flag to check for.

Returns:

present (boolean) – True, if this unit class has the given flag.

class Tech_Type

Represents a technological or cultural advance that a nation can research.

id: int

The unique ID of the advance.

rule_name(self: Tech_Type): (name: string)
Returns:

name (string) – The name given by the ruleset.

name_translation(self: Tech_Type): (name: string)
Returns:

name (string) – The localised translation of the name.

class Terrain

Represents a type of terrain that may appear on the map in this ruleset.

id: int

The unique ID of the terrain type.

rule_name(self: Terrain): (name: string)
Returns:

name (string) – The name given by the ruleset.

name_translation(self: Terrain): (name: string)
Returns:

name (string) – The localised translation of the name.

class_name(self: Terrain): (class: string)
Returns:

class (string) – The localised translation of the name.

class Disaster

Represents a type of disaster that can occur for a city in this ruleset.

id: int

The unique ID of the disaster type.

rule_name(self: Disaster): (name: string)
Returns:

name (string) – The name given by the ruleset.

name_translation(self: Disaster): (name: string)
Returns:

name (string) – The localised translation of the name.

class Achievement

Represents an achievement that a player can unlock in this ruleset.

id: int

The unique ID of the achievement.

rule_name(self: Achievement): (name: string)
Returns:

name (string) – The name given by the ruleset.

name_translation(self: Achievement): (name: string)
Returns:

name (string) – The localised translation of the name.

class Connection

Represents a player’s current connection to the game server.

id: int

The unique ID of the connection.

class Action

Represents a type of action that a unit can perform in this ruleset.

id: int

The unique ID of the action type.

rule_name(self: Action): (name: string)
Returns:

name (string) – The name given by the ruleset.

name_translation(self: Action): (name: string)
Returns:

name (string) – The localised translation of the name.

Nonexistent.exists(self: unknown): boolean

Checks if the object (still) exists.

Functions

Internationalization

String translation functions are used for localizable event messages included with the game. See Internationalization

_(text: String): (translated: String)
Parameters:

text (String) – The raw text to translate.

Returns:

translated (String) – The translated text.

N_(text: String): (raw-text: String)
Parameters:

text (String) – The raw text to mark for translation.

Returns:

raw-text (String) – The raw text again.

Q_(text: String): (translated: String)
Parameters:

text (String) – The raw text to disambiguate.

Returns:

translated (String) – The translated text.

PL_(singular: String, plural: String, count: int): (translated: String)
Parameters:
  • singular (String) – The raw text in singular form.

  • plural (String) – The raw text in plural form.

  • count (int) – The quantity to determine which form is used.

Returns:

translated (String) – The translated text for use with string.format.

Utilities

random(min: int, max: int): (roll: Number)

Generates a random number using Freeciv21’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.

Parameters:
  • min (int) – The minimum roll value (inclusive).

  • max (int) – The maximum roll value (inclusive).

Returns:

roll (Number) – The random number.

fc_version(): (version: String)
Returns:

version (String) – The current version of the project.

players_iterate()

Iterate over each Player in the game.

whole_map_iterate()

Iterate over each Tile on the map.

Debugging

listenv()

List all defined lua variables (functions, tables)

_freeciv_state_dump(): (state: string)

Dump the state of user scalar variables to a Lua code string.

list()

List all signals as well as any callbacks, via log.normal(). Intended for debugging.

fc_version(): (version: String)
Returns:

version (String) – The current version of the project.

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

Table 14 Unit Loss Reasons

Reason

Game Event

Loser Score

Killer Score

“killed”

  1. Unit loses a battle

  2. 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”

  1. Killed by shields upkeep

  2. 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”

  1. An unique unit is transferred with a city to a player having such one

  2. A unit from a lost city can’t be rehomed to another city

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

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”

  1. Got to a nonnative terrain by edit.unit_teleport or paradropping

  2. 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”

  1. Could not bounce out of a tile with non-allied units or city

  2. Moved to non-allied city or unit tile by edit.unit_teleport()

Yes

No

“bribed”

Bribed by enemy diplomat.***

Yes

Yes*

“captured”

Captured by enemy unit.***

Yes

Yes*

“caught”

  1. A diplomatic action failed from the beginning

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

Note

* The killer can be specified only by a script.

** Killer submitted only if the action was failed.

*** A new unit is created under the new ownership to replace the

old unit after the signal is processed.

Lua Built-ins

Some Lua builtin functions and modules are also available in Freeciv21 (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.

Lua Functions

Lua Globals

Lua Modules