[TOTPP] Lua function reference

TheNamelessOne

Warlord
Joined
Dec 18, 2013
Messages
227
Here's the complete reference of all Lua functions and data that can be used to interact with the game.

With v0.15 of ToTPP, scenario designers are able to change otherwise static rules during the course of the game. These changes are ephemeral, i.e. they only last for the current session, and will be restored to their default values on load. It is up to the designer to persist these changes, and apply them again in the onLoad trigger of the scenario. Such properties are marked below with 'Ephemeral'.



The civ library


Functions

addImprovement
civ.addImprovement(city, improvement) -> void

Adds city improvement `improvement` to city `city`.


canEnter
civ.canEnter(unittype, tile) -> boolean

Returns `true` if the given unittype can enter tile `tile`, `false` otherwise.


captureCity
civ.captureCity(city, tribe) -> void

Captures city `city` for tribe `tribe`.


createCity
civ.createCity(tribe, tile) -> city

Creates a city owned by `tribe` at the location given by `tile`. Returns `nil` if a city could not be created.


createUnit
civ.createUnit(unittype, tribe, tile) -> unit

Creates a unit of type `unittype`, owned by `tribe`, at the location given by `tile`.


deleteCity
civ.deleteCity(city) -> void

Deletes city `city` from the game.


deleteUnit
civ.deleteUnit(unit) -> void

Deletes unit `unit` from the game.


destroyWonder
civ.destroyWonder(wonder) -> void

Destroys wonder `wonder`, removing it from the game, and marking it as 'lost'.


enableTechGroup
civ.enableTechGroup(tribe, techgroup, value) -> void

Sets the value of tech group `techgroup` (0-7) to value `value` (0-2, 0 = can research, can own, 1 = can't research, can own, 2 = can't research, can't own) for tribe `tribe`.


endGame
civ.endGame(endscreens=false) -> void

Ends the game. `endscreens` is a boolean that determines whether to show the powergraph and related screens.


getActiveUnit
civ.getActiveUnit() -> unit

Returns the currently active unit.


getAtlasDimensions (since 0.16)
civ.getAtlasDimensions() -> width, height, number_of_maps

Returns three integers, the width and height of the map and the number of maps.


getBaseTerrain (since 0.16)
civ.getBaseTerrain(map, terrainType) -> baseterrain

Returns the base terrain object for the given map and terrain type.


getCity
civ.getCity(id) -> city

Returns the city with id `id`, or `nil` if it doesn't exist.


getCommodity (since 0.17)
civ.getCommodity(id) -> commodity

Returns the commodity with id `id` (0-15 for regular commodities, -1 for food supplies), or `nil` if it doesn't exist.


getCurrentTile
civ.getCurrentTile() -> tile

Returns the currently selected tile.


getCurrentTribe
civ.getCurrentTribe() -> tribe

Returns the currently active tribe.


getGameYear
civ.getGameYear() -> integer

Returns the current game year.


getImprovement
civ.getImprovement(id) -> improvement

Returns the improvement with id `id` (0-39), or `nil` if it doesn't exist.


getMap (since 0.16)
civ.getMap(id) -> map

Returns the map with id `id` (0-3) or `nil` if it doesn't exist.


getMapDimensions (deprecated since 0.16)
civ.getMapDimensions() -> width, height, number_of_maps

Alias for getAtlasDimensions.


getOpenCity (since 0.16)
civ.getOpenCity() -> city

Returns the city currently opened in the city window, `nil` if the city window is closed.


getPlayerTribe
civ.getPlayerTribe() -> tribe

Returns the player's tribe.


getTech
civ.getTech(id) -> tech

Returns the tech with id `id` (0-99), or `nil` if it doesn't exist.


getTerrain (since 0.16)
civ.getTerrain(map, terrainType, resource) -> terrain

Returns the terrain object for the given map, terrain type and resource.


getTile
civ.getTile(x, y, z) -> tile

Returns the tile with coordinates `x`, `y`, `z`, or `nil` if it doesn't exist.


getToTDir
civ.getToTDir() -> string

Returns the absolute path of the ToT installation directory.


getTribe
civ.getTribe(id) -> tribe

Returns the tech with id `id` (0-7), or `nil` if it doesn't exist.


getTurn
civ.getTurn() -> integer

Returns the current turn number.


getUnit
civ.getUnit(id) -> integer

Returns the unit with id `id`, or `nil` if it doesn't exist.


getUnitType
civ.getUnitType(id) -> unittype

Returns the unit type with id `id`, or `nil` if it doesn't exist.


getWonder
civ.getWonder(id) -> wonder

Returns the wonder with id `id` (0-27), or `nil` if it doesn't exist.


giveTech
civ.giveTech(tribe, tech) -> void

Gives tech `tech` to tribe `tribe`.


hasImprovement
civ.hasImprovement(city, improvement) -> void

Returns `true` if city `city` has improvement `improvement`, `false` otherwise.


hasTech
civ.hasTech(tribe, tech) -> boolean

Returns `true` if tribe `tribe` has tech `tech`, `false` otherwise.


isBaseTerrain (since 0.16)
civ.isBaseTerrain(object) -> boolean

Returns `true` if `object` is a base terrain, `false` otherwise.


isCity
civ.isCity(object) -> boolean

Returns `true` if `object` is a city, `false` otherwise.


isDialog (since 0.16)
civ.isDialog(object) -> boolean

Returns `true` if `object` is a dialog, `false` otherwise.


isImage (since 0.16)
civ.isImage(object) -> boolean

Returns `true` if `object` is an image, `false` otherwise.


isImprovement
civ.isImprovement(object) -> boolean

Returns `true` if `object` is a city improvement, `false` otherwise.


isLeader
civ.isLeader(object) -> boolean

Returns `true` if `object` is a leader, `false` otherwise.


isMap (since 0.16)
civ.isMap(object) -> boolean

Returns `true` if `object` is a map, `false` otherwise.


isTech
civ.isTech(object) -> boolean

Returns `true` if `object` is a tech, `false` otherwise.


isTerrain (since 0.16)
civ.isTerrain(object) -> boolean

Returns `true` if `object` is a terrain, `false` otherwise.


isTile
civ.isTile(object) -> boolean

Returns `true` if `object` is a tile, `false` otherwise.


isTradeRoute (since 0.17)
civ.isTradeRoute(object) -> boolean

Returns `true` if `object` is a trade route, `false` otherwise.


isTribe
civ.isTribe(object) -> boolean

Returns `true` if `object` is a tribe, `false` otherwise.


isUnit
civ.isUnit(object) -> boolean

Returns `true` if `object` is a unit, `false` otherwise.


isUnitType
civ.isUnitType(object) -> boolean

Returns `true` if `object` is a unit type, `false` otherwise.


isWonder
civ.isWonder(object) -> boolean

Returns `true` if `object` is a wonder, `false` otherwise.


iterateCities
civ.iterateCities() -> iterator

Returns an iterator yielding all cities in the game.


iterateUnits
civ.iterateUnits() -> iterator

Returns an iterator yielding all units in the game.


killTribe
civ.killTribe(tribe) -> void

Removes tribe `tribe` from the game. All its cities and units are removed.


makeAggression
civ.makeAggression(who, whom) -> void

Cancels any peace treaties between tribe `who` and tribe `whom`, and make `who` declare war on `whom`.


playMusic
civ.playMusic(trackNo or filename) -> void

Plays CD track `trackNo`, or with the DirectShow music patch enabled, play the file given by `filename`, where `filename` is relative to the 'Music' directory.


playSound
civ.playSound(filename) -> void

Plays the sound file given by `filename`.


playVideo
civ.playVideo(filename) -> void

Plays the video file given by `filename`.


removeImprovement
civ.removeImprovement(city, improvement) -> void

Removes city improvement `improvement` from city `city`.


sleep
civ.sleep(milliseconds) -> void

Sleeps for the given number of milliseconds.


takeTech
civ.takeTech(tribe, tech, collapse=false) -> void

Takes away tech `tech` from tribe `tribe`, the optional `collapse` parameter determines whether to take away all techs that have `tech` as a prerequisite somewhere up the tree.


teleportUnit
civ.teleportUnit(unit, tile) -> void

Teleports (i.e. moves at no cost) unit `unit` to tile `tile`. The unit is moved regardless of whether it is a valid location for the unit. To check this, see `civ.canEnter` and `civlua.isValidUnitLocation`.



The civ.ui library


Functions

centerView
civ.ui.centerView(tile) -> void

Centers the map on the given tile.


createDialog
civ.ui.createDialog() -> dialog

Creates and initializes a dialog. See the dialog section for more details.


loadImage
civ.ui.loadImage(filename, [x], [y], [width], [height]) -> image

Loads an image (BMP or GIF) from `filename`. Optionally accepts `x`, `y`, `width` and `height` to load part of the image.


loadTerrain
civ.ui.loadTerrain(map, filename1, filename2) -> void

Replaces terrain graphics for map number `map`, loading graphics from `filename1` (corresponding to "TERRAIN1.BMP") and `filename2` (corresponding to "TERRAIN2.BMP")


redrawMap
civ.ui.redrawMap() -> void

Redraws the entire map.


redrawTile
civ.ui.redrawTile(tile) -> void

Redraws the given tile.


setZoom
civ.ui.setZoom(integer) -> void

Sets the zoom level (range from -7 (max zoom out) to 8 (max zoom in)).


text
civ.ui.text(string) -> void

Display a pop-up text box with the given string as text.


zoomIn
civ.ui.zoomIn() -> void

Zooms in on the map (increases zoom level by 1).


zoomOut
civ.ui.zoomOut() -> void

Zooms out of the map (decreases zoom level by 1).



The city object


Properties

attributes (get/set)
city.attributes -> integer

Returns the city's attributes (bitmask).


baseTrade (get)
city.baseTrade -> integer

Returns the number of trade arrows before trade routes.


coastal (get)
city.coastal -> boolean

Returns whether or not the city is on a coast (can build coastal improvements).


currentProduction (get/set) (since 0.16)
city.currentProduction -> unit type or improvement or wonder

Returns the city's current production.


food (get/set)
city.food -> integer

Returns the quantity of food in store.


id (get)
city.id -> integer

Returns the city's id.


knownTo (get/set)
city.knownTo -> integer

Returns a bitmask indicating the tribes that have knowledge of this city.


location (get)
city.location -> tile

Returns the city's location. See the `relocate` method for a way to set this.


name (get/set)
city.name -> string

Returns the city's name.


numHappy (get)
city.numHappy -> integer

Returns the number of happy citizens.


numTradeRoutes (get)
city.numTradeRoutes -> integer

Returns the number of trade routes of the city.


numUnhappy (get)
city.numUnhappy -> integer

Returns the number of unhappy citizens.


originalOwner (get/set)
city.originalOwner -> tribe

Returns the city's original owner. This can be different from `owner` if the city was captured in the past.


owner (get/set)
city.owner -> tribe

Returns the city's owner.


science (get)
city.science -> integer

Returns the amount of science the city produces.


shields (get/set)
city.shields -> integer

Returns the number of shields towards the current item in production.


size (get/set)
city.size -> integer

Returns the city's size.


sizeForTribe (get/set) (since 0.16)
city.sizeForTribe[tribe] -> integer

Returns the city's size as known by the given tribe.


specialists (get/set)
city.specialists -> integer

Returns the city's specialists as a integer, 16 x 2 bits per specialist (0 - No specialist, 1 - Entertainer, 2 - Taxman, 3 - Scientist)


tax (get)
city.tax -> integer

Returns the amount of tax the city produces.


totalFood (get)
city.totalFood -> integer

Returns the total amount of food the city produces.


totalShield (get)
city.totalShield -> integer

Returns the total amount of shields the city produces.


totalTrade (get)
city.totalTrade -> integer

Returns the total amount of trade arrows the city produces (including trade routes).


tradeRoutes (get) (since 0.17)
city.tradeRoutes[id] -> traderoute

Returns the trade route with id `id` (0-2), or `nil` if not in use.


turnsSinceCapture (get/set)
city.turnsSinceCapture -> integer

Returns the number of turns since the city was last captured.


workers (get/set)
city.workers -> integer

Returns a bitmask with the workers and specialists of the city.


Methods

addImprovement
city:addImprovement(improvement) -> void

Alias for `civ.addImprovement(city, improvement)`.


addTradeRoute (since 0.17)
city:addTradeRoute(destination, commodity) -> void

Adds a new trade route to city `destination`, with commodity `commodity`. Returns an error if all 3 trade slots are already in use.


canBuild
city:canBuild(item) -> boolean

Returns whether or not `item` can currently be built in the city. `item` can be a unittype, improvement or wonder.


hasImprovement
city:hasImprovement(improvement) -> boolean

Alias for `civ.hasImprovement(city, improvement)`.


popTradeRoute (since 0.17)
city:popTradeRoute() -> void

Removes the last trade route, or does nothing if no trade routes are in use.


relocate
city:relocate(tile) -> boolean

Relocates the city to the location given by `tile`. Returns `true` if successful, `false` otherwise (if a city is already present for example).


removeImprovement
city:removeImprovement(improvement) -> void

Alias for `civ.removeImprovement(city, improvement)`.


removeTradeRoute (since 0.17)
city:removeTradeRoute(id) -> void

Removes the trade route with index `id` (0-2). This shifts elements after `id` to fill gaps in the array, so references to trade routes may not be valid anymore after calling this.



The traderoute object (since 0.17)


Properties

commodity (get/set)
traderoute.commodity -> commodity

The commodity of the trade route.


from (get)
traderoute.from -> city

The origin of the trade route.


id (get)
traderoute.id -> integer

The id of the trade route.


to (get/set)
traderoute.to -> city

The destination of the trade route.


Methods

remove
traderoute:remove() -> void

Alias for city:removeTradeRoute(id).



The commodity object (since 0.17)


Properties

id (get)
commodity.id -> integer

The id of the commodity (0-15 for regular commodities, -1 for food supplies).


name (get/set - ephemeral)
commodity.name -> string

The name of the commodity.



The tile object


Properties

baseTerrain (get/set) (since 0.16)
tile.baseTerrain -> baseterrain

Returns the baseterrain object associated with the tile.


city (get)
tile.city -> city

Returns the city at the tile's location, or `nil` if there's no city there.


defender (get)
tile.defender -> tribe

Returns the tile's defender.


fertility (get/set)
tile.fertility -> integer

Returns the tile's fertility.


grasslandShield (get) (since 0.16)
tile.grasslandShield -> boolean

Returns `true` if the tile would have a shield when changed to grassland, `false` otherwise.


hasGoodieHut (get) (since 0.18.2)
tile.hasGoodieHut -> boolean

Returns `true` if the tile has a goodie hut, `false` otherwise.


improvements (get/set)
tile.improvements -> integer

Returns the tile's improvements (bitmask).


landmass (get/set)
tile.landmass -> integer

Returns the tile's landmass index.


owner (get/set)
tile.owner -> tribe

Returns the tribe owning the tile.


river (get/set)
tile.river -> boolean

Returns `true` if the tile has a river, `false` otherwise.


terrain (get/set) (since 0.16)
tile.terrain -> terrain

Returns the terrain object associated with the tile.


terrainType (get/set)
tile.terrainType -> integer

Returns the terrain type of the tile.


units (get)
tile.units -> iterator

Returns an iterator yielding all units at the tile's location.


visibility (get/set) (since 0.16)
tile.visibility -> integer

Returns the tile's visibility for each tribe (bitmask).


visibleImprovements (get/set) (since 0.16)
tile.visibleImprovements[tribe] -> integer

Returns the tile's improvements as known by the given tribe (bitmask).


x (get)
tile.x -> integer

Returns the `x` coordinate of the tile.


y (get)
tile.y -> integer

Returns the `y` coordinate of the tile.


z (get)
tile.z -> integer

Returns the `z` coordinate of the tile (map number).



The unit object


Properties

attackSpent (get/set) (since 0.18)
unit.attackSpent -> integer

Returns the number of attacks spent by the unit (from the 'Attacks per turn' patch).


attributes (get/set)
unit.attributes -> integer

Returns the attributes of the unit (bitmask).


carriedBy (get/set)
unit.carriedBy -> unit

Returns the carrying unit if this unit is currently on board, `nil` otherwise. The game shares the memory location of this field with gotoTile.x, so don't use this field if gotoTile is not `nil`.


damage (get/set)
unit.damage -> integer

Returns the damage taken by the unit in hitpoints.


domainSpec (get/set) (since 0.16)
unit.domainSpec -> integer

Returns the value of the 'domain-specific counter' of the unit.


gotoTile (get/set)
unit.gotoTile -> tile

Returns the tile the unit is moving to under the goto order, or `nil` if it doesn't have the goto order.


hitpoints (get)
unit.hitpoints -> integer

Returns the number of hitpoints left. It is defined as unit.type.hitpoints - unit.damage.


homeCity (get/set)
unit.homeCity -> city

Returns the unit's home city, or `nil` if it doesn't have one.


id (get)
unit.id -> integer

Returns the unit's id.


location (get)
unit.location -> tile

Returns the unit's location.


moveSpent (get/set)
unit.moveSpent -> integer

Returns the number of moves spent by the unit.


order (get/set)
unit.order -> integer

Returns the current order of the unit.


owner (get/set)
unit.owner -> tribe

Returns the unit's owner.


type (get)
unit.type -> unittype

Returns the unit's type.


veteran (get/set)
unit.veteran -> boolean

Returns the veteran status of the unit.


visibility (get/set) (since 0.17)
unit.visibility -> integer

Returns the unit visibility mask.


Methods

activate
unit:activate() -> void

Activates a unit, clearing its orders, and, if it has a human owner and movement points left, selects it on the map.


teleport
unit:teleport(tile) -> void

Alias for `civ.teleportUnit(unit, tile)`.



The unittype object


Properties

advancedFlags (get/set - ephemeral) (since 0.16)
unittype.advancedFlags -> integer

Returns the 'advanced flags' settings of the unit type (bitmask).


attack (get/set - ephemeral)
unittype.attack -> integer

Returns the attack factor of the unit type.


attacksPerTurn (get/set - ephemeral) (since 0.18)
unittype.attacksPerTurn -> integer

Returns the number of attacks available per turn of the unit type (from the 'Attacks per turn' patch).


buildTransport (get/set)
unittype.buildTransport -> integer

Returns the 'build transport site' settings of the unit type (bitmask).


cost (get/set - ephemeral)
unittype.cost -> integer

Returns the cost of the unit type.


defense (get/set - ephemeral)
unittype.defense -> integer

Returns the defense factor of the unit type.


domain (get/set - ephemeral)
unittype.domain -> integer

Returns the domain of the unit type (0 - Ground, 1 - Air, 2 - Sea).


expires (get/set - ephemeral)
unittype.expires -> tech

Returns the tech that renders the unit obsolete, or `nil` if there isn't any.


firepower (get/set - ephemeral)
unittype.firepower -> integer

Returns the firepower of the unit type.


flags (get/set - ephemeral)
unittype.flags -> integer

Returns the flags of the unit type (bitmask).


hitpoints (get/set - ephemeral)
unittype.hitpoints -> integer

Returns the number of hit points of the unit type.


hold (get/set - ephemeral)
unittype.hold -> integer

Returns the number of holds of the unit type.


id (get)
unittype.id -> integer

Returns the id of the unit type.


minimumBribe (get/set - ephemeral) (since 0.16)
unittype.minimumBribe -> integer

Returns the minimum amount to bribe the unit type.


move (get/set - ephemeral)
unittype.move -> integer

Returns the movement rate of the unit type.


name (get)
unittype.name -> string

Returns the name of the unit type.


nativeTransport (get/set)
unittype.nativeTransport -> integer

Returns the 'native transport' settings of the unit type (bitmask).


notAllowedOnMap (get/set - ephemeral) (since 0.16)
unittype.notAllowedOnMap -> integer

Returns the 'not allowed on map' settings of the unit type (bitmask).


prereq (get/set - ephemeral)
unittype.prereq -> tech

Returns the prerequisite technology of the unit type, or `nil` if it doesn't have one.


range (get/set - ephemeral)
unittype.range -> integer

Returns the range of the unit type.


role (get/set - ephemeral)
unittype.role -> integer

Returns the role of the unit type.


tribeMayBuild (get/set - ephemeral) (since 0.16)
unittype.tribeMayBuild -> integer

Returns the 'tribe may build' settings of the unit type (bitmask).


useTransport (get/set)
unittype.useTransport -> integer

Returns the 'use transport site' settings of the unit type (bitmask).


Methods

canEnter
unittype:canEnter(tile) -> boolean

Alias for `civ.canEnter(unittype, tile)`



The tribe object


Properties

active (get)
tribe.active -> boolean

Returns whether the tribe is active, i.e. a human or AI player in the current game.


adjective (get/set)
tribe.adjective -> string

Returns the adjectival form of the tribe's name (e.g. "Roman").


attitude (get/set)
tribe.attitude[otherTribe] -> integer

Returns the tribe's attitude to `otherTribe`.


betrayals (get/set)
tribe.betrayals -> integer

Returns the number of times the tribe has betrayed another tribe.


futureTechs (get/set)
tribe.futureTechs -> integer

Returns the number of future techs the tribe has researched.


government (get/set)
tribe.government -> integer

Returns the government (0 - 6) of the tribe.


id (get)
tribe.id -> integer

Returns the id of the tribe.


isHuman (get/set)
tribe.isHuman -> boolean

Returns whether the tribe is a/the human player.


leader (get)
tribe.leader -> leader

Returns the leader of the tribe.


money (get/set)
tribe.money -> integer

Returns the amount of money/gold in the tribe's treasury.


name (get/set)
tribe.name -> string

Returns the name of the tribe (e.g. "Romans").


numCities (get)
tribe.numCities -> integer

Returns the number of cities the tribe has.


numTechs (get/set)
tribe.numTechs -> integer

Returns the number of techs the tribe has.


numUnits (get)
tribe.numUnits -> integer

Returns the number of units the tribe has.


patience (get/set)
tribe.patience -> integer

Returns the tribe's patience.


reputation (get/set)
tribe.reputation[otherTribe] -> integer

Returns the tribe's reputation with `otherTribe`.


researchCost (get)
tribe.researchCost -> integer

Returns the research cost of the tribe.


researchProgress (get/set)
tribe.researchProgress -> integer

Returns the progress towards the current research (range between 0 and tribe.researchCost).


researching (get/set)
tribe.researching -> tech

Returns the tech the tribe is currently researching, or `nil` if not researching anything.


scienceRate (get)
tribe.scienceRate -> integer

Returns the science rate of the tribe.


spaceship (get)
tribe.spaceship -> spaceship

Returns the space ship object of the tribe.


taxRate (get)
tribe.taxRate -> integer

Returns the tax rate of the tribe.


treaties (get/set)
tribe.treaties[otherTribe] -> integer

Returns the tribe's treaties with `otherTribe`.


Methods

enableTechGroup
tribe:enableTechGroup(techgroup, value) -> void

Alias for `civ.enableTechGroup(tribe, techgroup, value)`.


giveTech
tribe:giveTech(tech) -> void

Alias for `civ.giveTech(tribe, tech)`.


hasTech
tribe:hasTech(tech) -> boolean

Alias for `civ.hasTech(tribe, tech)`.


kill
tribe:kill() -> void

Alias for `civ.killTribe(tribe)`.


takeTech
tribe:takeTech(tech, collapse=false) -> void

Alias for `civ.takeTech(tribe, tech, collapse=false)`.



The improvement object


Properties

cantSell (get/set - ephemeral)
improvement.cantSell -> boolean

Returns `true` if the improvement cannot be sold, `false` otherwise. Requires the "Improvement flags" patch.


cost (get/set - ephemeral)
improvement.cost -> integer

Returns the cost of the improvement in rows. Multiply by civ.cosmic.shieldRows for the actual production cost.


id (get)
improvement.id -> integer

Returns the id of the improvement.


name (get)
improvement.name -> string

Returns the name of the improvement (e.g. "Barracks").


onCapture (get/set - ephemeral)
improvement.onCapture -> integer

Returns what happens to this improvement when a city is captured (0 - Default, 1 - Preserve, 2 - Destroy, 3 - Random). Requires the "Improvement flags" patch.


prereq (get/set - ephemeral)
improvement.prereq -> tech

Returns the prerequisite tech of the improvement.


upkeep (get/set - ephemeral) (since 0.16)
improvement.upkeep -> integer

Returns the upkeep cost of the improvement.



The tech object


Properties

aiValue (get/set - ephemeral)
tech.aiValue -> integer

Returns the AI value of the tech.


category (get/set - ephemeral)
tech.category -> integer

Returns the category of the tech.


epoch (get/set - ephemeral)
tech.epoch -> integer

Returns the epoch of the tech.


group (get/set - ephemeral)
tech.group -> integer

Returns the group of the tech.


id (get)
tech.id -> integer

Returns the id of the tech.


modifier (get/set - ephemeral)
tech.modifier -> integer

Returns the modifier to the AI value based on leader personality.


name (get)
tech.name -> string

Returns the name of the tech.


prereq1 (get/set - ephemeral)
tech.prereq1 -> tech

Returns the first prerequisite of the tech.


prereq2 (get/set - ephemeral)
tech.prereq2 -> tech

Returns the second prerequisite of the tech.


researched (get)
tech.researched -> boolean

Returns whether or not any tribe has researched the tech.



The leader object


Properties

attack (get/set - ephemeral)
leader.attack -> integer

Returns the "attack" value of the leader's personality.


cityStyle (get/set - ephemeral)
leader.cityStyle -> integer

Returns the leader's city style.


civilize (get/set - ephemeral)
leader.civilize -> integer

Returns the "civilize" value of the leader's personality.


color (get/set - ephemeral)
leader.color -> integer

Returns the leader's color.


expand (get/set - ephemeral)
leader.expand -> integer

Returns the "expand" value of the leader's personality.


female (get/set)
leader.female -> boolean

Returns whether or not the leader is female.


id (get)
leader.id -> integer

Returns the id of the leader.


name (get/set)
leader.name -> string

Returns the name of the leader.



The wonder object


Properties

city (get/set)
wonder.city -> city

Returns the city that has built the wonder, `nil` if not built yet or destroyed.


cost (get/set - ephemeral)
wonder.cost -> integer

Returns the cost of the wonder.


destroyed (get)
wonder.destroyed -> boolean

Returns whether or not the wonder is destroyed. Use wonder:destroy() to set this field.


expires (get/set - ephemeral)
wonder.expires -> tech

Returns the tech that renders the wonder obsolete, or `nil` if there isn't any.


id (get)
wonder.id -> integer

Returns the id of the wonder.


name (get)
wonder.name -> string

Returns the name of the wonder.


prereq (get/set - ephemeral)
wonder.prereq -> tech

Returns the prerequisite technology of the wonder.


Methods

destroy
wonder:destroy() -> void

Alias for `civ.destroyWonder(wonder)`.



The spaceship object


Properties

fuel (get/set)
spaceship.fuel -> integer

Returns the number of fuel components of the space ship.


fusionPowered (get/set)
spaceship.fusionPowered -> boolean

Returns `true` if the space ship has fusion power.


habitation (get/set)
spaceship.habitation -> integer

Returns the number of habitation modules of the space ship.


landed (get/set)
spaceship.landed -> boolean

Returns `true` if the space ship has landed.


launched (get/set)
spaceship.launched -> boolean

Returns `true` if the space ship is launched.


lifesupport (get/set)
spaceship.lifesupport -> integer

Returns the number of life support modules of the space ship.


owner (get)
spaceship.owner -> tribe

Returns the owner of the space ship.


propulsion (get/set)
spaceship.propulsion -> integer

Returns the number of propulsion components of the space ship.


solar (get/set)
spaceship.solar -> integer

Returns the number of solar modules of the space ship.


structural (get/set)
spaceship.structural -> integer

Returns the number of structural improvements of the space ship.



The dialog object


Properties

height (get/set)
dialog.height -> integer

Returns the height of the dialog. Normally this does not need to be set, since the height is automatically calculated from the height of the items.


title (get/set)
dialog.title -> string

Returns the title of the dialog.


width (get/set)
dialog.width -> integer

Returns the width of the dialog.


Methods

addCheckbox
dialog:addCheckbox(string, id, initial=false) -> void

Adds a checkbox to the dialog, with label given by `string`. `id` is an integer value that can be used in dialog:getCheckboxState to retrieve the state after calling dialog:show. `initial` is an optional boolean parameter, if set to `true` the checkbox will be checked initially. Can not be used in conjunction with dialog:addOption.


addImage
dialog:addImage(image) -> void

Adds an image to the dialog.


addOption
dialog:addOption(string, id) -> void

Adds a selectable option to the dialog, with label given by `string`. `id` is an integer value returned by dialog:show if this option was selected. Can not be used in conjunction with dialog:addCheckbox.


addText
dialog:addText(string) -> void

Adds a static text string to the dialog.


getCheckboxState
dialog:getCheckboxState(id) -> boolean

Returns the state of the checkbox identified by `id` after dialog:show has been called.


show
dialog:show() -> integer

Renders the dialog on screen. If this is an option dialog, returns the id of the selected option (see dialog:addOption). If this is a checkbox dialog, returns 0 if OK was pressed, -1 if Exit was pressed. Use dialog:getCheckboxState to query the individual checkboxes.
This method can only be called once per dialog. It will return an error if invoked a second time.

Example:
Code:
dialog = civ.ui.createDialog()
dialog.title = "My first dialog"
dialog.width = 250
dialog:addOption("Foo", 1)
dialog:addOption("Bar", 2)
dialog:show()



The map object (since 0.16)


Properties

customResources (get/set)
map.customResources -> boolean

Returns `true` if custom resources are enabled for this map, `false` otherwise.


height (get)
map.height -> integer

Returns the height of the map.


id (get)
map.id -> integer

Returns the id of the map.


width (get)
map.width -> integer

Returns the width of the map.


Methods

copyDefaultResources
map:copyDefaultResources() -> void

Enables custom resources for this map and copies the default resource pattern. Requires the "Custom resources" patch.


getBaseTerrain
map:getBaseTerrain(terrainType) -> baseterrain

Alias for `civ.getBaseTerrain(map, terrainType)`


getTerrain
map:getTerrain(terrainType, resource) -> terrain

Alias for `civ.getTerrain(map, terrainType, resource)`



The baseterrain object (since 0.16)


A baseterrain represents a (map, terrainType)-tuple.

Properties

abbrev (get)
baseterrain.abbrev -> string

The terrain abbreviation for this baseterrain (e.g. 'Drt', 'Pln' etc.).


canIrrigate (get/set - ephemeral)
baseterrain.canIrrigate -> boolean

Returns `true` if the underlying terrain type allows irrigation, `false` otherwise.


canMine (get/set - ephemeral)
baseterrain.canMine -> boolean

Returns `true` if the underlying terrain type allows mining, `false` otherwise.


defense (get/set - ephemeral)
baseterrain.defense -> integer

The defense factor of the underlying terrain type.


impassable (get/set - ephemeral)
baseterrain.impassable -> boolean

Returns `true` if the underlying terrain type is impassable, `false` otherwise.


irrigateAI (get/set - ephemeral)
baseterrain.irrigateAI -> integer

The minimum government level needed for the AI to consider irrigating.


irrigateBonus (get/set - ephemeral)
baseterrain.irrigateBonus -> integer

The extra amount of food from irrigation.


irrigateTo (get/set - ephemeral)
baseterrain.irrigateTo -> baseterrain

If the irrigation order changes the underlying terrain type return the baseterrain of the new terrain type, `nil` otherwise.


irrigateTurns (get/set - ephemeral)
baseterrain.irrigateTurns -> integer

The number of turns for settlers to irrigate.


map (get)
baseterrain.map -> integer

The map associated with the baseterrain object.


mineAI (get/set - ephemeral)
baseterrain.mineAI -> integer

The minimum government level needed for the AI to consider mining.


mineBonus (get/set - ephemeral)
baseterrain.mineBonus -> integer

The extra amount of production from mining.


mineTo (get/set - ephemeral)
baseterrain.mineTo -> baseterrain

If the mine order changes the underlying terrain type return the baseterrain of the new terrain type, `nil` otherwise.


mineTurns (get/set - ephemeral)
baseterrain.mineTurns -> integer

The number of turns for settlers to mine.


moveCost (get/set - ephemeral)
baseterrain.moveCost -> integer

The movement cost of the underlying terrain type.


name (get)
baseterrain.name -> string

The name of this baseterrain.


transformTo (get/set - ephemeral)
baseterrain.transformTo -> baseterrain

If the underlying terrain type can be transformed return the baseterrain of the new terrain type, `nil` otherwise.


type (get)
baseterrain.type -> integer

The terrain type associated with the baseterrain object.


Methods

getTerrain
baseterrain:getTerrain(resource) -> terrain

Returns the terrain object corresponding to the underlying terrain type and the given resource.



The terrain object (since 0.16)


A terrain represents a (map, terrainType, resource)-tuple.

Properties

baseTerrain (get)
terrain.baseTerrain -> baseterrain

The underlying baseterrain of the terrain object.


food (get/set - ephemeral)
terrain.food -> integer

The amount of food produced by the terrain.


map (get)
terrain.map -> integer

The map associated with the terrain object.


name (get)
terrain.name -> string

The name of the terrain.


resource (get)
terrain.resource -> integer

The resource associated with the terrain object.


shields (get/set - ephemeral)
terrain.shields -> integer

The amount of shields produced by the terrain.


trade (get/set - ephemeral)
terrain.trade -> integer

The amount of trade produced by the terrain.


type (get)
terrain.type -> integer

The terrain type associated with the terrain object.



The cosmic library


Properties

communismPalaceDistance (get/set - ephemeral)
cosmic.communismPalaceDistance -> integer

Returns the distance from palace used in happiness calculations under Communism.


foodEaten (get/set - ephemeral)
cosmic.foodEaten -> integer

Returns the amount of food eaten by each citizen each turn.


foodRows (get/set - ephemeral)
cosmic.foodRows -> integer

Returns the number of rows in the food box.


goodieHutsMask (get/set - ephemeral)
cosmic.goodieHutsMask -> integer

Returns the bitmask for goodie huts.


helisPickupHuts (get/set - ephemeral)
cosmic.helisPickupHuts -> integer

Returns whether helicopters (domain 1, range 0 units) pick up huts or not.


massThrustParadigm (get/set - ephemeral)
cosmic.massThrustParadigm -> integer

Returns the mass/thrust paradigm.


numberOfUnitTypes (get)
cosmic.numberOfUnitTypes -> integer

Returns the number of unit types from the @COSMIC2 key of the same name.


paradropRange (get/set - ephemeral)
cosmic.paradropRange -> integer

Returns the maximum paradrop range.


penaltyBetrayal (get/set - ephemeral)
cosmic.penaltyBetrayal -> integer

Returns the penalty to the civilization score for each betrayal of another tribe.


prodChangePenalty (get/set - ephemeral)
cosmic.prodChangePenalty -> integer

Returns the shield penalty percentage for changing production types.


riotFactor (get/set - ephemeral)
cosmic.riotFactor -> integer

Returns the riot factor based on the number of cities.


roadMultiplier (get/set - ephemeral)
cosmic.roadMultiplier -> integer

Returns the road movement multiplier.


scienceLostFundamentalism (get/set - ephemeral)
cosmic.scienceLostFundamentalism -> integer

Returns the percentage of science lost under Fundamentalism.


scienceRateFundamentalism (get/set - ephemeral)
cosmic.scienceRateFundamentalism -> integer

Returns the maximum effective science rate under Fundamentalism.


scoreCentauri (get/set - ephemeral)
cosmic.scoreCentauri -> integer

Returns the civilization score for each landing on Alpha Centauri first. Multiplied by number of habitats and success probability.


scoreCitizen (get/set - ephemeral)
cosmic.scoreCitizen -> integer

Returns the civilization score for each citizen.


scoreFutureTech (get/set - ephemeral)
cosmic.scoreFutureTech -> integer

Returns the civilization score for each future technology researched.


scorePeace (get/set - ephemeral)
cosmic.scorePeace -> integer

Returns the civilization score for each turn of peace after turn 199.


scorePollution (get/set - ephemeral)
cosmic.scorePollution -> integer

Returns the civilization score for each extant non-AI controlled polluted tile. Normally a negative value, i.e. a penalty.


scoreUnitKilled (get/set - ephemeral)
cosmic.scoreUnitKilled -> integer

Returns the civilization score for each unit killed.


scoreWonder (get/set - ephemeral)
cosmic.scoreWonder -> integer

Returns the civilization score for each wonder.


settlersEatHigh (get/set - ephemeral)
cosmic.settlersEatHigh -> integer

Returns the amount of food eaten by settlers for governments ≥ Communism.


settlersEatLow (get/set - ephemeral)
cosmic.settlersEatLow -> integer

Returns the amount of food eaten by settlers for governments ≤ Monarchy.


shieldRows (get/set - ephemeral)
cosmic.shieldRows -> integer

Returns the number of rows in the shield box.


sizeAquaduct (get/set - ephemeral)
cosmic.sizeAquaduct -> integer

Returns the city size that cannot be exceeded without an Aquaduct.


sizeSewer (get/set - ephemeral)
cosmic.sizeSewer -> integer

Returns the city size that cannot be exceeded without a Sewer System.


sizeUnhappiness (get/set - ephemeral)
cosmic.sizeUnhappiness -> integer

Returns the city size at which the first unhappy citizen appears at Chieftain difficulty.


supportCommunism (get/set - ephemeral)
cosmic.supportCommunism -> integer

Returns the number of units that are free of support under Communism.


supportFundamentalism (get/set - ephemeral)
cosmic.supportFundamentalism -> integer

Returns the number of units that are free of support costs under Fundamentalism.


supportMonarchy (get/set - ephemeral)
cosmic.supportMonarchy -> integer

Returns the number of units that are free of support under Monarchy.


techParadigm (get/set - ephemeral)
cosmic.techParadigm -> integer

Returns the tech paradigm. Scenarios use civ.scen.params.techParadigm instead of this value.


transformBase (get/set - ephemeral)
cosmic.transformBase -> integer

Returns the base time needed for engineers to transform terrain.


triremeLost (get/set - ephemeral)
cosmic.triremeLost -> integer

Returns the 1 in x chance of a trireme getting lost at sea.



The game library


Properties

activeTribes (get/set)
game.activeTribes -> integer

Returns the active tribe mask.


barbarianActivity (get/set)
game.barbarianActivity -> integer

Returns the level of barbarian activity.


difficulty (get/set)
game.difficulty -> integer

Returns the difficulty level.


gameYear (get/set)
game.gameYear -> integer

Returns the game year, or for scenarios with monthly increments, the number of months * 12.


humanPlayers (get/set)
game.humanPlayers -> integer

Returns the human players mask.


humanTribe (get)
game.humanTribe -> tribe

Returns the last active human tribe.


peaceTurns (get/set)
game.peaceTurns -> integer

Returns the number of turns of peace.


revealMap (get/set)
game.revealMap -> boolean

Returns whether or not the full map is revealed.


turnsElapsed (get/set)
game.turnsElapsed -> integer

Returns the number of turns elapsed.



The game.rules library (since 0.16)


Properties

flatWorld (get/set)
game.rules.flatWorld -> boolean

Returns `true` if the world map is flat, `false` otherwise.



The civ.scen library


Functions

onActivateUnit
civ.scen.onActivateUnit(function (unit, source, repeatMove [since 0.17]) -> void) -> void

Registers a function to be called every time a unit is activated. The callback takes the unit activated as a parameter, and the source of unit activation. `source` is `true` if activated by keyboard or mouse click, `false` if activated by the game itself. `repeatMove` is `true` if it's a repeat activation caused by moving (see civ.scen.compatibility), `false` otherwise.


onBribeUnit
civ.scen.onBribeUnit(function (unit, previousOwner) -> void) -> void

Registers a function that is called when a unit is bribed successfully. unit.owner is the new owner at this point, `previousOwner` the old owner.


onCalculateCityYield (since 0.16)
civ.scen.onCalculateCityYield(function (city, food, shields, trade) -> (foodChange, shieldChangeBeforeWaste, shieldChangeAfterWaste, tradeChangeBeforeCorruption, tradeChangeAfterCorruption)) -> void

Registers a function to be called every time a city calculates its total resource yield. Input is the city, and the food, shields and trade of its tiles. Returns a 5-tuple of modifiers, food change, shield change before waste, shield change after waste, trade change before corruption, trade change after corruption. These modifiers are applied at the following points in the calculation:
  • Calculate yield from all worked tiles
  • Run onCalculateCityYield
  • Add foodChange, shieldChangeBeforeWaste and tradeChangeBeforeCorruption
  • Add changes from food trade routes
  • Add shields from improvements
  • Calculate and subtract waste
  • Calculate corruption and add changes from commodity trade routes
  • Calculate corruption again (now using the value after trade routes) and subtract.
  • Add shieldChangeAfterWaste and tradeChangeAfterCorruption
  • Calculate Tax/Lux/Sci


onCanBuild
civ.scen.onCanBuild(function (defaultBuildFunction, city, item) -> boolean) -> void

Registers a function to be called every time a check is done whether a city can build something or not. It is called for all unit types, improvements and wonders. The first parameter of the callback is the default build function, as implemented by the game. It takes the city and item as parameters. You can call this to produce a result for cases you don't need to handle yourself. `item` can be a unittype, improvement or wonder.
Return `true` if `city` is allowed to produce `item`, `false` if not.


onCanFoundCity (since 0.18)
civ.scen.onCanFoundCity(function (unit, advancedTribe) -> boolean) -> void

Registers a function that is called to determine if `unit` can found a city at the unit's location. `advancedTribe` is `true` when picking up a hut with `unit` triggers an advanced tribe. Return `true` to allow, `false` to disallow.


onCentauriArrival
civ.scen.onCentauriArrival(function (tribe) -> void) -> void

Registers a function that is called when a tribe's spaceship reaches its target. Just registering this function causes the game to not end at this point ("endgame override").


onChooseDefender (since 0.17)
civ.scen.onChooseDefender(function (defaultFunction, tile, attacker, isCombat) -> unit) -> void

Registers a function that is called every time a unit is chosen to defend a tile. The first parameter is the default function as implemented by the game. It takes `tile` and `attacker` as parameters. You can call this to produce a result for cases you don't need to handle yourself. The second parameter is the tile that's being considered, the third is the attacking unit, and the fourth, `isCombat`, is a boolean that indicates if this invocation will be followed by combat. This function is also called by the AI to determine its goals, in which case `isCombat` is false.


onCityDestroyed
civ.scen.onCityDestroyed(function (city) -> void) -> void

Registers a function that is called when a city is destroyed.


onCityFounded
civ.scen.onCityFounded(function (city) -> optional (function () -> void)) -> void

Registers a function to be called every time a city is founded. The callback takes the city as a parameter, and can optionally return a function (since 0.18) that is called to perform cleanup when the user cancels founding the city.


onCityProcessingComplete (since 0.18)
civ.scen.onCityProcessingComplete(function (turn, tribe) -> void) -> void

Registers a function that is called when a tribe's cities have been processed for that turn. See `onTurn` for interaction with other "turn" triggers.


onCityProduction
civ.scen.onCityProduction(function (city, prod) -> void) -> void

Registers a function that is called when a city completes its production order. The produced item `prod` is either a unit, improvement or wonder (this can be checked with the civ.is* functions).


onCityTaken
civ.scen.onCityTaken(function (city, defender) -> void) -> void

Registers a function that is called when a city is captured. `city` is the city changing hands, at this point city.owner is the new owner already. `defender` is the old owner.


onGameEnds
civ.scen.onGameEnds(function (reason) -> boolean) -> void

Registers a function that is called when the game ends. `reason` is an integer between 1 and 6:
1 and 2 - Space race victory. This does not trigger if `onCentauriArrival` has a callback registered.
3 - Conquest victory
4 - Defeat
5 - Retirement
6 - Macro ENDGAME action
Return `true` to end the game, `false` to keep playing.


onGetFormattedDate (since 0.18)
civ.scen.onGetFormattedDate(function (turn, defaultDateString) -> string) -> void

Registers a function that is called when the game needs to get the date string for a given turn (e.g. "4000 B.C." for turn 1). `turn` is the turn for which the date is requested (not always the current turn), and `defaultDateString` is the string as formatted by the game


onGetRushBuyCost (since 0.17)
civ.scen.onGetRushBuyCost(function (city, cost) -> integer) -> void

Registers a function that is called when calculating the cost to rush-buy a city's current production. It takes the city and the cost as calculated by the game as parameters. Returns an integer representing the new costs.


onInitiateCombat (since 0.16)
civ.scen.onInitiateCombat(function (attacker, defender, attackerDie, attackerPower, defenderDie, defenderPower, isSneakAttack [since 0.17]) -> coroutine) -> void

Registers a function to be called every time combat is initiated. The callback takes seven parameters, the attacker, the defender, attackerDie ('die' as in dice, the attacker's chance to hit), attackerPower (attacker's firepower), defenderDie, defenderPower and isSneakAttack. Returns a coroutine that yields every time it wants to process a round, and returns when it wants combat to end. Example:

Code:
civ.scen.onInitiateCombat(function (attacker, defender, attackerDie, attackerPower, defenderDie, defenderPower)
  print("Attacker's die: 1d" .. attackerDie .. ", firepower: " .. attackerPower)
  print("Defender's die: 1d" .. defenderDie .. ", firepower: " .. defenderPower)
  return coroutine.create(function ()
    local round = 0
    while (round < 5 and attacker.hitpoints >= 0 and defender.hitpoints >= 0) do
      print("Round " .. round)
      print(attacker, defender)
      if round % 2 == 0 then
        attacker.damage = attacker.damage + 2
        coroutine.yield(true, defender) -- either attacker or defender
      else
        print("Attack bonus!")
        result = coroutine.yield(false, attackerDie * 2, attackerPower * 2)
        print(result.winner, result.attackerRoll, result.defenderRoll, result.reroll)
      end
      round = round + 1
    end
    print("End of combat")
  end)
end)

This example shows how to limit combat to five rounds, damages the attacker on even rounds and doubles the attacker's values on odd rounds.

If the coroutine yields true as its first value, the game's default combat resolution is skipped for that round and the designer is responsible for updating damage. The second value yielded is either the attacker or the defender, this is used to render animations etc. In this case the coroutine resumes without any values.

If the coroutine yields false as its first value, the game runs its default combat algorithm. The designer can additionally yield modified values for attackerDie, attackerPower, defenderDie and defenderPower (in this order) which will be used by the game for that round. In this case the coroutine resumes with the result of the round, a table containing four values:
  • winner, this is either attacker or defender.
  • attackerRoll, the result of the attacker's die roll
  • defenderRoll, the result of the defender's die roll
  • reroll, true if a reroll happened. This can happen only if the attacker is tribe 0, the defender is a unit guarding a city, and the city is the capital or the tribe has less than 8 cities in total and the attacker's die roll is higher than the defender's. A reroll can happen at most once.


onKeyPress
civ.scen.onKeyPress(function (keyCode) -> void) -> void

Registers a function to be called every time a key is pressed.


onLoad
civ.scen.onLoad(function (string) -> void) -> void

Registers a function that is called when the game is loaded.


onNegotiation
civ.scen.onNegotiation(function (talker, listener) -> boolean) -> void

Registers a function that is called when two tribes attempt negotiations. `talker` is the tribe initiating the contact, `listener` the receiver. Return `true` to allow the negotiations to commence, `false` to deny.


onResolveCombat (deprecated since 0.16)
civ.scen.onResolveCombat(function (defaultResolutionFunction, defender, attacker) -> boolean) -> void

Registers a function to be called during every combat turn. The first parameter of the callback is the default resolution function, as implemented by the game. It takes the attacker and defender as parameters. You can call this to produce a result for cases you don't need to handle yourself.
Return `true` to continue combat, `false` to stop.

See onInitiateCombat for replacement.


onSave
civ.scen.onSave(function () -> string) -> void

Registers a function that is called when the game is saved.


onScenarioLoaded
civ.scen.onScenarioLoaded(function () -> void) -> void

Registers a function that is called when the scenario is loaded.


onSchism
civ.scen.onSchism(function (tribe) -> boolean) -> void

Registers a function that is called when a schism is triggered. This happens when the capital of a AI-controlled tribe with more than four cities is captured, and, if the attacker is human-controlled, it is ranked lower in power than the defender. If the attacker is AI-controlled the best human tribe must be ranked lower than the defender for the schism to trigger.
If the schism is allowed, a new tribe will be created that takes over about half the cities of the old tribe. If no new tribe can be created, the schism does not occur.
Return `true` to allow the schism to happen, `false` to deny.


onSelectMusic (since 0.18)
civ.scen.onSelectMusic(function (track) -> optional integer) -> void

Registers a function that is called when a new music track is to be played. `track` is either nil or an integer. If nil, the game wants to play a random track, if not nil it's either due to the user choosing a track from the menu (first track has id 0), or the game playing one of it's special tracks ("Funeral March" - track id 0, and "Ode to Joy" - track id 1). To handle special tracks, you can return nil to signal that the game should play the default track associated with that track id. If you want to handle this track id, call civ.playMusic (this will check the Music folder of the scenario first before falling back to the global Music folder) and return an integer, which is used to synchronize the track list in the menu. The track names can be added in @PICKMUSICTOT in Game.txt.


onTribeTurnBegin (since 0.18)
civ.scen.onTribeTurnBegin(function (turn, tribe) -> void) -> void

Registers a function that is called at the start of a tribe's turn. See `onTurn` for interaction with other "turn" triggers.


onTribeTurnEnd (since 0.18)
civ.scen.onTribeTurnEnd(function (turn, tribe) -> void) -> void

Registers a function that is called at the end of a tribe's turn. See `onTurn` for interaction with other "turn" triggers.


onTurn
civ.scen.onTurn(function (turn) -> void) -> void

Registers a function that is called at the start of a turn. The basic sequence of this and other "turn" triggers is as follows:
  • `onTurn` fires
  • Non-tribe-specific updates take place
  • `onTribeTurnBegin` fires for tribe 0.
  • Tribe 0 cities are processed.
  • `onCityProcessingComplete` fires for tribe 0 (this fires even when a tribe has no cities).
  • Tribe 0 units move
  • `onTribeTurnEnd` fires for tribe 0.
  • All active tribes are processed in order according to the sequence for tribe 0
  • `onTribeTurnEnd` fires for tribe 7.
  • `onTurn` fires for the next turn


onUnitKilled
civ.scen.onUnitKilled(function (loser, winner) -> void) -> void

Registers a function that is called whenever a unit is killed. `loser` is the unit that is killed, `winner` is the unit responsible for it.


onUseNuclearWeapon (since 0.18)
civ.scen.onUseNuclearWeapon(function (unit, tile) -> boolean) -> void

Registers a function that is called when a nuclear weapon is used. This is also called when a spy plants a nuclear device in a city. `unit` is the weapon or the spy unit, `tile` is the location of the attack. Return `false` to abort the attack, `true` to proceed.



The civ.scen.params library


Properties

decisiveDefeat (get/set)
civ.scen.params.decisiveDefeat -> integer

Number of objectives required for a decisive defeat.


decisiveVictory (get/set)
civ.scen.params.decisiveVictory -> integer

Number of objectives required for a decisive victory.


flags (get/set)
civ.scen.params.flags -> integer

Bitmask representing scenario flags:

00000000 00000001 Total war
00000000 00000010 Use objective victory
00000000 00000100 Count wonders as objectives
00000000 00001000 Reveal cities
00000000 00010000 No government change
00000000 00100000 No tech conquest
00000000 01000000 No pollution
00000000 10000000 Terrain animation lockout
00000001 00000000 Unit animation lockout
00000010 00000000 .SPR file override
01000000 00000000 Scenario is a TOTPP mod
10000000 00000000 WWII AI


marginalDefeat (get/set)
civ.scen.params.marginalDefeat -> integer

Number of objectives required for a marginal defeat.


marginalVictory (get/set)
civ.scen.params.marginalVictory -> integer

Number of objectives required for a marginal victory.


maxTurns (get/set)
civ.scen.params.maxTurns -> integer

Maximum number of turns before the scenario ends.


name (get/set)
civ.scen.params.name -> string

The name of the scenario.


objectivesProtagonist (get/set)
civ.scen.params.objectivesProtagonist -> tribe

Returns the objectives protagonist.


startingYear (get)
civ.scen.params.startingYear -> integer

Returns the starting year of the scenario.


techParadigm (get/set)
civ.scen.params.techParadigm -> integer

Returns the tech paradigm used by the scenario. Non-scenario games use civ.cosmic.techParadigm instead of this value.


yearIncrement (get/set)
civ.scen.params.yearIncrement -> integer

Returns the year increment (number of years per turn). Negative for monthly increments.



The civ.scen.compatibility library (since 0.17)


Enable or disable certain behavior of the scenario library.

Properties

activateUnitEveryMove (get/set - ephemeral)
civ.scen.compatibility.activateUnitEveryMove -> boolean

If set to true, onActivateUnit will re-trigger for every tile the active unit moves. Defaults to false, in which case onActivateUnit triggers only once.



The totpp library


The `totpp` library provides data about TOTPP itself, and is also available for individual ToTPP patches to register sub-libraries in, to allow interacting with them from the game.

Properties

patches (get) (since 0.16)
totpp.patches -> table<string, boolean>

Returns a table with the enabled status for all patches. The string keys are the same as the ones used in TOTPP.ini


roadTrade (get/set - ephemeral) (since 0.16)
totpp.roadTrade[map] -> integer

Returns a bitmask with the terrain types that receive an initial trade arrow when a road is built. Provided by the Initial trade arrow for roads patch.



The totpp.version library (since 0.16)


Properties

major (get)
totpp.version.major -> integer

Returns the major version of the TOTPP dll.


minor (get)
totpp.version.minor -> integer

Returns the minor version of the TOTPP dll.


patch (get)
totpp.version.patch -> integer

Returns the patch version of the TOTPP dll.



The totpp.movementMultipliers library


Provided by the Movement multipliers patch.

Properties

aggregate (get)
totpp.movementMultipliers.aggregate -> integer

Returns the aggregate movement multiplier (the lcm of the four multipliers above). This value is recalculated when setting any of the individual multipliers. This is an alias for `civ.cosmic.roadMultiplier`.


alpine (get/set - ephemeral)
totpp.movementMultipliers.alpine -> integer

Returns the alpine movement multiplier if it is set, `nil` otherwise.


railroad (get/set - ephemeral)
totpp.movementMultipliers.railroad -> integer

Returns the railroad movement multiplier if it is set, `nil` otherwise.


river (get/set - ephemeral)
totpp.movementMultipliers.river -> integer

Returns the river movement multiplier if it is set, `nil` otherwise.


road (get/set - ephemeral)
totpp.movementMultipliers.road -> integer

Returns the road movement multiplier if it is set, `nil` otherwise.



The totpp.mod library (since 0.16)


Provided by the Custom game mods patch

Properties

premadeMap (get)
totpp.mod.premadeMap -> boolean

Returns `true` if the game was started on a pre-made map, `false` otherwise. Only valid right after starting a new game.


Documentation generated on 2022-01-31 22:37:15 UTC (TOTPP version 0.18, using civfanatics template)
 
Last edited:
Just printed this off to have a proper study. Is there any possibility of posting a small example of an event file with a few basic events so I can get my head around how it would be laid out? For example the Macro events always start @BEGINEVENTS. Does Lua have similar rules? Once I have an example to reverse engineer from I should be able to work the rest out and do some testing.

EDIT: Just seen this in Tootal's guide. Will take a look now: Examples and documentation on writing events be found in `Scifi\events.lua' and 'lua\migrating events to lua.txt', both distributed with the project. For more documentation, see the civfanatics forums.
 
TNO, one comment from my side: as far as I've seen "unit" also has a method "owner" to get the tribe number owning the unit (now that I think about it I did not test if it can also be used to set the information ...) - in case you get around to continuing this great reference, perhaps you can add it for completion?

And a more general question - would it be possible to get a generic "hex read/write" functionality? Like, for each of the object there is a method "Byte(i)" where the i'th byte after the beginning of the structure can be read (and preferbly set)? That's of course a very dangerous tool and one would have to know very well what one is doing ... but it would provide massive flexibility without you having to create additional interfaces (for example I'd love to be able to read the number of specialists in a city or the number of trade arrows etc - e.g. from Catfishs save game format I have an idea how to hex edit ist, but it would open extreme possibilities to get this information into lua events...)
 
onCanBuild

civ.scen.onCanBuild(function (defaultBuildFunction, city, item) -> boolean)

Registers a function to be called every time a check is done whether a city can build something or not. It is called for all unit types, improvements and wonders. The first parameter of the callback is the default build function, as implemented by the game. It takes the city and item as parameters. You can call this to produce a result for cases you don't need to handle yourself. `item` can be a unittype, improvement or wonder.
Return `true` if `city` is allowed to produce `item`, `false` if not.

Wait a minute - so I can build a function such that if the item is unittype.name=="Cavalry" and the city.improvements do not contain, say improvement 5(="Stables") then it returns false, else return defaultBuildFunction?
So I can couple the possibility to build certain items to arbitrary conditions?

And if one manages to create a data structure which checks if the city tile is connected by roads to a certain special resource, then one could also build that into the condition? ie the CivX (X larger then 2) special resource mechanic is possible in principle?
:eek::eek::eek:
 
Wait a minute - so I can build a function such that if the item is unittype.name=="Cavalry" and the city.improvements do not contain, say improvement 5(="Stables") then it returns false, else return defaultBuildFunction?
So I can couple the possibility to build certain items to arbitrary conditions?

Absolutely.

And if one manages to create a data structure which checks if the city tile is connected by roads to a certain special resource, then one could also build that into the condition? ie the CivX (X larger then 2) special resource mechanic is possible in principle?
:eek::eek::eek:

If one would be so inclined, definitely.
 
onResolveCombat

civ.scen.onResolveCombat(function (defaultResolutionFunction, attacker, defender) -> boolean)

Registers a function to be called during every combat turn. The first parameter of the callback is the default resolution function, as implemented by the game. It takes the attacker and defender as parameters. You can call this to produce a result for cases you don't need to handle yourself.
Return `true` to continue combat, `false` to stop.
Has anyone had success working with this function yet? Or perhaps, TheNamelessOne (if you have a moment), could you explain your vision behind why this was added, and how you expect it to be used?

In my testing, it seems first of all that the "attacker" and "defender" parameters are reversed -- the first unit seems to be the defending one.

But more importantly: it seems that this essentially runs after each combat round, and allows me to override the game's determination of whether or not the battle should continue into further rounds. Civ2's normal rule, of course, is that the battle should continue until one unit has 0 HP remaining.

If only one unit has HP remaining, and I intercept the "false" result to return "true" instead, this seems to lead to an endless loop where Civ2 hangs or crashes, and I have to kill the process.

If both units have HP remaining, I can intercept the "true" result to return "false" instead, which does seem to stop a battle prematurely -- although so far, it seems that one unit is still always destroyed. I haven't had instances where a battle ended with both units alive and with partial HP.

I feel like this function is really close to being incredibly powerful and valuable, but unfortunately doesn't seem nearly as useful in its current form.

One thing I was hoping I could do, is intercept the normal battle logic and block even the first round of combat from taking place -- in other words, intercepting an intended attack before the game had a chance to run or apply any damage calculations. I'd like to have Lua run some other code, and then return "false" to prevent the battle from beginning at all. The in-game behavior would be as if the attacking unit had never moved -- as if it attempted to move into an invalid or impassable tile.

A second thing I was hoping I could do, is to evaluate the two units and break off a battle after a few combat rounds but before either unit was totally destroyed -- leaving both units alive, with one or both having reduced HP. I could then apply additional Lua commands causing one unit to retreat, for example (there are myriad other possibilities).

Would something like what I'm proposing be possible? I'd welcome any discussion on this topic!
 
But more importantly: it seems that this essentially runs after each combat round, and allows me to override the game's determination of whether or not the battle should continue into further rounds. Civ2's normal rule, of course, is that the battle should continue until one unit has 0 HP remaining.

I think this might run before the round of combat. In Over the Reich, we wanted to prevent bombs from killing aircraft on the ground at night (map 2). Under the correct conditions, this sets the bomb's hp to 0. If it happened after the combat round, then bombs would still sometimes do damage to the unit they are attacking. However, in my tests the defending unit always had full hp at the end of combat.

Code:
local function combatResolutionFunction(defaultResolutionFunction,defender,attacker)
    if attacker.location.z == 2 then
        local aType = attacker.type
        local dType = defender.type
        if (aType == unitAliases.TwoHundredFiftylb or aType == unitAliases.FiveHundredlb
            or aType == unitAliases.Thousandlb) and not(dType == unitAliases.SpecialTarget
            or dType == unitAliases.Urban1 or dType == unitAliases.Urban2
            or dType == unitAliases.Urban3) then
            attacker.damage = attacker.type.hitpoints
            return false
        end
    end
    return defaultResolutionFunction(attacker,defender)
end

civ.scen.onResolveCombat(combatResolutionFunction)

It looks like we could pretty easily have any combat calculation we like as long as a unit dies at the end. Perform the calculation, set the damage to the attacker and defender, and return false. The unit with 0 hp dies, and the combat is complete.
 
I think this might run before the round of combat. In Over the Reich, we wanted to prevent bombs from killing aircraft on the ground at night (map 2). Under the correct conditions, this sets the bomb's hp to 0. If it happened after the combat round, then bombs would still sometimes do damage to the unit they are attacking. However, in my tests the defending unit always had full hp at the end of combat.
Thanks for this update. It's been awhile, so I don't remember all of the ways in which I tested this, but I recall that at one point I simply set onResolveCombat() to do nothing except return false (meaning, don't continue the battle into another round), without calling defaultResolutionFunction() at all. Yet one unit still took damage and died while the other retained all its HP. I took that to mean that the game was running the first round of battle before I was able to intercept and block it, and the unit which lost that first round was the one which was destroyed. But it's entirely possible that I reached an incorrect conclusion, or that I didn't set up enough different tests to really understand what was happening. In my defense :) I'll just say that my main goal at the time wasn't really to rewrite the game's battle logic, but simply to see if I could get around the rule that "one unit has to die".

It looks like we could pretty easily have any combat calculation we like as long as a unit dies at the end. Perform the calculation, set the damage to the attacker and defender, and return false. The unit with 0 hp dies, and the combat is complete.
Feel free to correct me if I'm mistaken here: I think that the way the game normally works, onResolveCombat() (or perhaps I should just say, the defaultResolutionFunction()since you don't need to use onResolveCombat() at all) is called separately for each round of a battle, and a single round results in one of the two units losing X HP, where X is equal to the FP of the other (winning) unit. The battle then continues into another round unless the losing unit has 0 HP remaining. In terms of probability, this multi-round battle system makes it much harder for a weaker unit to defeat a stronger unit. I've read that the Civ 2 developers implemented this system in order to improve on the way Civ 1 worked, where an ancient unit like a phalanx would sometimes defeat a modern tank. I'm only pointing this out because it sounds like you're proposing an approach which condenses the battle to only a single round, at least as far as the Civ 2 engine would know.

I agree, though, that what you're proposing certainly seems possible -- and extensive efforts here could revolutionize battle within Civ 2 as we know it (some examples that have crossed my mind: custom bonuses or win probabilities depending on the specific matchup of unit types; new impacts for terrain types and/or improvements such as fortresses; revised or more nuanced effects for things like city walls and SAM batteries; revised impact of veteran status, or perhaps even another "tier" of veterancy such as "elite"; etc.). My only caution would be that in order to avoid falling back into the Civ 1 trap, it might be wise if "any combat calculation we like" still included multiple rounds of calculation internally, which would be aggregated into a single result. A loop within the code of onResolveCombat() could accomplish this easily enough.

In the project I'm currently working on, I decided I could live with the results provided by defaultResolutionFunction(), so I set aside research and experimentation on this topic for the time being. But I'll certainly watch with interest to see what you're able to do here... I do think there's a lot of potential. My previous comment to TNO ("I feel like this function is really close to being incredibly powerful and valuable, but unfortunately doesn't seem nearly as useful in its current form.") was probably far too negative. :)
 
Last edited:
researching (get/set)
tribe.researching -> tech

Returns the tech the tribe is currently researching.

I'm getting crash to desktop behaviour when trying to get tribe.researching for a tribe not currently researching anything. (at least from the console) Can anyone confirm this behaviour? Does anyone have an idea of how to find out if the tribe currently isn't researching anything through some other code?
 
I'm getting crash to desktop behaviour when trying to get tribe.researching for a tribe not currently researching anything. (at least from the console) Can anyone confirm this behaviour?
I confirmed crash to desktop if I try to print(tribe.researching) from the console, when they aren't researching anything. But this didn't crash:
if tribe.researching == nil then print("It was nil") else print("It was something else") end
What printed was "It was something else". So it seems that referencing the field isn't what causes the crash, it's apparently trying to print it (or convert it to a string?).

Does anyone have an idea of how to find out if the tribe currently isn't researching anything through some other code?
It's certainly a pain to go this route, but it worked for me:
Code:
local researchingSomething = false
for i = 0, 99 do
    if tribe.researching == civ.getTech(i) then
        researchingSomething = true
        break
    end
end
if researchingSomething == true then
    print(tribe.researching)
else
    print("Not researching anything")
end
This correctly prints "Not researching anything" when that's the case (no crash).
 
Last edited:
When looking for some information a little while ago, I noticed a reference to civ.scen.params.

techParadigm (get/set)
civ.cosmic.techParadigm -> integer

Returns the tech paradigm. Scenarios use civ.scen.params.techParadigm instead of this value. Ephemeral.

By looking into the TOTPP.dll file, I have found the following values. Unfortunately, for some reason, starting year can't be set, which is unfortunate, since starting year and yearIncrement together would allow some turns to be different lengths from other turns.

civ.scen.params.techParadigm

civ.scen.params.decisiveDefeat

civ.scen.params.marginalDefeat

civ.scen.params.marginalVictory

civ.scen.params.decisiveVictory

civ.scen.params.objectivesProtagonist

civ.scen.params.maxTurns

civ.scen.params.startingYear

Can only get, can't set.

civ.scen.params.yearIncrement

I opened totpp.dll in a text editor, and deleted more or less everything that wasn't text. I would expect that any 'fundamental' totpp key would be in here as text somewhere. A text string would usually only appear once, so if the same key is used in multiple instances, it may only appear once in the file. For example, techParadigm doesn't appear with the rest of these keys, but instead near stuff like sizeSewer.

Turns out there are at least two more keys for units:

unit.stackPrev

unit.stackNext

These get other units in a stack. These might be useful if you want something to happen once in a unit stack...

Perhaps there are other undocumented features to find, if you want to look. I've attached the text I was able to extract.
 

Attachments

  • totpptext.txt
    27.2 KB · Views: 100
Nice... I definitely plan to look through that text and see what else I can uncover.

I know civ.scen.params.name is another valid field, and also civ.scen.params.flags. I believe the values found in the flags field are documented in the TOTPP launcher under the "Custom game mods" patch, and they correspond pretty closely to the options available in the menu under "Scenario Parameters" -> "Edit Special Rules". I'm not sure if these fields are writeable or not, I haven't tested that.
 
Last edited:
I found a few new things from going over your text file attachment:

civ.foundCity() -- not sure how this is different from civ.createCity()
civ.getCurrentMap()

civ.game.gameType
civ.game.globalWarming
civ.game.globalWarmingCycle
civ.game.pollution
civ.game.pollutionNearCities

spaceship.fusionPowered
spaceship.landed

I also found these references, but I don't know how to make use of them:
civ.triberel
civ.tribegov
civ.govtitle
 
I was looking into the issue of corruption, and realized that the fields/values provided in the city object aren't ideal.

city.totalTrade is actually the net trade produced by the city, after arrows lost to corruption are subtracted. :sad:

There doesn't seem to be any field that provides the true total trade generated by the city, or -- for that matter -- the amount of corruption experienced.

city.totalTrade is made up of city.baseTrade (arrows generated from worked tiles) plus the value of arrows from trade routes. But it turns out that this is also affected by corruption. I haven't worked on the formula, but some of the corruption seems to be taken from the "baseTrade" portion, and some from the "trade routes" portion. So city.baseTrade is also the "net trade" generated by the worked tiles, not the actual quantity they generate.

Based on the corruption formula I found at https://apolyton.net/forum/miscellaneous/archives/civ2-strategy-archive/62524-corruption-and-waste, I worked on a way to reverse-engineer the amount of corruption based on the net trade value that we have. "What would the total trade need to be, in order for the corruption it generates to leave this amount of net trade?" This approach can get close, but it won't hit the target every time. Based on the way the formula works, if a city has 4 net trade, there are situations where it's possible for this to result from 8 with 4 corruption, or 9 with 5 corruption, or 10 with 6 corruption. I can't tell which one of those is actually the case. Even in larger cities with more trade and multiple trade routes, it's possible for 37 net trade to result from 41 with 4 corruption or 42 with 5 corruption.

The same problem likely exists with waste (I expect that city.totalShield is the net value after waste is subtracted) but I haven't confirmed or tested this yet.
 
I just noticed the edits to the function reference, and I hope they mean what I think they mean!
 
Top Bottom