<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://modiki.civfanatics.com/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=DonQuich</id>
	<title>Civilization Modding Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://modiki.civfanatics.com/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=DonQuich"/>
	<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php/Special:Contributions/DonQuich"/>
	<updated>2026-05-01T11:17:04Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.43.1</generator>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Template:Civ5_API_Beta_Banner&amp;diff=14158</id>
		<title>Template:Civ5 API Beta Banner</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Template:Civ5_API_Beta_Banner&amp;diff=14158"/>
		<updated>2012-12-25T18:58:36Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;noinclude&amp;gt;Now obsolete, we&#039;re no longer in beta version.&amp;lt;/noinclude&amp;gt;&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Template:Civ5_API_Beta_Banner&amp;diff=14157</id>
		<title>Template:Civ5 API Beta Banner</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Template:Civ5_API_Beta_Banner&amp;diff=14157"/>
		<updated>2012-12-25T18:58:05Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: Beta period is over. See http://forums.civfanatics.com/showthread.php?p=12096993#post12096993&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;noinclude&amp;gt;&lt;br /&gt;
==Demonstration==&lt;br /&gt;
{|&lt;br /&gt;
|-&lt;br /&gt;
!Code&lt;br /&gt;
!Result&lt;br /&gt;
|-&lt;br /&gt;
|&amp;lt;pre style=&amp;quot;border:none; margin:0px; padding:0px;&amp;quot;&amp;gt;{{Civ5 API Beta Banner}}&amp;lt;/pre&amp;gt;&lt;br /&gt;
|{{Civ5 API Beta Banner}}&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Usage==&lt;br /&gt;
&amp;lt;pre&amp;gt;{{Civ5 API Beta Banner}}&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API Templates]]&amp;lt;/noinclude&amp;gt;&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Template:Civ5_API_Beta_Banner&amp;diff=14092</id>
		<title>Template:Civ5 API Beta Banner</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Template:Civ5_API_Beta_Banner&amp;diff=14092"/>
		<updated>2012-10-14T23:51:44Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;includeonly&amp;gt;&amp;lt;div style=&amp;quot;background-color: #FAEBD7; border: 2px solid #FF8C00; clear:both;&amp;quot;&amp;gt;&lt;br /&gt;
{| width=&amp;quot;100%&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot; |&amp;lt;div style=&amp;quot;width:64px; text-align:center&amp;quot;&amp;gt;[[Image:lock-128.png|64px]]&amp;lt;/div&amp;gt;&lt;br /&gt;
|&amp;lt;div style=&amp;quot;font-size:110%; font-weight:bold; align:center; width:100%; text-align:center;&amp;quot;&amp;gt;&lt;br /&gt;
Beta version. Do not edit this page, all modifications will be lost at the end of the beta period!&lt;br /&gt;
&amp;lt;/div&amp;gt;&amp;lt;div style=&amp;quot;align:center; width:100%; text-align:center;&amp;quot;&amp;gt;This page was automatically generated by the Civ5 API Bot (see the [[Civ5 API Reference FAQ]]). This bot is currently in beta version until &#039;&#039;&#039;October 31&#039;&#039;&#039; and all pages will be regenerated at this date. &amp;lt;br/&amp;gt;You can join us to provide feedback and report bugs on [http://forums.civfanatics.com/showthread.php?p=11843283 the bot&#039;s thread] at CivFanatics.&amp;lt;/div&amp;gt;&lt;br /&gt;
|}&amp;lt;/div&amp;gt;&amp;lt;/includeonly&amp;gt;&amp;lt;noinclude&amp;gt;&lt;br /&gt;
==Demonstration==&lt;br /&gt;
{|&lt;br /&gt;
|-&lt;br /&gt;
!Code&lt;br /&gt;
!Result&lt;br /&gt;
|-&lt;br /&gt;
|&amp;lt;pre style=&amp;quot;border:none; margin:0px; padding:0px;&amp;quot;&amp;gt;{{Civ5 API Beta Banner}}&amp;lt;/pre&amp;gt;&lt;br /&gt;
|{{Civ5 API Beta Banner}}&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Usage==&lt;br /&gt;
&amp;lt;pre&amp;gt;{{Civ5 API Beta Banner}}&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API Templates]]&amp;lt;/noinclude&amp;gt;&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Civ5_Modding_Tutorials&amp;diff=14084</id>
		<title>Civ5 Modding Tutorials</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Civ5_Modding_Tutorials&amp;diff=14084"/>
		<updated>2012-10-01T19:55:12Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Getting started =&lt;br /&gt;
&#039;&#039;&#039;Get a tour.&#039;&#039;&#039; &lt;br /&gt;
:If you have no idea about modding and what are Lua and Xml, you should give a look at [http://www.weplayciv.com/forums/entry.php?15-Dale-s-Mod-Blog-Civ5-Modding-Explained Civ5 Modding Explained].&lt;br /&gt;
&#039;&#039;&#039;Read the guide.&#039;&#039;&#039; &lt;br /&gt;
:The best introduction to civ5 modding is still the &#039;&#039;&#039;[http://forums.civfanatics.com/showthread.php?t=385009 Kael&#039;s Guide]&#039;&#039;&#039;. However it was written a long time ago and some informations are obsolete or missing. &lt;br /&gt;
&#039;&#039;&#039;Import your files into VFS.&#039;&#039;&#039; &lt;br /&gt;
:The main change since Kael wrote his guide is about the [[VFS (Civ5)|VFS]] (Virtual File System). Forgetting to import files into the VFS is the common source of problems for beginners. &lt;br /&gt;
&#039;&#039;&#039;Get the right tools for the job.&#039;&#039;&#039; &lt;br /&gt;
:See [[Civ5 Useful Programs]]. You should have installed the SDK of course, but it is also strongly recommended that you get a tool to search in all civ5 files at once, to compensate for the lack of documentation. You may also need additional softwares to extract and read the textures, test and debug your mod, etc.&lt;br /&gt;
&#039;&#039;&#039;Modify your ini files.&#039;&#039;&#039;&lt;br /&gt;
:See [[Debugging (Civ5)#Configuration|Debugging#Configuration]].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Tutorials =&lt;br /&gt;
See also the [http://forums.civfanatics.com/forumdisplay.php?f=394&amp;amp;order=desc&amp;amp;page=2 Modding tutorials section] on the forums.&amp;lt;br/&amp;gt;&lt;br /&gt;
Also note that the [[Civ5 XML Reference|XML]] and [[Lua and UI Reference|Lua]] sections each contain specific tutorials, articles and extensive documentation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== General ===&lt;br /&gt;
* [[Modding Limits and Issues (Civ5)|Modding Limits and Issues]]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=459392 Create and use DDS textures]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=449431 Adding custom data and using them in Lua]&lt;br /&gt;
* [http://wiki.2kgames.com/civ5/index.php/Mods:LocalizationSyntax Localization Syntax]&lt;br /&gt;
* [[Debugging (Civ5)|Debugging]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Common tasks ===&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=391823 New Leaders (2D images)]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=389782 New Resources]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=474309 New Resources (with 3D textures)]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=470290 New Buildings]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=406877 New Specialists]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=392985 New Units]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Specific topics ===&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=394056 Converting civ4 units for civ5: 1. importing the mesh and creating the unit]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=396911 Converting civ4 units for civ5: 2. using civ5 animations]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=444883 Importing civ5 units into Blender]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=405148 Civilization-specific techs]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=468374 Culture buildings - vanilla and G&amp;amp;K cross compatibility]&lt;br /&gt;
* [[Text icons and markups (Civ5)|Text icons and markups]]&lt;br /&gt;
* [[VFS (Civ5)|VFS]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14079</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14079"/>
		<updated>2012-09-30T14:13:16Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= About Lua =&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Syntax cheatsheet=&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Basics =&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are all the possible results:&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Value_type value types].&lt;br /&gt;
** &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
** &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
** &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Reference_type reference types]&lt;br /&gt;
** &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
** &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned and immutable (see [#String Interning]).&lt;br /&gt;
** &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and are often read-only. &lt;br /&gt;
** &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
** &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: Many objects in the Civ5 API are actually regular tables which either have userdata methods as members, or a userdata metatable index.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
* The Civ5 API may or may not implicitly convert the values you pass to its methods and functions. Considers it does not.&lt;br /&gt;
* Aside of those, no implicit conversion is ever performed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is far stricter than most dynamic languages for example and somehow stricter than C.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal (false is typically defined as a number).&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal (nil is typically defined as a number).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Numbers and booleans are compared by value. Everything else by reference. Strings are interned.&#039;&#039;&#039;&lt;br /&gt;
* Numbers and booleans are compared by value.&lt;br /&gt;
* Tables, userdata, functions and threads are compared by reference.&lt;br /&gt;
* Strings are interned (see [#String Interning]), which means that two identical strings are always the same reference. So comparisons are made by reference but are equivalent to by-value comparisons.&lt;br /&gt;
* All nil values are always equal.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local a = 5&lt;br /&gt;
assert(a == 5)    &lt;br /&gt;
-- true, comparison by value&lt;br /&gt;
&lt;br /&gt;
local a = {}&lt;br /&gt;
assert(a == {})   &lt;br /&gt;
-- false, comparison by reference: those two tables are distinct objects.&lt;br /&gt;
&lt;br /&gt;
local a = &amp;quot;Hello &amp;quot;..&amp;quot;world&amp;quot;&lt;br /&gt;
assert(a == &amp;quot;Hello world&amp;quot;)&lt;br /&gt;
-- true, both strings are the same reference thanks to string interning.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== String interning ===&lt;br /&gt;
&#039;&#039;&#039;All strings are interned in Lua, without any exception.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
[http://en.wikipedia.org/wiki/String_interning String interning] is a process through which all identical strings ends up being the same reference to a unique string instance. Typically, the interpreter maintains a string dictionary in the memory and whenever a string needs to be built (from a literal, from a concatenation, from a native call, etc), it first searches in this dictionary whether there is already a reference for this sequence of characters and uses it when it exists. This process usually reduces memory consumptions and speeds up equality comparisons, but it makes other operations slower because of the lookup cost. Some platforms such as Dotnet or Java automatically interns literals only. Lua, on the other hand, systematically interns every string.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Method calls: dot versus colon ===&lt;br /&gt;
&#039;&#039;&#039;The colon (&amp;lt;code&amp;gt;:&amp;lt;/code&amp;gt;) operator implicitly passes the caller as the first argument.&#039;&#039;&#039; &amp;lt;br/&amp;gt;&lt;br /&gt;
As opposed to the dot (&amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt;) operator that performs a regular call without implicitly passing anything. The colon operator behavior is obviously designed for instance methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local myTable = { msg = &amp;quot;Hello world&amp;quot; }&lt;br /&gt;
myTable.Print = function(self) print(self.msg)&lt;br /&gt;
&lt;br /&gt;
-- Three different ways to call this method&lt;br /&gt;
myTable:Print() &lt;br /&gt;
myTable.Print(myTable)&lt;br /&gt;
&lt;br /&gt;
local func = myTable.Print&lt;br /&gt;
func(myTable)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: in the civ5 API you will often encounter static methods that do not take any argument but that are called through a dot. This results from a misunderstanding of Lua from one of the Firaxis developers. While this work when the method does not take any argument (the one provided by the colon operator will be ignored), this is slower and can be considered as an error without any consequence.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was created with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Indices start at 1 ===&lt;br /&gt;
&#039;&#039;&#039;All indices in the API, not just for arrays, start at 1.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
When you declare an array with implicit keys, when you use ipairs, when you retrieve the n-th character of a string, when you query the n-th call informations in the stack call, etcetera. This is a consistent pattern in Lua.&lt;br /&gt;
&lt;br /&gt;
{{Warning}} The Civ5 API, however, uses 0-based indices, as it is the standard in C and most programming languages.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Local variables visibility ===&lt;br /&gt;
&#039;&#039;&#039;Local variables are only visible after the point where they have been declared.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is different from global variables that are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)    -- Will NOT see someLocal.&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)   -- Will see someGlobal.&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;         -- The &amp;quot;foo&amp;quot; value will never be used.&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)    -- Will see someLocal.&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)   -- Will see someGlobal.&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Files structure ===&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* If you&#039;re not familiar with scripting languages, consider that whenever Lua reads a file, it executes it. Practically, a Lua chunk (the root scope of a file) is no different from any other scope. It can contains ordinary statements as the ones found in a function scope, and you can use the &amp;lt;code&amp;gt;include&amp;lt;/code&amp;gt; statement from any scope (although the globals defined in this included file will still be globals and won&#039;t be contained in the current scope). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Semi-advanced topics =&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Advanced topics=&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the running coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14078</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14078"/>
		<updated>2012-09-30T14:10:51Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= About Lua =&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Syntax cheatsheet=&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Basics =&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Value_type value types].&lt;br /&gt;
** &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
** &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
** &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Reference_type reference types]&lt;br /&gt;
** &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
** &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned and immutable (see [#String Interning]).&lt;br /&gt;
** &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and are often read-only. &lt;br /&gt;
** &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
** &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: Many objects in the Civ5 API are actually regular tables which either have userdata methods as members, or a userdata metatable index.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is far stricter than most dynamic languages for example and somehow stricter than C.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal (false is typically defined as a number).&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal (nil is typically defined as a number).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Numbers and booleans are compared by value. Everything else by reference. Strings are interned.&#039;&#039;&#039;&lt;br /&gt;
* Numbers and booleans are compared by value.&lt;br /&gt;
* Tables, userdata, functions and threads are compared by reference.&lt;br /&gt;
* Strings are interned (see [#String Interning]), which means that two identical strings are always the same reference. So comparisons are made by reference but are equivalent to by-value comparisons.&lt;br /&gt;
* All nil values are always equal.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local a = 5&lt;br /&gt;
assert(a == 5)    &lt;br /&gt;
-- true, comparison by value&lt;br /&gt;
&lt;br /&gt;
local a = {}&lt;br /&gt;
assert(a == {})   &lt;br /&gt;
-- false, comparison by reference: those two tables are distinct objects.&lt;br /&gt;
&lt;br /&gt;
local a = &amp;quot;Hello &amp;quot;..&amp;quot;world&amp;quot;&lt;br /&gt;
assert(a == &amp;quot;Hello world&amp;quot;)&lt;br /&gt;
-- true, both strings are the same reference thanks to string interning.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== String interning ===&lt;br /&gt;
&#039;&#039;&#039;All strings are interned in Lua, without any exception.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
[http://en.wikipedia.org/wiki/String_interning String interning] is a process through which all identical strings ends up being the same reference to a unique string instance. Typically, the interpreter maintains a string dictionary in the memory and whenever a string needs to be built (from a literal, from a concatenation, from a native call, etc), it first searches in this dictionary whether there is already a reference for this sequence of characters and uses it when it exists. This process usually reduces memory consumptions and speeds up equality comparisons, but it makes other operations slower because of the lookup cost. Some platforms such as Dotnet or Java automatically interns literals only. Lua, on the other hand, systematically interns every string.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Method calls: dot versus colon ===&lt;br /&gt;
&#039;&#039;&#039;The colon (&amp;lt;code&amp;gt;:&amp;lt;/code&amp;gt;) operator implicitly passes the caller as the first argument.&#039;&#039;&#039; &amp;lt;br/&amp;gt;&lt;br /&gt;
As opposed to the dot (&amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt;) operator that performs a regular call without implicitly passing anything. The colon operator behavior is obviously designed for instance methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local myTable = { msg = &amp;quot;Hello world&amp;quot; }&lt;br /&gt;
myTable.Print = function(self) print(self.msg)&lt;br /&gt;
&lt;br /&gt;
-- Three different ways to call this method&lt;br /&gt;
myTable:Print() &lt;br /&gt;
myTable.Print(myTable)&lt;br /&gt;
&lt;br /&gt;
local func = myTable.Print&lt;br /&gt;
func(myTable)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: in the civ5 API you will often encounter static methods that do not take any argument but that are called through a dot. This results from a misunderstanding of Lua from one of the Firaxis developers. While this work when the method does not take any argument (the one provided by the colon operator will be ignored), this is slower and can be considered as an error without any consequence.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was created with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Indices start at 1 ===&lt;br /&gt;
&#039;&#039;&#039;All indices in the API, not just for arrays, start at 1.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
When you declare an array with implicit keys, when you use ipairs, when you retrieve the n-th character of a string, when you query the n-th call informations in the stack call, etcetera. This is a consistent pattern in Lua.&lt;br /&gt;
&lt;br /&gt;
{{Warning}} The Civ5 API, however, uses 0-based indices, as it is the standard in C and most programming languages.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Local variables visibility ===&lt;br /&gt;
&#039;&#039;&#039;Local variables are only visible after the point where they have been declared.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is different from global variables that are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)    -- Will NOT see someLocal.&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)   -- Will see someGlobal.&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;         -- The &amp;quot;foo&amp;quot; value will never be used.&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)    -- Will see someLocal.&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)   -- Will see someGlobal.&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Files structure ===&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* If you&#039;re not familiar with scripting languages, consider that whenever Lua reads a file, it executes it. Practically, a Lua chunk (the root scope of a file) is no different from any other scope. It can contains ordinary statements as the ones found in a function scope, and you can use the &amp;lt;code&amp;gt;include&amp;lt;/code&amp;gt; statement from any scope (although the globals defined in this included file will still be globals and won&#039;t be contained in the current scope). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Semi-advanced topics =&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Advanced topics=&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the running coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14077</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14077"/>
		<updated>2012-09-30T14:09:23Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= About Lua =&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Syntax cheatsheet=&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Basics =&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Value_type value types].&lt;br /&gt;
** &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
** &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
** &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Reference_type reference types]&lt;br /&gt;
** &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
** &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned and immutable (see [#String Interning]).&lt;br /&gt;
** &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and are often read-only. &lt;br /&gt;
** &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
** &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: Many objects in the Civ5 API are actually regular tables which either have userdata methods as members, or a userdata metatable index.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is far stricter than most dynamic languages for example and somehow stricter than C.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal (false is typically defined as a number).&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal (nil is typically defined as a number).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Numbers and booleans are compared by value. Everything else by reference. Strings are interned.&#039;&#039;&#039;&lt;br /&gt;
* Numbers and booleans are compared by value.&lt;br /&gt;
* Tables, userdata, functions and threads are compared by reference.&lt;br /&gt;
* Strings are interned (see [#String Interning]), which means that two identical strings are always the same reference. So comparisons are made by reference but are equivalent to by-value comparisons.&lt;br /&gt;
* All nil values are always equal.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local a = 5&lt;br /&gt;
assert(a == 5)    &lt;br /&gt;
-- true, comparison by value&lt;br /&gt;
&lt;br /&gt;
local a = {}&lt;br /&gt;
assert(a == {})   &lt;br /&gt;
-- false, comparison by reference: those two tables are distinct objects.&lt;br /&gt;
&lt;br /&gt;
local a = &amp;quot;Hello &amp;quot;..&amp;quot;world&amp;quot;&lt;br /&gt;
assert(a == &amp;quot;Hello world&amp;quot;)&lt;br /&gt;
-- true, both strings are the same reference thanks to string interning.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== String interning ===&lt;br /&gt;
&#039;&#039;&#039;All strings are interned in Lua, without any exception.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
[http://en.wikipedia.org/wiki/String_interning String interning] is a process through which all identical strings ends up being the same reference to a unique string instance. Typically, the interpreter maintains a string dictionary in the memory and whenever a string needs to be built (from a literal, from a concatenation, from a native call, etc), it first searches in this dictionary whether there is already a reference for this sequence of characters and uses it when it exists. This process usually reduces memory consumptions and speeds up equality comparisons, but it makes other operations slower because of the lookup cost. Some platforms such as Dotnet or Java automatically interns literals only. Lua, on the other hand, systematically interns every string.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Method calls: dot versus colon ===&lt;br /&gt;
&#039;&#039;&#039;The colon (&amp;lt;code&amp;gt;:&amp;lt;/code&amp;gt;) operator implicitly passes the caller as the first argument.&#039;&#039;&#039; &amp;lt;br/&amp;gt;&lt;br /&gt;
As opposed to the dot (&amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt;) operator that performs a regular call without implicitly passing anything. The colon operator behavior is obviously designed for instance methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local myTable = { msg = &amp;quot;Hello world&amp;quot; }&lt;br /&gt;
myTable.Print = function(self) print(self.msg)&lt;br /&gt;
&lt;br /&gt;
-- Three different ways to call this method&lt;br /&gt;
myTable:Print() &lt;br /&gt;
myTable.Print(myTable)&lt;br /&gt;
&lt;br /&gt;
local func = myTable.Print&lt;br /&gt;
func(myTable)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: in the civ5 API you will often encounter static methods that do not take any argument but that are called through a dot. This results from a misunderstanding of Lua from one of the Firaxis developers. While this work when the method does not take any argument (the one provided by the colon operator will be ignored), this is slower and can be considered as an error without any consequence.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was created with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Indices start at 1 ===&lt;br /&gt;
&#039;&#039;&#039;All indices in the API, not just for arrays, start at 1.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
When you declare an array with implicit keys, when you use ipairs, when you retrieve the n-th character of a string, when you query the n-th call informations in the stack call, etcetera. This is a consistent pattern in Lua.&lt;br /&gt;
&lt;br /&gt;
{{Warning}} The Civ5 API, however, uses 0-based indices, as it is the standard in C and most programming languages.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals declaration order does matter ===&lt;br /&gt;
&#039;&#039;&#039;Local variables are only visible after the point where they have been declared.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is different from global variables that are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)    -- Will NOT see someLocal.&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)   -- Will see someGlobal.&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;         -- The &amp;quot;foo&amp;quot; value will never be used.&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)    -- Will see someLocal.&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)   -- Will see someGlobal.&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Files structure ===&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* If you&#039;re not familiar with scripting languages, consider that whenever Lua reads a file, it executes it. Practically, a Lua chunk (the root scope of a file) is no different from any other scope. It can contains ordinary statements as the ones found in a function scope, and you can use the &amp;lt;code&amp;gt;include&amp;lt;/code&amp;gt; statement from any scope (although the globals defined in this included file will still be globals and won&#039;t be contained in the current scope). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Semi-advanced topics =&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Advanced topics=&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the running coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14076</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14076"/>
		<updated>2012-09-30T14:09:06Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= About Lua =&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Syntax cheatsheet=&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Basics =&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Value_type value types].&lt;br /&gt;
** &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
** &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
** &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Reference_type reference types]&lt;br /&gt;
** &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
** &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned and immutable (see [#String Interning]).&lt;br /&gt;
** &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and are often read-only. &lt;br /&gt;
** &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
** &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: Many objects in the Civ5 API are actually regular tables which either have userdata methods as members, or a userdata metatable index.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is far stricter than most dynamic languages for example and somehow stricter than C.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal (false is typically defined as a number).&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal (nil is typically defined as a number).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Numbers and booleans are compared by value. Everything else by reference. Strings are interned.&#039;&#039;&#039;&lt;br /&gt;
* Numbers and booleans are compared by value.&lt;br /&gt;
* Tables, userdata, functions and threads are compared by reference.&lt;br /&gt;
* Strings are interned (see [#String Interning]), which means that two identical strings are always the same reference. So comparisons are made by reference but are equivalent to by-value comparisons.&lt;br /&gt;
* All nil values are always equal.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local a = 5&lt;br /&gt;
assert(a == 5)    &lt;br /&gt;
-- true, comparison by value&lt;br /&gt;
&lt;br /&gt;
local a = {}&lt;br /&gt;
assert(a == {})   &lt;br /&gt;
-- false, comparison by reference: those two tables are distinct objects.&lt;br /&gt;
&lt;br /&gt;
local a = &amp;quot;Hello &amp;quot;..&amp;quot;world&amp;quot;&lt;br /&gt;
assert(a == &amp;quot;Hello world&amp;quot;)&lt;br /&gt;
-- true, both strings are the same reference thanks to string interning.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== String interning ===&lt;br /&gt;
&#039;&#039;&#039;All strings are interned in Lua, without any exception.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
[http://en.wikipedia.org/wiki/String_interning String interning] is a process through which all identical strings ends up being the same reference to a unique string instance. Typically, the interpreter maintains a string dictionary in the memory and whenever a string needs to be built (from a literal, from a concatenation, from a native call, etc), it first searches in this dictionary whether there is already a reference for this sequence of characters and uses it when it exists. This process usually reduces memory consumptions and speeds up equality comparisons, but it makes other operations slower because of the lookup cost. Some platforms such as Dotnet or Java automatically interns literals only. Lua, on the other hand, systematically interns every string.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Method calls: dot versus colon ===&lt;br /&gt;
&#039;&#039;&#039;The colon (&amp;lt;code&amp;gt;:&amp;lt;/code&amp;gt;) operator implicitly passes the caller as the first argument.&#039;&#039;&#039; &amp;lt;br/&amp;gt;&lt;br /&gt;
As opposed to the dot (&amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt;) operator that performs a regular call without implicitly passing anything. The colon operator behavior is obviously designed for instance methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local myTable = { msg = &amp;quot;Hello world&amp;quot; }&lt;br /&gt;
myTable.Print = function(self) print(self.msg)&lt;br /&gt;
&lt;br /&gt;
-- Three different ways to call this method&lt;br /&gt;
myTable:Print() &lt;br /&gt;
myTable.Print(myTable)&lt;br /&gt;
&lt;br /&gt;
local func = myTable.Print&lt;br /&gt;
func(myTable)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: in the civ5 API you will often encounter static methods that do not take any argument but that are called through a dot. This results from a misunderstanding of Lua from one of the Firaxis developers. While this work when the method does not take any argument (the one provided by the colon operator will be ignored), this is slower and can be considered as an error without any consequence.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Indices start at 1 ===&lt;br /&gt;
&#039;&#039;&#039;All indices in the API, not just for arrays, start at 1.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
When you declare an array with implicit keys, when you use ipairs, when you retrieve the n-th character of a string, when you query the n-th call informations in the stack call, etcetera. This is a consistent pattern in Lua.&lt;br /&gt;
&lt;br /&gt;
{{Warning}} The Civ5 API, however, uses 0-based indices, as it is the standard in C and most programming languages.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals declaration order does matter ===&lt;br /&gt;
&#039;&#039;&#039;Local variables are only visible after the point where they have been declared.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is different from global variables that are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)    -- Will NOT see someLocal.&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)   -- Will see someGlobal.&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;         -- The &amp;quot;foo&amp;quot; value will never be used.&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)    -- Will see someLocal.&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)   -- Will see someGlobal.&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Files structure ===&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* If you&#039;re not familiar with scripting languages, consider that whenever Lua reads a file, it executes it. Practically, a Lua chunk (the root scope of a file) is no different from any other scope. It can contains ordinary statements as the ones found in a function scope, and you can use the &amp;lt;code&amp;gt;include&amp;lt;/code&amp;gt; statement from any scope (although the globals defined in this included file will still be globals and won&#039;t be contained in the current scope). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Semi-advanced topics =&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Advanced topics=&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the running coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14075</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14075"/>
		<updated>2012-09-30T14:06:45Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= About Lua =&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Syntax cheatsheet=&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Basics =&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Value_type value types].&lt;br /&gt;
** &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
** &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
** &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Reference_type reference types]&lt;br /&gt;
** &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
** &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned and immutable (see [#String Interning]).&lt;br /&gt;
** &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and are often read-only. &lt;br /&gt;
** &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
** &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: Many objects in the Civ5 API are actually regular tables which either have userdata methods as members, or a userdata metatable index.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is far stricter than most dynamic languages for example and somehow stricter than C.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal (false is typically defined as a number).&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal (nil is typically defined as a number).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Numbers and booleans are compared by value. Everything else by reference. Strings are interned.&#039;&#039;&#039;&lt;br /&gt;
* Numbers and booleans are compared by value.&lt;br /&gt;
* Tables, userdata, functions and threads are compared by reference.&lt;br /&gt;
* Strings are interned (see [#String Interning]), which means that two identical strings are always the same reference. So comparisons are made by reference but are equivalent to by-value comparisons.&lt;br /&gt;
* All nil values are always equal.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local a = 5&lt;br /&gt;
assert(a == 5)    &lt;br /&gt;
-- true, comparison by value&lt;br /&gt;
&lt;br /&gt;
local a = {}&lt;br /&gt;
assert(a == {})   &lt;br /&gt;
-- false, comparison by reference: those two tables are distinct objects.&lt;br /&gt;
&lt;br /&gt;
local a = &amp;quot;Hello &amp;quot;..&amp;quot;world&amp;quot;&lt;br /&gt;
assert(a == &amp;quot;Hello world&amp;quot;)&lt;br /&gt;
-- true, both strings are the same reference thanks to string interning.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== String interning ===&lt;br /&gt;
&#039;&#039;&#039;All strings are interned in Lua, without any exception.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
[http://en.wikipedia.org/wiki/String_interning String interning] is a process through which all identical strings ends up being the same reference to a unique string instance. Typically, the interpreter maintains a string dictionary in the memory and whenever a string needs to be built (from a literal, from a concatenation, from a native call, etc), it first searches in this dictionary whether there is already a reference for this sequence of characters and uses it when it exists. This process usually reduces memory consumptions and speeds up equality comparisons, but it makes other operations slower because of the lookup cost. Some platforms such as Dotnet or Java automatically interns literals only. Lua, on the other hand, systematically interns every string.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Method calls: dot versus colon ===&lt;br /&gt;
&#039;&#039;&#039;The colon (&amp;lt;code&amp;gt;:&amp;lt;/code&amp;gt;) operator implicitly passes the caller as the first argument.&#039;&#039;&#039; &amp;lt;br/&amp;gt;&lt;br /&gt;
As opposed to the dot (&amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt;) operator that performs a regular call without implicitly passing anything. The colon operator behavior is obviously designed for instance methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local myTable = { msg = &amp;quot;Hello world&amp;quot; }&lt;br /&gt;
myTable.Print = function(self) print(self.msg)&lt;br /&gt;
&lt;br /&gt;
-- Three different ways to call this method&lt;br /&gt;
myTable:Print() &lt;br /&gt;
myTable.Print(myTable)&lt;br /&gt;
&lt;br /&gt;
local func = myTable.Print&lt;br /&gt;
func(myTable)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: in the civ5 API you will often encounter static methods that do not take any argument but that are called through a dot. This results from a misunderstanding of Lua from one of the Firaxis developers. While this work when the method does not take any argument (the one provided by the colon operator will be ignored), this is slower and can be considered as an error without any consequence.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Indices start at 1 ===&lt;br /&gt;
&#039;&#039;&#039;All indices in the API, not just for arrays, start at 1.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
When you declare an array with implicit keys, when you use ipairs, when you retrieve the n-th character of a string, when you query the n-th call informations in the stack call, etcetera. This is a consistent pattern in Lua.&lt;br /&gt;
&lt;br /&gt;
{{Warning}} The Civ5 API, however, uses 0-based indices, as it is the standard in C and most programming languages.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals declaration order does matter ===&lt;br /&gt;
&#039;&#039;&#039;Local variables are only visible after the point where they have been declared.&#039;&#039;&#039;&lt;br /&gt;
This is different from global variables that are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)    -- Will NOT see someLocal&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)   -- Will see someGlobal&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)    -- Will see someLocal&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)   -- Will see someGlobal&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== File structure ===&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* If you&#039;re not familiar with scripting languages, consider that whenever Lua reads a file, it executes it. Practically, a Lua chunk (the root scope of a file) is no different from any other scope. It can contains ordinary statements as the ones found in a function scope, and you can use the &amp;lt;code&amp;gt;include&amp;lt;/code&amp;gt; statement from any scope (although the globals defined in this included file will still be globals and won&#039;t be contained in the current scope). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Semi-advanced topics =&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Advanced topics=&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the running coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14074</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14074"/>
		<updated>2012-09-30T13:48:55Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= About Lua =&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Syntax cheatsheet=&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Basics =&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Value_type value types].&lt;br /&gt;
** &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
** &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
** &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Reference_type reference types]&lt;br /&gt;
** &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
** &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned and immutable (see [#String Interning]).&lt;br /&gt;
** &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and are often read-only. &lt;br /&gt;
** &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
** &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: Many objects in the Civ5 API are actually regular tables which either have userdata methods as members, or a userdata metatable index.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is far stricter than most dynamic languages for example and somehow stricter than C.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal (false is typically defined as a number).&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal (nil is typically defined as a number).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Numbers and booleans are compared by value. Everything else by reference. Strings are interned.&#039;&#039;&#039;&lt;br /&gt;
* Numbers and booleans are compared by value.&lt;br /&gt;
* Tables, userdata, functions and threads are compared by reference.&lt;br /&gt;
* Strings are interned (see [#String Interning]), which means that two identical strings are always the same reference. So comparisons are made by reference but are equivalent to by-value comparisons.&lt;br /&gt;
* All nil values are always equal.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local a = 5&lt;br /&gt;
assert(a == 5)    &lt;br /&gt;
-- true, comparison by value&lt;br /&gt;
&lt;br /&gt;
local a = {}&lt;br /&gt;
assert(a == {})   &lt;br /&gt;
-- false, comparison by reference: those two tables are distinct objects.&lt;br /&gt;
&lt;br /&gt;
local a = &amp;quot;Hello &amp;quot;..&amp;quot;world&amp;quot;&lt;br /&gt;
assert(a == &amp;quot;Hello world&amp;quot;)&lt;br /&gt;
-- true, both strings are the same reference thanks to string interning.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== String interning ===&lt;br /&gt;
&#039;&#039;&#039;All strings are interned in Lua, without any exception.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
[http://en.wikipedia.org/wiki/String_interning String interning] is a process through which all identical strings ends up being the same reference to a unique string instance. Typically, the interpreter maintains a string dictionary in the memory and whenever a string needs to be built (from a literal, from a concatenation, from a native call, etc), it first searches in this dictionary whether there is already a reference for this sequence of characters and uses it when it exists. This process usually reduces memory consumptions and speeds up equality comparisons, but it makes other operations slower because of the lookup cost. Some platforms such as Dotnet or Java automatically interns literals only. Lua, on the other hand, systematically interns every string.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Method calls: dot versus colon ===&lt;br /&gt;
&#039;&#039;&#039;The colon (&amp;lt;code&amp;gt;:&amp;lt;/code&amp;gt;) operator implicitly passes the caller as the first argument.&#039;&#039;&#039; &amp;lt;br/&amp;gt;&lt;br /&gt;
As opposed to the dot (&amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt;) operator that performs a regular call without implicitly passing anything. The colon operator behavior is obviously designed for instance methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local myTable = { msg = &amp;quot;Hello world&amp;quot; }&lt;br /&gt;
myTable.Print = function(self) print(self.msg)&lt;br /&gt;
&lt;br /&gt;
-- Three different ways to call this method&lt;br /&gt;
myTable:Print() &lt;br /&gt;
myTable.Print(myTable)&lt;br /&gt;
&lt;br /&gt;
local func = myTable.Print&lt;br /&gt;
func(myTable)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: in the civ5 API you will often encounter static methods that do not take any argument but that are called through a dot. This results from a misunderstanding of Lua from one of the Firaxis developers. While this work when the method does not take any argument (the one provided by the colon operator will be ignored), this is slower and can be considered as an error without any consequence.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals, globals and includes ===&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* Another specificities of locals: they&#039;re only visible after the point they have been declared in the file, while globals are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Semi-advanced topics =&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Advanced topics=&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the running coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14073</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14073"/>
		<updated>2012-09-30T13:47:21Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= About Lua =&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Syntax cheatsheet=&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Basics =&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Value_type value types].&lt;br /&gt;
** &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
** &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
** &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Reference_type reference types]&lt;br /&gt;
** &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
** &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are [http://en.wikipedia.org/wiki/String_interning interned] and immutable.&lt;br /&gt;
** &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and are often read-only. &lt;br /&gt;
** &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
** &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: Many objects in the Civ5 API are actually regular tables which either have userdata methods as members, or a userdata metatable index.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is far stricter than most dynamic languages for example and somehow stricter than C.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal (false is typically defined as a number).&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal (nil is typically defined as a number).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Numbers and booleans are compared by value. Everything else by reference. Strings are interned.&#039;&#039;&#039;&lt;br /&gt;
* Numbers and booleans are compared by value.&lt;br /&gt;
* Tables, userdata, functions and threads are compared by reference.&lt;br /&gt;
* Strings are [http://en.wikipedia.org/wiki/String_interning interned], which means that two identical strings are always the same reference. So comparisons are made by reference but are equivalent to by-value comparisons.&lt;br /&gt;
* All nil values are always equal.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local a = 5&lt;br /&gt;
assert(a == 5)    &lt;br /&gt;
-- true, comparison by value&lt;br /&gt;
&lt;br /&gt;
local a = {}&lt;br /&gt;
assert(a == {})   &lt;br /&gt;
-- false, comparison by reference: those two tables are distinct objects.&lt;br /&gt;
&lt;br /&gt;
local a = &amp;quot;Hello &amp;quot;..&amp;quot;world&amp;quot;&lt;br /&gt;
assert(a == &amp;quot;Hello world&amp;quot;)&lt;br /&gt;
-- true, both strings are the same reference thanks to string interning.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== String interning ===&lt;br /&gt;
&#039;&#039;&#039;All strings are interned in Lua, without any exception.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
[http://en.wikipedia.org/wiki/String_interning String interning] is a process through which all identical strings ends up being the same reference to a unique string instance. Typically, the interpreter maintains a string dictionary in the memory and whenever a string needs to be built (from a literal, from a concatenation, from a native call, etc), it first searches in this dictionary whether there is already a reference for this sequence of characters and uses it when it exists. This process usually reduces memory consumptions and speeds up equality comparisons, but it makes other operations slower because of the lookup cost. Some platforms such as Dotnet or Java automatically interns literals only. Lua, on the other hand, systematically interns every string.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Method calls: dot versus colon ===&lt;br /&gt;
&#039;&#039;&#039;The colon (&amp;lt;code&amp;gt;:&amp;lt;/code&amp;gt;) operator implicitly passes the caller as the first argument.&#039;&#039;&#039; &amp;lt;br/&amp;gt;&lt;br /&gt;
As opposed to the dot (&amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt;) operator that performs a regular call without implicitly passing anything. The colon operator behavior is obviously designed for instance methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local myTable = { msg = &amp;quot;Hello world&amp;quot; }&lt;br /&gt;
myTable.Print = function(self) print(self.msg)&lt;br /&gt;
&lt;br /&gt;
-- Three different ways to call this method&lt;br /&gt;
myTable:Print() &lt;br /&gt;
myTable.Print(myTable)&lt;br /&gt;
&lt;br /&gt;
local func = myTable.Print&lt;br /&gt;
func(myTable)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: in the civ5 API you will often encounter static methods that do not take any argument but that are called through a dot. This results from a misunderstanding of Lua from one of the Firaxis developers. While this work when the method does not take any argument (the one provided by the colon operator will be ignored), this is slower and can be considered as an error without any consequence.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals, globals and includes ===&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* Another specificities of locals: they&#039;re only visible after the point they have been declared in the file, while globals are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Semi-advanced topics =&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Advanced topics=&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the running coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14072</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14072"/>
		<updated>2012-09-30T13:44:17Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= About Lua =&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Syntax cheatsheet=&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Basics =&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Value_type value types].&lt;br /&gt;
** &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
** &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
** &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* The following are [http://en.wikipedia.org/wiki/Reference_type reference types]&lt;br /&gt;
** &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
** &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are [http://en.wikipedia.org/wiki/String_interning interned] and immutable.&lt;br /&gt;
** &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and are often read-only. &lt;br /&gt;
** &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
** &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: Many objects in the Civ5 API are actually regular tables which either have userdata methods as members, or a userdata metatable index.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is far stricter than most dynamic languages for example and somehow stricter than C.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal (false is typically defined as a number).&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal (nil is typically defined as a number).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Numbers and booleans are compared by value. Everything else by reference. Strings are interned.&#039;&#039;&#039;&lt;br /&gt;
* Numbers and booleans are compared by value.&lt;br /&gt;
* Tables, userdata, functions and threads are compared by reference.&lt;br /&gt;
* Strings are [http://en.wikipedia.org/wiki/String_interning interned], which means that two identical strings are always the same reference. So comparison is made by reference but it is equivalent to a by-value comparison.&lt;br /&gt;
* All nil values are always equal.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local a = 5&lt;br /&gt;
assert(a == 5)    &lt;br /&gt;
-- true, comparison by value&lt;br /&gt;
&lt;br /&gt;
local a = {}&lt;br /&gt;
assert(a == {})   &lt;br /&gt;
-- false, comparison by reference: those two tables are distinct objects.&lt;br /&gt;
&lt;br /&gt;
local a = &amp;quot;Hello &amp;quot;..&amp;quot;world&amp;quot;&lt;br /&gt;
assert(a == &amp;quot;Hello world&amp;quot;)&lt;br /&gt;
-- true, both strings are the same reference thanks to string interning.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== String interning ===&lt;br /&gt;
&#039;&#039;&#039;All strings are interned in Lua, without any exception.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
[http://en.wikipedia.org/wiki/String_interning String interning] is a process through which all identical strings ends up being the same reference to a unique string instance. Typically, the interpreter maintains a string dictionary in the memory and whenever a string needs to be built (from a literal, from a concatenation, from a native call, etc), it first searches in this dictionary whether there is already a reference for this sequence of characters and uses it when it exists. This process usually reduces memory consumptions and speeds up equality comparisons, but it makes other operations slower because of the lookup cost. Some platforms such as Dotnet or Java automatically interns literals only. Lua, on the other hand, systematically interns every string.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Method calls: dot versus colon ===&lt;br /&gt;
&#039;&#039;&#039;The colon (&amp;lt;code&amp;gt;:&amp;lt;/code&amp;gt;) operator implicitly passes the caller as the first argument.&#039;&#039;&#039; &amp;lt;br/&amp;gt;&lt;br /&gt;
As opposed to the dot (&amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt;) operator that performs a regular call without implicitly passing anything. The colon operator behavior is obviously designed for instance methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local myTable = { msg = &amp;quot;Hello world&amp;quot; }&lt;br /&gt;
myTable.Print = function(self) print(self.msg)&lt;br /&gt;
&lt;br /&gt;
-- Three different ways to call this method&lt;br /&gt;
myTable:Print() &lt;br /&gt;
myTable.Print(myTable)&lt;br /&gt;
&lt;br /&gt;
local func = myTable.Print&lt;br /&gt;
func(myTable)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note: in the civ5 API you will often encounter static methods that do not take any argument but that are called through a dot. This results from a misunderstanding of Lua from one of the Firaxis developers. While this work when the method does not take any argument (the one provided by the colon operator will be ignored), this is slower and can be considered as an error without any consequence.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals, globals and includes ===&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* Another specificities of locals: they&#039;re only visible after the point they have been declared in the file, while globals are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Semi-advanced topics =&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Advanced topics=&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the running coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Civ5_Modding_Tutorials&amp;diff=14065</id>
		<title>Civ5 Modding Tutorials</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Civ5_Modding_Tutorials&amp;diff=14065"/>
		<updated>2012-09-28T20:05:18Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Getting started =&lt;br /&gt;
&#039;&#039;&#039;Get a tour.&#039;&#039;&#039; &lt;br /&gt;
:If you have no idea about modding and what are Lua and Xml, you should give a look at [http://www.weplayciv.com/forums/entry.php?15-Dale-s-Mod-Blog-Civ5-Modding-Explained Civ5 Modding Explained].&lt;br /&gt;
&#039;&#039;&#039;Read the guide.&#039;&#039;&#039; &lt;br /&gt;
:The best introduction to civ5 modding is still the &#039;&#039;&#039;[http://forums.civfanatics.com/showthread.php?t=385009 Kael&#039;s Guide]&#039;&#039;&#039;. However it was written a long time ago and some informations are obsolete or missing. &lt;br /&gt;
&#039;&#039;&#039;Import your files into VFS.&#039;&#039;&#039; &lt;br /&gt;
:The main change since Kael wrote his guide is about the [[VFS (Civ5)|VFS]] (Virtual File System). Forgetting to import files into the VFS is the common source of problems for beginners. &lt;br /&gt;
&#039;&#039;&#039;Get the right tools for the job.&#039;&#039;&#039; &lt;br /&gt;
:See [[Civ5 Useful Programs]]. You should have installed the SDK of course, but it is also strongly recommended that you get a tool to search in all civ5 files at once, to compensate for the lack of documentation. You may also need additional softwares to extract and read the textures, test and debug your mod, etc.&lt;br /&gt;
&#039;&#039;&#039;Modify your ini files.&#039;&#039;&#039;&lt;br /&gt;
:See [[Debugging (Civ5)#Configuration|Debugging#Configuration]].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Tutorials =&lt;br /&gt;
See also the [http://forums.civfanatics.com/forumdisplay.php?f=394&amp;amp;order=desc&amp;amp;page=2 Modding tutorials section] on the forums.&amp;lt;br/&amp;gt;&lt;br /&gt;
Also note that the [[Civ5 XML Reference|XML]] and [[Lua and UI Reference|Lua]] sections each contain specific tutorials, articles and extensive documentation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== General ===&lt;br /&gt;
* [[Modding Limits and Issues (Civ5)|Modding Limits and Issues]]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=459392 Create and use DDS textures]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=449431 Adding custom data and using them in Lua]&lt;br /&gt;
* [http://wiki.2kgames.com/civ5/index.php/Mods:LocalizationSyntax Localization Syntax]&lt;br /&gt;
* [[Debugging (Civ5)|Debugging]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Common tasks ===&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=391823 New Leaders (2D images)]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=389782 New Resources]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=474309 New Resources (with 3D textures)]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=470290 New Buildings]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=406877 New Specialists]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=392985 New Units]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Specific topics ===&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=394056 Importing civ4 units into civ5]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=396911 Making units that use Civ5 animations]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=405148 Locking techs on a civilization basis]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=468374 Culture buildings - vanilla and G&amp;amp;K cross compatibility]&lt;br /&gt;
* [[Text icons and markups (Civ5)|Text icons and markups]]&lt;br /&gt;
* [[VFS (Civ5)|VFS]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Modding_Limits_and_Issues_(Civ5)&amp;diff=14060</id>
		<title>Modding Limits and Issues (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Modding_Limits_and_Issues_(Civ5)&amp;diff=14060"/>
		<updated>2012-09-25T12:23:54Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
= Hard limits =&lt;br /&gt;
Limits you won&#039;t be able to circumvent.&lt;br /&gt;
* &#039;&#039;&#039;Audio&#039;&#039;&#039;&lt;br /&gt;
:A mod cannot add its own audio files&lt;br /&gt;
* &#039;&#039;&#039;3D leader scenes&#039;&#039;&#039; &lt;br /&gt;
:They use a proprietary format. Although a paper has been published that explains how the algorithm works, the details of the implementation are unknown and as of August 2012 there is not tool to read or write them.&lt;br /&gt;
* &#039;&#039;&#039;Combat mechanics&#039;&#039;&#039;&lt;br /&gt;
:Since the pre-G&amp;amp;K patch the combat is no longer moddable.&lt;br /&gt;
* &#039;&#039;&#039;AI&#039;&#039;&#039;&lt;br /&gt;
:Most of it is processed on the C++ side and the API exposes almost no hooks to replace, trigger or prevent the standard behaviors. Now the diplomacy UI may be slightly modded though bonuses, and the fact that a mod can give orders to units opens a theoritical way to override the tactical and strategical UI although the daunting amount of work required and the involved CPU cost when comparing to Lua to C++ probably just makes this an illusion.&lt;br /&gt;
* &#039;&#039;&#039;Terrain modifications&#039;&#039;&#039;&lt;br /&gt;
:When they require an update of the 3D mesh (changing the TerrainType or the PlotType, and removing a feature), this one is not dynamically updated, the game needs to be reloaded. No terraforming mod.&lt;br /&gt;
* &#039;&#039;&#039;No more than 200 promotions&#039;&#039;&#039;&lt;br /&gt;
:Any promotion after that is added to every unit in the game. The base game with all DLC and expansion have about 165 promotions, so mods are restricted to less than 35 promotions in total. &#039;&#039;&#039;Will be removed in the 2012 Fall patch.&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;No more than 22 major civilizations and 41 city states&#039;&#039;&#039;&lt;br /&gt;
:More hard-coded values.&lt;br /&gt;
* &#039;&#039;&#039;Espionage&#039;&#039;&#039;&lt;br /&gt;
:There is about no API to control it (no way to add/remove spies for example).&lt;br /&gt;
* &#039;&#039;&#039;Religious units&#039;&#039;&#039;&lt;br /&gt;
:There is no API to set a unit&#039;s religion.&lt;br /&gt;
* &#039;&#039;&#039;Civilizations without overrides&#039;&#039;&#039;&lt;br /&gt;
:A civilization that doesn&#039;t have at least two overrides (unique units/buildings) will not appear in the civilization selection screen.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Soft limits =&lt;br /&gt;
Limits that can be overcame.&lt;br /&gt;
* &#039;&#039;&#039;Some assets cannot be deleted&#039;&#039;&#039;&lt;br /&gt;
:Deleting them causes the game to crash. Try to disable them instead.&lt;br /&gt;
* &#039;&#039;&#039;No more than one leader per civilization&#039;&#039;&#039;&lt;br /&gt;
:The Lua code for the setup screen only keeps the first leader for every civilization. You would need to use a modified version of the setup screen.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Modularity problems =&lt;br /&gt;
Things that only one mod can do at the same time because it requires the full replacement of some resources. The community could theoretically issue solutions in some cases but in practice there is rarely a solution available.&lt;br /&gt;
* &#039;&#039;&#039;Units arts&#039;&#039;&#039;&lt;br /&gt;
:UnitMemberArtInfos and UnitArtInfos must be replaced altogether.&lt;br /&gt;
* &#039;&#039;&#039;UI&#039;&#039;&#039;&lt;br /&gt;
:Most of the UI mods need to replace some parts of the UI with their custom versions.&lt;br /&gt;
* &#039;&#039;&#039;Resources placement&#039;&#039;&#039;&lt;br /&gt;
:It requires the replacement of some of the AssignStartingPlots functions&lt;br /&gt;
* &#039;&#039;&#039;Natural wonders placement&#039;&#039;&#039;&lt;br /&gt;
:For the same reasons than resources.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Modding_Limits_and_Issues_(Civ5)&amp;diff=14059</id>
		<title>Modding Limits and Issues (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Modding_Limits_and_Issues_(Civ5)&amp;diff=14059"/>
		<updated>2012-09-25T12:23:41Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
= Hard limits =&lt;br /&gt;
Limits you won&#039;t be able to circumvent.&lt;br /&gt;
* &#039;&#039;&#039;Audio&#039;&#039;&#039;&lt;br /&gt;
:A mod cannot add its own audio files&lt;br /&gt;
* &#039;&#039;&#039;3D leader scenes&#039;&#039;&#039; &lt;br /&gt;
:They use a proprietary format. Although a paper has been published that explains how the algorithm works, the details of the implementation are unknown and as of August 2012 there is not tool to read or write them.&lt;br /&gt;
* &#039;&#039;&#039;Combat mechanics&#039;&#039;&#039;&lt;br /&gt;
:Since the pre-G&amp;amp;K patch the combat is no longer moddable.&lt;br /&gt;
* &#039;&#039;&#039;AI&#039;&#039;&#039;&lt;br /&gt;
:Most of it is processed on the C++ side and the API exposes almost no hooks to replace, trigger or prevent the standard behaviors. Now the diplomacy UI may be slightly modded though bonuses, and the fact that a mod can give orders to units opens a theoritical way to override the tactical and strategical UI although the daunting amount of work required and the involved CPU cost when comparing to Lua to C++ probably just makes this an illusion.&lt;br /&gt;
* &#039;&#039;&#039;Terrain modifications&#039;&#039;&#039;&lt;br /&gt;
:When they require an update of the 3D mesh (changing the TerrainType or the PlotType, and removing a feature), this one is not dynamically updated, the game needs to be reloaded. No terraforming mod.&lt;br /&gt;
* &#039;&#039;&#039;No more than 200 promotions&#039;&#039;&#039;&lt;br /&gt;
:Any promotion after that is added to every unit in the game. The base game with all DLC and expansion have about 165 promotions, so mods are restricted to less than 35 promotions in total. &#039;&#039;&#039;Will be removed in the 2012 Fall patch.&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;No more than 22 major civilizations and 41 city states&#039;&#039;&#039;&lt;br /&gt;
:More hard-coded values.&lt;br /&gt;
* &#039;&#039;&#039;Espionage&#039;&#039;&#039;&lt;br /&gt;
:There is about no API to control it (no way to add/remove spies for example).&lt;br /&gt;
* &#039;&#039;&#039;Religious units&#039;&#039;&#039;&lt;br /&gt;
:There is no API to set a unit&#039;s religion.&lt;br /&gt;
* &#039;&#039;&#039;Civilizations without overrides&#039;&#039;&#039;&lt;br /&gt;
:A civilization that doesn&#039;t have at least two overrides (unique units/buildings) will not appear in the civilization selection screen.&lt;br /&gt;
&lt;br /&gt;
= Soft limits =&lt;br /&gt;
Limits that can be overcame.&lt;br /&gt;
* &#039;&#039;&#039;Some assets cannot be deleted&#039;&#039;&#039;&lt;br /&gt;
:Deleting them causes the game to crash. Try to disable them instead.&lt;br /&gt;
* &#039;&#039;&#039;No more than one leader per civilization&#039;&#039;&#039;&lt;br /&gt;
:The Lua code for the setup screen only keeps the first leader for every civilization. You would need to use a modified version of the setup screen.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Modularity problems =&lt;br /&gt;
Things that only one mod can do at the same time because it requires the full replacement of some resources. The community could theoretically issue solutions in some cases but in practice there is rarely a solution available.&lt;br /&gt;
* &#039;&#039;&#039;Units arts&#039;&#039;&#039;&lt;br /&gt;
:UnitMemberArtInfos and UnitArtInfos must be replaced altogether.&lt;br /&gt;
* &#039;&#039;&#039;UI&#039;&#039;&#039;&lt;br /&gt;
:Most of the UI mods need to replace some parts of the UI with their custom versions.&lt;br /&gt;
* &#039;&#039;&#039;Resources placement&#039;&#039;&#039;&lt;br /&gt;
:It requires the replacement of some of the AssignStartingPlots functions&lt;br /&gt;
* &#039;&#039;&#039;Natural wonders placement&#039;&#039;&#039;&lt;br /&gt;
:For the same reasons than resources.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=VFS_(Civ5)&amp;diff=14058</id>
		<title>VFS (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=VFS_(Civ5)&amp;diff=14058"/>
		<updated>2012-09-25T12:21:49Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This article explains the Virtual File System (VFS) in Civ5. Lua developers looking for informations on the &#039;&#039;&#039;include&#039;&#039;&#039; function should look at [[Specificities of the Lua implementation in Civ5]].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= What is it? =&lt;br /&gt;
[[File:ModBuddy.ImportIntoVFS.png|frame|The &#039;&#039;import into VFS&#039;&#039; option.]] &lt;br /&gt;
VFS stands for Virtual File System. Rather than locating the files directly in the file system, Civ5 looks for them in its virtual file system. This system provides the following benefits:&lt;br /&gt;
* &#039;&#039;&#039;Modularity:&#039;&#039;&#039; each mod, expansion or DLC can provide its own version of a given file without overwriting the original one. At run-time the game sequentially loads those files into the VFS, performing virtual overwrites as needed. This contrasts with the mods hell in the Elders Scrolls series for example.&lt;br /&gt;
* &#039;&#039;&#039;Packaging:&#039;&#039;&#039; The files in the VFS can be either independent files or parts of packages (archives). The VFS behaves as a unified resource loader.&lt;br /&gt;
* &#039;&#039;&#039;Sandboxing:&#039;&#039;&#039; whenever a mod requests a file, civ5 only looks in the VFS. This prevents mods to be allowed to look at the physical file system since this could open a security breach.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Determining whether a file must be imported or not =&lt;br /&gt;
In doubt, import your files into the VFS. But you should better stick to what is written here.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Must be imported&#039;&#039;&#039; the files that are requested during the game.&lt;br /&gt;
* The XML UI files. &lt;br /&gt;
* The XML files for animations, scenes, etc.&lt;br /&gt;
* The Lua files (minus the exception detailed below).&lt;br /&gt;
* The art assets such as textures or models.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Should not be imported&#039;&#039;&#039; the files that are loaded through the project&#039;s content and actions tab (except the XML UI files, those ones should always be imported). While this is harmless most of the time, this can sometimes result in unexpected side-effects.&lt;br /&gt;
* The Lua files that are directly loaded through the project&#039;s content tab. This does not apply if the Lua file is associated with a XML file and you load this XML file instead. Note that if you want a Lua file to be included by other Lua or XML UI files, you will still have to import it into the VFS but you may see it loaded more times than necessary. &lt;br /&gt;
* The XML data and text files. Those ones are only ran at start up to modify the data tables.&lt;br /&gt;
* The SQL files. For the same reasons.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Importing a file into the VFS =&lt;br /&gt;
* In ModBuddy, select a file in the solution explorer. &lt;br /&gt;
* Hit F4 (or click View &amp;gt; Properties Window) to open its properties.&lt;br /&gt;
* At the bottom of this new window, look for &#039;&#039;&#039;Import into VFS&#039;&#039;&#039; and set it to true.&lt;br /&gt;
* If Civ5 is opened, you will need to exit to the main menu for this change to be applied.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Final warning =&lt;br /&gt;
{{Warning}} In some circumstances (notable the include statement in Lua, see [[Specificities of the Lua implementation in Civ5]]) only the first eight characters of the file matter. Tow files starting with the same first eight characters could then be confused by the game.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=VFS_(Civ5)&amp;diff=14057</id>
		<title>VFS (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=VFS_(Civ5)&amp;diff=14057"/>
		<updated>2012-09-25T12:21:21Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This article explains the Virtual File System (VFS) in Civ5. Lua developers looking for informations on the &#039;&#039;&#039;include&#039;&#039;&#039; function should look at [[Specificities of the Lua implementation in Civ5]].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= What is it? =&lt;br /&gt;
[[File:ModBuddy.ImportIntoVFS.png|frame|The &#039;&#039;import into VFS&#039;&#039; option.]] &lt;br /&gt;
VFS stands for Virtual File System. Rather than locating the files directly in the file system, Civ5 looks for them in its virtual file system. This system provides the following benefits:&lt;br /&gt;
* &#039;&#039;&#039;Modularity:&#039;&#039;&#039; each mod, expansion or DLC can provide its own version of a given file without overwriting the original one. At run-time the game sequentially loads those files into the VFS, performing virtual overwrites as needed. This contrasts with the mods hell in the Elders Scrolls series for example.&lt;br /&gt;
* &#039;&#039;&#039;Packaging:&#039;&#039;&#039; The files in the VFS can be either independent files or parts of packages (archives). The VFS behaves as a unified resource loader.&lt;br /&gt;
* &#039;&#039;&#039;Sandboxing:&#039;&#039;&#039; whenever a mod requests a file, civ5 only looks in the VFS. This prevents mods to be allowed to look at the physical file system since this could open a security breach.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Determining whether a file must be imported or not =&lt;br /&gt;
In doubt, import your files into the VFS. But you should better stick to what is written here.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Must be imported&#039;&#039;&#039; the files that are requested during the game.&lt;br /&gt;
* The XML UI files. &lt;br /&gt;
* The XML files for animations, scenes, etc.&lt;br /&gt;
* The Lua files (minus the exception detailed below).&lt;br /&gt;
* The art assets such as textures or models.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Should not be imported&#039;&#039;&#039; the files that are loaded through the project&#039;s content and actions tab (except the XML UI files, those ones should always be imported). While this is harmless most of the time, this can sometimes result in unexpected side-effects.&lt;br /&gt;
* The Lua files that are directly loaded through the project&#039;s content tab. This does not apply if the Lua file is associated with a XML file and you load this XML file instead. Note that if you want a Lua file to be included by other Lua or XML UI files, you will still have to import it into the VFS but you may see it loaded more times than necessary. &lt;br /&gt;
* The XML data and text files. Those ones are only ran at start up to modify the data tables.&lt;br /&gt;
* The SQL files. For the same reasons.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Importing a file into the VFS =&lt;br /&gt;
* In ModBuddy, select a file in the solution explorer. &lt;br /&gt;
* Hit F4 (or click View &amp;gt; Properties Window) to open its properties.&lt;br /&gt;
* At the bottom of this new window, look for &#039;&#039;&#039;Import into VFS&#039;&#039;&#039; and set it to true.&lt;br /&gt;
* If Civ5 is opened, you will need to exit to the main menu for this change to be applied.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Final warning =&lt;br /&gt;
{{Warning}} In some circumstances (notable the include statement in Lua, see [[Specificities of the Lua implementation in Civ5]], only the first eight characters of the file matter. Tow files starting with the same first eight characters could then be confused by the game.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Civ5_Modding_Tutorials&amp;diff=14056</id>
		<title>Civ5 Modding Tutorials</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Civ5_Modding_Tutorials&amp;diff=14056"/>
		<updated>2012-09-25T12:18:45Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Getting started =&lt;br /&gt;
&#039;&#039;&#039;Get a tour.&#039;&#039;&#039; &lt;br /&gt;
:If you have no idea about modding and what are Lua and Xml, you should give a look at [http://www.weplayciv.com/forums/entry.php?15-Dale-s-Mod-Blog-Civ5-Modding-Explained Civ5 Modding Explained].&lt;br /&gt;
&#039;&#039;&#039;Read the guide.&#039;&#039;&#039; &lt;br /&gt;
:The best introduction to civ5 modding is still the &#039;&#039;&#039;[http://forums.civfanatics.com/showthread.php?t=385009 Kael&#039;s Guide]&#039;&#039;&#039;. However it was written a long time ago and some informations are obsolete or missing. &lt;br /&gt;
&#039;&#039;&#039;Import your files into VFS.&#039;&#039;&#039; &lt;br /&gt;
:The main change since Kael wrote his guide is about the [[VFS (Civ5)|VFS]] (Virtual File System). Forgetting to import files into the VFS is the common source of problems for beginners. &lt;br /&gt;
&#039;&#039;&#039;Get the right tools for the job.&#039;&#039;&#039; &lt;br /&gt;
:See [[Civ5 Useful Programs]]. You should have installed the SDK of course, but it is also strongly recommended that you get a tool to search in all civ5 files at once, to compensate for the lack of documentation. You may also need additional softwares to extract and read the textures, test and debug your mod, etc.&lt;br /&gt;
&#039;&#039;&#039;Modify your ini files.&#039;&#039;&#039;&lt;br /&gt;
:See [[Debugging (Civ5)#Configuration|Debugging#Configuration]].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Tutorials =&lt;br /&gt;
See also the [http://forums.civfanatics.com/forumdisplay.php?f=394&amp;amp;order=desc&amp;amp;page=2 Modding tutorials section] on the forums.&amp;lt;br/&amp;gt;&lt;br /&gt;
Also note that the [[Civ5 XML Reference|XML]] and [[Lua and UI Reference|Lua]] sections each contain specific tutorials, articles and extensive documentation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== General ===&lt;br /&gt;
* [[Modding Limits and Issues (Civ5)|Modding Limits and Issues]]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=459392 Create and use DDS textures]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=449431 Adding custom data and using them in Lua]&lt;br /&gt;
* [http://wiki.2kgames.com/civ5/index.php/Mods:LocalizationSyntax Localization Syntax]&lt;br /&gt;
* [[Debugging (Civ5)|Debugging]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Common tasks ===&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=391823 New Leaders (2D images)]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=389782 New Resources]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=470290 New Buildings]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=406877 New Specialists]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=392985 New Units]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Specific topics ===&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=468374 Culture buildings - vanilla and G&amp;amp;K cross compatibility]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=394056 Import civ4 units into civ5]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=405148 Locking techs on a civilization basis]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=396911 Making units that use Civ5 animations]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=474309 Guide to Adding a new Resource with Custom Reskins]&lt;br /&gt;
* [[Text icons and markups (Civ5)|Text icons and markups]]&lt;br /&gt;
* [[VFS (Civ5)|VFS]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Persisting_data_(Civ5)&amp;diff=14055</id>
		<title>Persisting data (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Persisting_data_(Civ5)&amp;diff=14055"/>
		<updated>2012-09-25T12:12:31Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This article explains how to store data that are persisted when the user saves his game, or at anytime for mods settings.&lt;br /&gt;
&lt;br /&gt;
= Opening or creating a storage space =&lt;br /&gt;
&lt;br /&gt;
Mods can store data in the following containers:&lt;br /&gt;
* Global storage spaces accessible at any time. To store mods settings for example.&lt;br /&gt;
* One local storage space embedded in savegames. A zombie mod could for example use it to store the locations where units died in case they should be resurrected later.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Global storage spaces ===&lt;br /&gt;
You create/open such a space by using: &amp;lt;code&amp;gt;{{Type5|ModData}} Modding.{{Func5|Modding|OpenUserData}}(&#039;&#039;&#039;string&#039;&#039;&#039; name, &#039;&#039;&#039;int&#039;&#039;&#039; version)&amp;lt;code&amp;gt;.&lt;br /&gt;
* Many modders specify their mod&#039;s GUID as a name. However this is not mandatory and it is not necessary the best practice for the end-user since it produces undecipherable files names. We suggest you just make sure to provide a unique name to avoid conflicts between mods.&lt;br /&gt;
* This storage space will be stored under a file in &amp;lt;code&amp;gt;My Games/Sid Meier&#039;s Civilization V/ModUserData/&amp;lt;/code&amp;gt;. The file name will be the name you provided with the &amp;quot;.db&amp;quot; extension.&lt;br /&gt;
* Mods can use the same space if they share common settings for example. However it cannot be used as a communication channel it is not possible to listen for changes.&lt;br /&gt;
* One mod can create as much spaces as it wants.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Savegame&#039;s storage space ===&lt;br /&gt;
You can create/open the savegame&#039;s storage space by using: &amp;lt;code&amp;gt;{{Type5|ModData}} Modding.{{Func5|Modding|OpenSaveData}}()&amp;lt;/code&amp;gt;.&lt;br /&gt;
* This space is shared by all mods, so beware of keys names conflicts: when saving a property try to prepend its name with a unique prefix for your mod &amp;quot;IGE_&amp;quot; for In-game editor, &amp;quot;RED_&amp;quot; for R.E.D., etc.&lt;br /&gt;
* The content of this space is written directly in the savegame file whenever the user saves his game.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Using the storage space =&lt;br /&gt;
=== Get or set value ===&lt;br /&gt;
Once you retrieve a {{Type5|ModData}} instance, this one exposes the following methods:&lt;br /&gt;
* &amp;lt;code&amp;gt;{{Func5|ModData|SetValue}}(&#039;&#039;&#039;string&#039;&#039;&#039; name, &#039;&#039;&#039;variant&#039;&#039;&#039; data)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;variant&#039;&#039;&#039; {{Func5|ModData|GetValue}}(&#039;&#039;&#039;string&#039;&#039;&#039; name)&amp;lt;/code&amp;gt;&lt;br /&gt;
A few remarks:&lt;br /&gt;
* Data can be &#039;&#039;&#039;nil&#039;&#039;&#039;, &#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;number&#039;&#039;&#039; or &#039;&#039;&#039;string&#039;&#039;&#039;.&lt;br /&gt;
* If you query a value never assigned before, it will be nil.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Dealing with default values ===&lt;br /&gt;
Since it is not possible to know whether the value you just did read already existed before, you need to deal with the default nil values you will encounter. Here are some examples:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local db = Modding.OpenSaveData()&lt;br /&gt;
local trueByDefault = db.GetValue(&amp;quot;trueByDefault&amp;quot;) ~= &amp;quot;false&amp;quot;  -- False if &amp;quot;false&amp;quot;, true otherwise&lt;br /&gt;
local falseByDefault = db.GetValue(&amp;quot;falseByDefault&amp;quot;) == &amp;quot;true&amp;quot; -- True if &amp;quot;true&amp;quot;, false otherwise&lt;br /&gt;
local oneByDefault = db.GetValue(&amp;quot;oneByDefault&amp;quot;) or 1          -- 1 if nil or false, the value otherwise&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Addressing performances problems =&lt;br /&gt;
The {{Type5|ModData}} you get is implemented through a database table. This means that every value read/write will generate a request string, this one will have to be parsed, etc. If you frequently read or write values, this can greatly hinder the game&#039;s performances. &lt;br /&gt;
&lt;br /&gt;
=== Using a local cache ===&lt;br /&gt;
Dealing with the reads is pretty easy, we only need to create a local copy of the properties, as demonstrated in the G&amp;amp;K scenarios. Instead of calling {{Func5|ModData|GetValue}} and {{Func5|ModData|SetValue}} directly, we will use the following wrappers:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
g_SaveData = Modding.OpenSaveData()&lt;br /&gt;
g_Properties = {}&lt;br /&gt;
&lt;br /&gt;
function GetPersistentProperty(name)&lt;br /&gt;
    if not g_Properties[name] then&lt;br /&gt;
        g_Properties[name] = g_SaveData.GetValue(name)&lt;br /&gt;
    end&lt;br /&gt;
    return g_Properties[name]&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
function SetPersistentProperty(name, value)&lt;br /&gt;
    if GetPersistentProperty(name) == value then return end&lt;br /&gt;
    g_SaveData.SetValue(name, value)&lt;br /&gt;
    g_Properties[name] = value&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Persisting tables ===&lt;br /&gt;
A convenient and fast solution is to save tables, by exploiting the [http://www.lua.org/manual/5.1/manual.html#pdf-loadstring loadstring] table. The following implementation is a simple and naive one with the following limitations:&lt;br /&gt;
* Strings cannot contain the &amp;quot;]]&amp;quot; sequence.&lt;br /&gt;
* Can only save nils, booleans, numbers, strings, and tables. No functions or API Objects like {{Type5|Player}}.&lt;br /&gt;
* No identity preservation: if a sub-table is stored twice in the provided table, it will be deserialized as two different tables.&lt;br /&gt;
* It has not been tested, there may be errors.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function ToLuaCode(item)&lt;br /&gt;
   if type(item) == &amp;quot;nil&amp;quot; then return &amp;quot;nil&amp;quot; end&lt;br /&gt;
   if type(item) == &amp;quot;bool&amp;quot; then return tostring(item) end&lt;br /&gt;
   if type(item) == &amp;quot;number&amp;quot; then return tostring(item) end&lt;br /&gt;
   if type(item) == &amp;quot;string&amp;quot; then return &amp;quot;[[&amp;quot; .. item .. &amp;quot;]]&amp;quot; end&lt;br /&gt;
   if type(item) ~= &amp;quot;table&amp;quot; then error(&amp;quot;could not serialize an element&amp;quot;) end&lt;br /&gt;
   &lt;br /&gt;
   local str = &amp;quot;{&amp;quot;&lt;br /&gt;
   for k, v in pairs(item) do&lt;br /&gt;
       str = str .. &amp;quot;[&amp;quot; .. ToLuaCode(k) .. &amp;quot;] = &amp;quot; .. ToLuaCode(v) .. &amp;quot;, &amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
   return str..&amp;quot;}&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
function SetPersistentTable(name, t)&lt;br /&gt;
    g_SaveData.SetValue(name, ToLuaCode(t))&lt;br /&gt;
    g_Properties[name] = t&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
function GetPersistentTable(name)&lt;br /&gt;
    if not g_Properties[name] then&lt;br /&gt;
        local code = g_SaveData.GetValue(name)&lt;br /&gt;
        g_Properties[name] = loadstring(code)()&lt;br /&gt;
    end&lt;br /&gt;
    return g_Properties[name]&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Just-in-time writes ===&lt;br /&gt;
The previous tricks unfortunately do not address the problem entirely if you need frequent writes (for example anytime a unit moves). A good idea in theory would be to detect when the user is going to save his game so that you only write data at this point. Unfortunately there is no event for this circumstance and while it is possible to hijack the &amp;quot;quicksave&amp;quot; hotkey and the &amp;quot;save&amp;quot; menu, &#039;&#039;&#039;this creates a whole bunch of incompatibilities with other mods&#039;&#039;&#039;. Use it in last resort. If you want to see an implementation example, look at the R.E.D. WWII mod.&lt;br /&gt;
&lt;br /&gt;
Another alternative is to use custom tables, as described in the next section.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Alternatives =&lt;br /&gt;
&lt;br /&gt;
=== Using the script data (mostly deprecated) ===&lt;br /&gt;
Every {{Type5|Player}}, {{Type5|Plot}} and {{Type5|Unit}} can hold one string.&lt;br /&gt;
* Strings are set through Player:{{Func5|Player|SetScriptData}}, Plot:{{Func5|Plot|SetScriptData}}, and Unit:{{Func5|Unit|SetScriptData}}&lt;br /&gt;
* Strings are retrieved through Player:{{Func5|Player|GetScriptData}}, Plot:{{Func5|Plot|GetScriptData}}, and Unit:{{Func5|Unit|GetScriptData}}&lt;br /&gt;
* Those data are shared between mods so this is a frequent cause of conflicts.&lt;br /&gt;
* There were more of those &amp;quot;SetScriptData&amp;quot; methods in the past, on other objects, but they have been removed on May 2012 by Firaxis. It is possible that Firaxis also removes the last three ones at a later point.&lt;br /&gt;
* Users interested in this solution should give a look at the [http://forums.civfanatics.com/showthread.php?t=392958 SaveUtils] library from Whys.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Using a custom table ===&lt;br /&gt;
If you want you may use a custom data table, although it has few advantages. It&#039;s not very convenient and if you were using it to store one row at once, you would encounter the same performances problems as {{Type5|ModData}}. However writing one or thousands of values at once in a data table makes small difference in the execution time so you could use it for batch updates and get good results. This can be an alternative to the table persistence method explained before. This can be done through &amp;lt;code&amp;gt;DB.{{Func5|DB|Query}}(&#039;&#039;&#039;variant&#039;&#039;&#039; data)&amp;lt;/code&amp;gt;. Users interested in this solution should also give a look at the [http://forums.civfanatics.com/showthread.php?t=442249 TableSaverLoader] library from Pazyryk.&lt;br /&gt;
&lt;br /&gt;
Here is an example where we store magic points for some units (untested):&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Create table if not already done on mod loading&lt;br /&gt;
if not GetPersistentProperty(&amp;quot;MyMod_initialized&amp;quot;) then &lt;br /&gt;
   DB.Query(&amp;quot;CREATE TABLE UnitsMagic( id INTEGER PRIMARY KEY UNIQUE, value INTEGER);&amp;quot;)&lt;br /&gt;
   SetPersistentProperty(&amp;quot;MyMod_initialized&amp;quot;, true)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- SaveAll takes a table[playerID][unitID] = value&lt;br /&gt;
function SaveAll(magicPoints)&lt;br /&gt;
    local query = &amp;quot;&amp;quot;&lt;br /&gt;
    for playerID, playerTable in ipairs(magicPoints) do&lt;br /&gt;
        for unitID, magicPoints in ipairs(playerTable) do&lt;br /&gt;
            -- Units&#039; ID are player-specific only, so we compute a global unique identifier from the player&#039;s and unit&#039;s identifiers.&lt;br /&gt;
            local ID = playerID * 10000 + unitID&lt;br /&gt;
            query = query..&amp;quot;REPLACE INTO UnitsMagic (id, value) VALUES (&amp;quot;..ID..&amp;quot;, &amp;quot;..magicPoints..&amp;quot;);\n&amp;quot;&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    DB.Query(query)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Persisting_data_(Civ5)&amp;diff=14054</id>
		<title>Persisting data (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Persisting_data_(Civ5)&amp;diff=14054"/>
		<updated>2012-09-25T12:12:03Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This article explains how to store data that are persisted when the user saves his game, or at anytime for mods settings.&lt;br /&gt;
&lt;br /&gt;
= Opening or creating a storage space =&lt;br /&gt;
&lt;br /&gt;
Mods can store data in the following containers:&lt;br /&gt;
* Global storage spaces accessible at any time. To store mods settings for example.&lt;br /&gt;
* One local storage space embedded in savegames. A zombie mod could for example use it to store the locations where units died in case they should be resurrected later.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Global storage spaces ===&lt;br /&gt;
You create/open such a space by using: &amp;lt;code&amp;gt;{{Type5|ModData}} Modding.{{Func5|Modding|OpenUserData}}(&#039;&#039;&#039;string&#039;&#039;&#039; name, &#039;&#039;&#039;int&#039;&#039;&#039; version)&amp;lt;code&amp;gt;.&lt;br /&gt;
* Many modders specify their mod&#039;s GUID as a name. However this is not mandatory and it is not necessary the best practice for the end-user since it produces undecipherable files names. We suggest you just make sure to provide a unique name to avoid conflicts between mods.&lt;br /&gt;
* This storage space will be stored under a file in &amp;lt;code&amp;gt;My Games/Sid Meier&#039;s Civilization V/ModUserData/&amp;lt;/code&amp;gt;. The file name will be the name you provided with the &amp;quot;.db&amp;quot; extension.&lt;br /&gt;
* Mods can use the same space if they share common settings for example. However it cannot be used as a communication channel it is not possible to listen for changes.&lt;br /&gt;
* One mod can create as much spaces as it wants.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Savegame&#039;s storage space ===&lt;br /&gt;
You can create/open the savegame&#039;s storage space by using: &amp;lt;code&amp;gt;{{Type5|ModData}} Modding.{{Func5|Modding|OpenSaveData}}()&amp;lt;/code&amp;gt;.&lt;br /&gt;
* This space is shared by all mods, so beware of keys names conflicts: when saving a property try to prepend its name with a unique prefix for your mod &amp;quot;IGE_&amp;quot; for In-game editor, &amp;quot;RED_&amp;quot; for R.E.D., etc.&lt;br /&gt;
* The content of this space is written directly in the savegame file whenever the user saves his game.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Using the storage space =&lt;br /&gt;
=== Get or set value ===&lt;br /&gt;
Once you retrieve a {{Type5|ModData}} instance, this one exposes the following methods:&lt;br /&gt;
* &amp;lt;code&amp;gt;{{Func5|ModData|SetValue}}(&#039;&#039;&#039;string&#039;&#039;&#039; name, &#039;&#039;&#039;variant&#039;&#039;&#039; data)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;variant&#039;&#039;&#039; {{Func5|ModData|GetValue}}(&#039;&#039;&#039;string&#039;&#039;&#039; name)&amp;lt;/code&amp;gt;&lt;br /&gt;
A few remarks:&lt;br /&gt;
* Data can be &#039;&#039;&#039;nil&#039;&#039;&#039;, &#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;number&#039;&#039;&#039; or &#039;&#039;&#039;string&#039;&#039;&#039;.&lt;br /&gt;
* If you query a value never assigned before, it will be nil.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Dealing with default values ===&lt;br /&gt;
Since it is not possible to know whether the value you just did read already existed before, you need to deal with the default nil values you will encounter. Here are some examples:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local db = Modding.OpenSaveData()&lt;br /&gt;
local trueByDefault = db.GetValue(&amp;quot;trueByDefault&amp;quot;) ~= &amp;quot;false&amp;quot;  -- False if &amp;quot;false&amp;quot;, true otherwise&lt;br /&gt;
local falseByDefault = db.GetValue(&amp;quot;falseByDefault&amp;quot;) == &amp;quot;true&amp;quot; -- True if &amp;quot;true&amp;quot;, false otherwise&lt;br /&gt;
local oneByDefault = db.GetValue(&amp;quot;oneByDefault&amp;quot;) or 1          -- 1 if nil or false, the value otherwise&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Addressing performances problems ==&lt;br /&gt;
The {{Type5|ModData}} you get is implemented through a database table. This means that every value read/write will generate a request string, this one will have to be parsed, etc. If you frequently read or write values, this can greatly hinder the game&#039;s performances. &lt;br /&gt;
&lt;br /&gt;
=== Using a local cache ===&lt;br /&gt;
Dealing with the reads is pretty easy, we only need to create a local copy of the properties, as demonstrated in the G&amp;amp;K scenarios. Instead of calling {{Func5|ModData|GetValue}} and {{Func5|ModData|SetValue}} directly, we will use the following wrappers:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
g_SaveData = Modding.OpenSaveData()&lt;br /&gt;
g_Properties = {}&lt;br /&gt;
&lt;br /&gt;
function GetPersistentProperty(name)&lt;br /&gt;
    if not g_Properties[name] then&lt;br /&gt;
        g_Properties[name] = g_SaveData.GetValue(name)&lt;br /&gt;
    end&lt;br /&gt;
    return g_Properties[name]&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
function SetPersistentProperty(name, value)&lt;br /&gt;
    if GetPersistentProperty(name) == value then return end&lt;br /&gt;
    g_SaveData.SetValue(name, value)&lt;br /&gt;
    g_Properties[name] = value&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Persisting tables ===&lt;br /&gt;
A convenient and fast solution is to save tables, by exploiting the [http://www.lua.org/manual/5.1/manual.html#pdf-loadstring loadstring] table. The following implementation is a simple and naive one with the following limitations:&lt;br /&gt;
* Strings cannot contain the &amp;quot;]]&amp;quot; sequence.&lt;br /&gt;
* Can only save nils, booleans, numbers, strings, and tables. No functions or API Objects like {{Type5|Player}}.&lt;br /&gt;
* No identity preservation: if a sub-table is stored twice in the provided table, it will be deserialized as two different tables.&lt;br /&gt;
* It has not been tested, there may be errors.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function ToLuaCode(item)&lt;br /&gt;
   if type(item) == &amp;quot;nil&amp;quot; then return &amp;quot;nil&amp;quot; end&lt;br /&gt;
   if type(item) == &amp;quot;bool&amp;quot; then return tostring(item) end&lt;br /&gt;
   if type(item) == &amp;quot;number&amp;quot; then return tostring(item) end&lt;br /&gt;
   if type(item) == &amp;quot;string&amp;quot; then return &amp;quot;[[&amp;quot; .. item .. &amp;quot;]]&amp;quot; end&lt;br /&gt;
   if type(item) ~= &amp;quot;table&amp;quot; then error(&amp;quot;could not serialize an element&amp;quot;) end&lt;br /&gt;
   &lt;br /&gt;
   local str = &amp;quot;{&amp;quot;&lt;br /&gt;
   for k, v in pairs(item) do&lt;br /&gt;
       str = str .. &amp;quot;[&amp;quot; .. ToLuaCode(k) .. &amp;quot;] = &amp;quot; .. ToLuaCode(v) .. &amp;quot;, &amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
   return str..&amp;quot;}&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
function SetPersistentTable(name, t)&lt;br /&gt;
    g_SaveData.SetValue(name, ToLuaCode(t))&lt;br /&gt;
    g_Properties[name] = t&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
function GetPersistentTable(name)&lt;br /&gt;
    if not g_Properties[name] then&lt;br /&gt;
        local code = g_SaveData.GetValue(name)&lt;br /&gt;
        g_Properties[name] = loadstring(code)()&lt;br /&gt;
    end&lt;br /&gt;
    return g_Properties[name]&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Just-in-time writes ===&lt;br /&gt;
The previous tricks unfortunately do not address the problem entirely if you need frequent writes (for example anytime a unit moves). A good idea in theory would be to detect when the user is going to save his game so that you only write data at this point. Unfortunately there is no event for this circumstance and while it is possible to hijack the &amp;quot;quicksave&amp;quot; hotkey and the &amp;quot;save&amp;quot; menu, &#039;&#039;&#039;this creates a whole bunch of incompatibilities with other mods&#039;&#039;&#039;. Use it in last resort. If you want to see an implementation example, look at the R.E.D. WWII mod.&lt;br /&gt;
&lt;br /&gt;
Another alternative is to use custom tables, as described in the next section.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Alternatives =&lt;br /&gt;
&lt;br /&gt;
=== Using the script data (mostly deprecated) ===&lt;br /&gt;
Every {{Type5|Player}}, {{Type5|Plot}} and {{Type5|Unit}} can hold one string.&lt;br /&gt;
* Strings are set through Player:{{Func5|Player|SetScriptData}}, Plot:{{Func5|Plot|SetScriptData}}, and Unit:{{Func5|Unit|SetScriptData}}&lt;br /&gt;
* Strings are retrieved through Player:{{Func5|Player|GetScriptData}}, Plot:{{Func5|Plot|GetScriptData}}, and Unit:{{Func5|Unit|GetScriptData}}&lt;br /&gt;
* Those data are shared between mods so this is a frequent cause of conflicts.&lt;br /&gt;
* There were more of those &amp;quot;SetScriptData&amp;quot; methods in the past, on other objects, but they have been removed on May 2012 by Firaxis. It is possible that Firaxis also removes the last three ones at a later point.&lt;br /&gt;
* Users interested in this solution should give a look at the [http://forums.civfanatics.com/showthread.php?t=392958 SaveUtils] library from Whys.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Using a custom table ===&lt;br /&gt;
If you want you may use a custom data table, although it has few advantages. It&#039;s not very convenient and if you were using it to store one row at once, you would encounter the same performances problems as {{Type5|ModData}}. However writing one or thousands of values at once in a data table makes small difference in the execution time so you could use it for batch updates and get good results. This can be an alternative to the table persistence method explained before. This can be done through &amp;lt;code&amp;gt;DB.{{Func5|DB|Query}}(&#039;&#039;&#039;variant&#039;&#039;&#039; data)&amp;lt;/code&amp;gt;. Users interested in this solution should also give a look at the [http://forums.civfanatics.com/showthread.php?t=442249 TableSaverLoader] library from Pazyryk.&lt;br /&gt;
&lt;br /&gt;
Here is an example where we store magic points for some units (untested):&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Create table if not already done on mod loading&lt;br /&gt;
if not GetPersistentProperty(&amp;quot;MyMod_initialized&amp;quot;) then &lt;br /&gt;
   DB.Query(&amp;quot;CREATE TABLE UnitsMagic( id INTEGER PRIMARY KEY UNIQUE, value INTEGER);&amp;quot;)&lt;br /&gt;
   SetPersistentProperty(&amp;quot;MyMod_initialized&amp;quot;, true)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- SaveAll takes a table[playerID][unitID] = value&lt;br /&gt;
function SaveAll(magicPoints)&lt;br /&gt;
    local query = &amp;quot;&amp;quot;&lt;br /&gt;
    for playerID, playerTable in ipairs(magicPoints) do&lt;br /&gt;
        for unitID, magicPoints in ipairs(playerTable) do&lt;br /&gt;
            -- Units&#039; ID are player-specific only, so we compute a global unique identifier from the player&#039;s and unit&#039;s identifiers.&lt;br /&gt;
            local ID = playerID * 10000 + unitID&lt;br /&gt;
            query = query..&amp;quot;REPLACE INTO UnitsMagic (id, value) VALUES (&amp;quot;..ID..&amp;quot;, &amp;quot;..magicPoints..&amp;quot;);\n&amp;quot;&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
    DB.Query(query)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Map_and_terrain_(Civ5)&amp;diff=14053</id>
		<title>Map and terrain (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Map_and_terrain_(Civ5)&amp;diff=14053"/>
		<updated>2012-09-25T12:11:41Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
= Layout =&lt;br /&gt;
&lt;br /&gt;
=== Coordinates systems ===&lt;br /&gt;
Civ5 uses three different coordinates systems for plots:&lt;br /&gt;
* The &#039;&#039;&#039;world coordinates&#039;&#039;&#039;. The coordinates of the plot&#039;s graphics in the 3D space where the world is rendered. This system is only used when you want to display an icon over the map, through a {{Type5|WorldAnchor}}.&lt;br /&gt;
* The &#039;&#039;&#039;grid coordinates&#039;&#039;&#039;. The logical coordinates of a plot. This is the system returned by Plot:{{Func5|Plot|GetX}}() and Plot:{{Func5|Plot|GetY}}()&lt;br /&gt;
* The &#039;&#039;&#039;hex coordinates&#039;&#039;&#039;. The logical coordinates of a plot. Some computations are easier to perform in this system.&lt;br /&gt;
&lt;br /&gt;
{|&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot; |[[File:Coords-Grid.png|frame|The grid coordinates: horizontal and vertical axes are orthogonal.]]&lt;br /&gt;
|width=&amp;quot;20px&amp;quot;|&lt;br /&gt;
|valign=&amp;quot;top&amp;quot; |[[File:Coords-Hex.png|frame|The hex coordinates: the vertical axis makes a 60° angle with the horizontal axis.]]&lt;br /&gt;
|}&lt;br /&gt;
The reason behind the coexistence of the grid and hex coordinates is because most computations are easier to perform in the hex system. For example, if you wish to examine the neighbors of a plot...&lt;br /&gt;
* In the grid coordinates, you first need to test whether y is odd or even. Depending on the result, the offsets of the top plots will be { (0,1), (1,1) } or { (-1,1), (0,1)}. &lt;br /&gt;
* However no such test is required in the hex system: the top offsets are always { (-1,1), (0,1) }.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Helpful functions ===&lt;br /&gt;
The following global functions will help you:&lt;br /&gt;
{|&lt;br /&gt;
|-&lt;br /&gt;
|align=&amp;quot;right&amp;quot;|&amp;lt;code&amp;gt;{{Type5|Vector2}}&amp;lt;/code&amp;gt;&lt;br /&gt;
|width=&amp;quot;6px&amp;quot;|&lt;br /&gt;
|&amp;lt;code&amp;gt;{{Func5|Vector2}}(int x, int y)&amp;lt;/code&amp;gt; makes a 2D vector.&lt;br /&gt;
|-&lt;br /&gt;
|align=&amp;quot;right&amp;quot;|&amp;lt;code&amp;gt;int, int&amp;lt;/code&amp;gt;&lt;br /&gt;
|width=&amp;quot;6px&amp;quot;|&lt;br /&gt;
|&amp;lt;code&amp;gt;{{Func5|ToGridFromHex}}(int x, int y)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
|align=&amp;quot;right&amp;quot;|&amp;lt;code&amp;gt;int, int, int &amp;lt;/code&amp;gt;&lt;br /&gt;
|width=&amp;quot;6px&amp;quot;|&lt;br /&gt;
|&amp;lt;code&amp;gt;{{Func5|GridToWorld}}(int x, int y)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
|align=&amp;quot;right&amp;quot;|&amp;lt;code&amp;gt;{{Type5|Vector2}}&amp;lt;/code&amp;gt;&lt;br /&gt;
|width=&amp;quot;6px&amp;quot;|&lt;br /&gt;
|&amp;lt;code&amp;gt;{{Func5|ToHexFromGrid}}({{Type5|Vector2}} hexPos)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
|align=&amp;quot;right&amp;quot;|&amp;lt;code&amp;gt;{{Type5|Vector3}}&amp;lt;/code&amp;gt;&lt;br /&gt;
|width=&amp;quot;6px&amp;quot;|&lt;br /&gt;
|&amp;lt;code&amp;gt; {{Func5|HexToWorld}}({{Type5|Vector2}} hexPos)&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Plots indexing ===&lt;br /&gt;
The function Map.{{Func5|Map|GetPlotByIndex}}(int index) takes an index and returns a plot. This index can be computed as follow:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local w = Map.GetGridSize()&lt;br /&gt;
local index = gridX + gridY * w&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Enumerating neighbor plots ===&lt;br /&gt;
The best way is to use &amp;lt;code&amp;gt;Map.{{Func5|Map|PlotDirection}}(&#039;&#039;&#039;int&#039;&#039;&#039; x, &#039;&#039;&#039;int&#039;&#039;&#039; y, {{Type5|DirectionType}} direction)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x, y = ... -- Initialize those&lt;br /&gt;
for i = 0, 5 do&lt;br /&gt;
    local plot = Map.PlotDirection(x, y, i)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Enumerating plots in a certain range ===&lt;br /&gt;
If you need to enumerate plots in specific orders, you should look at [http://forums.civfanatics.com/showthread.php?t=474634 Border and plots iterator], a great library from Whoward69 who provides nice iterators for different scan orders.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Otherwise, Map.{{Func5|Map|PlotXYWithRangeCheck}} offers a simple way to scan all plots within a certain range.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x, y = ... -- Initialize those&lt;br /&gt;
local range = 5&lt;br /&gt;
for dx = -range, range do&lt;br /&gt;
    for dy = -range, range do&lt;br /&gt;
        local plot = Map.PlotXYWithRangeCheck(x, y, dx, dy, range)&lt;br /&gt;
        if plot then&lt;br /&gt;
            -- Do whatever you want with this plot&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== The world is not flat ===&lt;br /&gt;
Maps can be wrapped along X or Y. You can get those values through Map.{{Func5|Map|IsWrapX}}() and Map.{{Func5|Map|IsWrapY}}(). &lt;br /&gt;
* When wrapped along X, reaching the west side of the map brings you to the east side. &lt;br /&gt;
* When wrapped along Y, reaching the north side brings you to the south side. &lt;br /&gt;
* A map can neither be wrapped along X, neither around Y. For example a map that only covers a part of the world.&lt;br /&gt;
* A map cannot be both wrapped along X and Y.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Terrain =&lt;br /&gt;
=== Nature ===&lt;br /&gt;
The nature, aspect and value of a {{Type5|Plot}} in civ5 are defined by the following data:&lt;br /&gt;
* {{Type5|PlotType}}. It can be ocean (includes lakes and coasts), land, hills or mountain.&lt;br /&gt;
* {{Type5|TerrainType}}. It can be ocean, coast (lake or coast), grasslands, plains, tundra or snow. A coast is automatically a lake if it belongs to a water area not larger than nine plots (see the [[#Areas|next section]]).&lt;br /&gt;
* {{Type5|FeatureType}}. It can be none, forest, jungle, floodplains, marsh, oasis, ice, fallout or any natural wonder.&lt;br /&gt;
* {{Type5|ResourceType}} and a quantity value. It can be any resource: gold, gems, horses, fish, etc.&lt;br /&gt;
* {{Type5|ImprovementType}} and a &amp;quot;pillaged&amp;quot; boolean flag. It can be any improvement: mines, farm, etc. Goodies, city ruins and barbarian camps are also improvements.&lt;br /&gt;
* {{Type5|RouteType}}. It can be none, road or railroad.&lt;br /&gt;
* {{Type5|ArtStyleType}}. It can be South America, Asian, European, Middle-East, Polynesian Greco-Roman or Barbarian. It decides which graphics will be used to render the plot.&lt;br /&gt;
* Besides of those, a plot also stores its coordinates, references to the city and units it hosts, its owner index, and visibility flags for every player in the game.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Areas ===&lt;br /&gt;
* The map is divided into different areas: one per landmass and one per watermass. That is, all plots in an island belong to the same area, which is different from the closest continent&#039;s area. Every lake or inner sea also has their own areas.&lt;br /&gt;
* Areas are represented in the API by the {{Type5|Area}} type.&lt;br /&gt;
* Water areas that contains nine plots at most are lakes. Otherwise they are oceans.&lt;br /&gt;
* Areas are computed when the map is generated, through Map.{{Func5|Map|RecalculateAreas}}(). You should not recompute them unless you turn some plots from water to land and reciprocally.&lt;br /&gt;
* In Civ4 impassable plots had their distinct areas and they could diode a landmass into sub-areas. This is no longer true in civ5.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Rivers =&lt;br /&gt;
=== Methods ===&lt;br /&gt;
[[File:RiverSides.png|frame|You can only query or modify three edges per plot: E, SE, SW]] &lt;br /&gt;
[[File:RiverFlow.png|frame|Illustration of the {{Type5|FlowDirectionType}} on every edge.]]&lt;br /&gt;
Every plot has:&lt;br /&gt;
* Three status getters:&lt;br /&gt;
** &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039; Plot:IsWOfRiver()&amp;lt;/code&amp;gt;. Checks the east edge (IsWOfRiver stands for &amp;quot;is at the west of a river&amp;quot;)&lt;br /&gt;
** &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039; Plot:IsNWOfRiver()&amp;lt;/code&amp;gt;. SE edge.&lt;br /&gt;
** &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039; Plot:IsNEOfRiver()&amp;lt;/code&amp;gt;. SW edge.&lt;br /&gt;
* Three direction getters:&lt;br /&gt;
** &amp;lt;code&amp;gt;{{Type5|FlowDirectionType}} Plot:GetRiverEFlowDirection()&amp;lt;/code&amp;gt;.&lt;br /&gt;
** &amp;lt;code&amp;gt;{{Type5|FlowDirectionType}} Plot:GetRiverSEFlowDirection()&amp;lt;/code&amp;gt;.&lt;br /&gt;
** &amp;lt;code&amp;gt;{{Type5|FlowDirectionType}} Plot:GetRiverSWFlowDirection()&amp;lt;/code&amp;gt;.&lt;br /&gt;
* Three setters:&lt;br /&gt;
** &amp;lt;code&amp;gt;Plot:SetWOfRiver(&#039;&#039;&#039;bool&#039;&#039;&#039; hasRiver, {{Type5|FlowDirectionType}} flow = -1)&amp;lt;/code&amp;gt;.&lt;br /&gt;
** &amp;lt;code&amp;gt;Plot:SetNWOfRiver(&#039;&#039;&#039;bool&#039;&#039;&#039; hasRiver, {{Type5|FlowDirectionType}} flow = -1)&amp;lt;/code&amp;gt;.&lt;br /&gt;
** &amp;lt;code&amp;gt;Plot:SetNEOfRiver(&#039;&#039;&#039;bool&#039;&#039;&#039; hasRiver, {{Type5|FlowDirectionType}} flow = -1)&amp;lt;/code&amp;gt;.&lt;br /&gt;
* Two generalized getters that return true if there is a river in the specified direction (or towards the specified plot):&lt;br /&gt;
** &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039; Plot:{{Func5|Plot|IsRiverCrossing}}({{Type5|DirectionType}} direction)&amp;lt;/code&amp;gt; &lt;br /&gt;
** &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039; Plot:{{Func5|Plot|IsRiverCrossingToPlot}}({{Type5|Plot}} toPlot)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Generalized functions ===&lt;br /&gt;
The fact that you can only query three edges is troublesome. Here are simple functions to circumvent this limitation. Note that the HasRiver function is redundant with the {{Func5|Plot|IsRiverCrossing}} and {{Func5|Plot|IsRiverCrossingToPlot}} methods.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot; style=&amp;quot;clear:none;&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function HasRiver(plot, direction)&lt;br /&gt;
    if direction == 1 then return plot:IsWOfRiver() end&lt;br /&gt;
    if direction == 2 then return plot:IsNWOfRiver() end&lt;br /&gt;
    if direction == 3 then return plot:IsNEOfRiver() end&lt;br /&gt;
    local neighbor = Map.PlotDirection(plot:GetX(), plot:GetY(), direction)&lt;br /&gt;
    return HasRiver(neighbor, direction - 3)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
function GetRiverFlow(plot, direction)&lt;br /&gt;
    if direction == 1 then return plot:GetRiverEFlowDirection() end&lt;br /&gt;
    if direction == 2 then return plot:GetRiverSEFlowDirection() end&lt;br /&gt;
    if direction == 3 then return plot:GetRiverSWFlowDirection() end&lt;br /&gt;
    local neighbor = Map.PlotDirection(plot:GetX(), plot:GetY(), direction)&lt;br /&gt;
    return GetRiverFlow(neighbor, direction - 3)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
function SetRiver(plot, direction, hasRiver, flowDirection)&lt;br /&gt;
    if direction == 1 then return plot:SetWOfRiver(hasRiver, flowDirection) end&lt;br /&gt;
    if direction == 2 then return plot:SetNWOfRiver(hasRiver, flowDirection) end&lt;br /&gt;
    if direction == 3 then return plot:SetNEOfRiver(hasRiver, flowDirection) end&lt;br /&gt;
    local neighbor = Map.PlotDirection(plot:GetX(), plot:GetY(), direction)&lt;br /&gt;
    return SetRiver(neighbor, direction - 3, hasRiver, flowDirection)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_Libraries_for_Civ5&amp;diff=14052</id>
		<title>Lua Libraries for Civ5</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_Libraries_for_Civ5&amp;diff=14052"/>
		<updated>2012-09-25T12:11:21Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Improving modularity and mods compatibility =&lt;br /&gt;
Sometimes mods needs to modify the standard game files in order to achieve some features. Since only one mod can modify a given file a a time, this creates conflicts. Those libraries address those issues: all mods use the same file replacement and this one exposes a way to register new entries and such.&lt;br /&gt;
{| cellpadding=&amp;quot;4&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!Name&lt;br /&gt;
!Author&lt;br /&gt;
!Description&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot; |[http://forums.civfanatics.com/showthread.php?t=411186 Fully Modifyable Custom Notifications]&lt;br /&gt;
|valign=&amp;quot;top&amp;quot; |&#039;&#039;Sneaks&#039;&#039;&lt;br /&gt;
|Provides a non-conflicting way for mods to add custom notifications.&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot; |[http://forums.civfanatics.com/showthread.php?p=11394279 Modular Diplo Corner]&lt;br /&gt;
|valign=&amp;quot;top&amp;quot; |&#039;&#039;Whoward69&#039;&#039;&lt;br /&gt;
|Provides a non-conflicting way for mods to add entries to the diplo corner menu. While Civ5 now offers a similar functionality in standard, this mod still offers the benefit to prevent compatibility issues between updated and outdated mods.&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot; |[http://forums.civfanatics.com/showthread.php?t=458740 Modular Minimap Overlays]&lt;br /&gt;
|valign=&amp;quot;top&amp;quot; |&#039;&#039;Whoward69&#039;&#039;&lt;br /&gt;
|Provides a non-conflicting way for mods to add entries to the minimap overlays menu.&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot; |[http://forums.civfanatics.com/showthread.php?t=459207 Modular Summary Bar]&lt;br /&gt;
|valign=&amp;quot;top&amp;quot; |&#039;&#039;Whoward69&#039;&#039;&lt;br /&gt;
|Provides a non-conflicting way for mods to add entries to the topmost bar, near the turn number.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Other libraries =&lt;br /&gt;
{| cellpadding=&amp;quot;4&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!Name&lt;br /&gt;
!Author&lt;br /&gt;
!Description&lt;br /&gt;
|-&lt;br /&gt;
|[http://forums.civfanatics.com/showthread.php?t=474634 Border and Area Plot Iterators]&lt;br /&gt;
|&#039;&#039;Whoward69&#039;&#039;&lt;br /&gt;
|Provides iterators to enumerate plots in a given range and in different orders.&lt;br /&gt;
|-&lt;br /&gt;
|[http://forums.civfanatics.com/showthread.php?t=392958 SaveUtils] &lt;br /&gt;
|&#039;&#039;Whys&#039;&#039;&lt;br /&gt;
|Wrappers around the SetScriptData methods (partially deprecated) for conveniency purpose and mods conflicts prevention. See also [[Persisting data (Civ5)]].&lt;br /&gt;
|-&lt;br /&gt;
|[http://forums.civfanatics.com/showthread.php?t=442249 TableSaverLoader] &lt;br /&gt;
|&#039;&#039;Pazyryk&#039;&#039;&lt;br /&gt;
|Saves a Lua table into a custom data table. See also [[Persisting data (Civ5)]].&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Civ5_API_Reference_FAQ&amp;diff=14051</id>
		<title>Civ5 API Reference FAQ</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Civ5_API_Reference_FAQ&amp;diff=14051"/>
		<updated>2012-09-25T12:10:55Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Types terminology=&lt;br /&gt;
{| cellpadding=&amp;quot;8&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot;|&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;unknown&#039;&#039;&#039;&amp;lt;/code&amp;gt;&lt;br /&gt;
|This parameter&#039;s type could not be identified.&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot;|&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039;&amp;lt;/code&amp;gt;&lt;br /&gt;
|A Lua string.&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot;|&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;int&#039;&#039;&#039;&amp;lt;/code&amp;gt;&lt;br /&gt;
|Any integer.&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot;|&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;float&#039;&#039;&#039;&amp;lt;/code&amp;gt;&lt;br /&gt;
|Any number, integer or floating-point.&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot;|&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;table&#039;&#039;&#039;&amp;lt;/code&amp;gt;&lt;br /&gt;
|An unidentified table. Look at the code samples to figure it out by yourself.&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot;|&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;table(key =&amp;gt; value)&#039;&#039;&#039;&amp;lt;/code&amp;gt;&lt;br /&gt;
|A table whose keys and values have the specified types.&lt;br /&gt;
:Example: &amp;lt;code&amp;gt;table({{Type5|PlayerID}} =&amp;gt; {{Type5|Player}}) players&amp;lt;/code&amp;gt;&lt;br /&gt;
::It can be enumerated with: &amp;lt;code&amp;gt;for playerID, player in ipairs(players) do&amp;lt;/code&amp;gt;&lt;br /&gt;
::The following will return a {{Type5|Player}}: &amp;lt;code&amp;gt;players[0]&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot;|&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;iterator(type1, type2, type3)&#039;&#039;&#039;&amp;lt;/code&amp;gt;&lt;br /&gt;
|To be used in a &amp;lt;code&amp;gt;for... in...&amp;lt;/code&amp;gt; loop.&lt;br /&gt;
:Example: &amp;lt;code&amp;gt;iterator({{Type5|Unit}}) Units()&amp;lt;/code&amp;gt; &lt;br /&gt;
::It can be enumerated with: &amp;lt;code&amp;gt;for pUnit in Units() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot;|&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;variant&#039;&#039;&#039;&amp;lt;/code&amp;gt;&lt;br /&gt;
|This parameter can be assigned with different types.&lt;br /&gt;
:Example: &amp;lt;code&amp;gt;DB.{{Func5|DB|Query}}(&#039;&#039;&#039;variant&#039;&#039;&#039; arg)&amp;lt;/code&amp;gt; &lt;br /&gt;
::This function can accept a string or a table.&lt;br /&gt;
|-&lt;br /&gt;
|valign=&amp;quot;top&amp;quot;|&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;...&#039;&#039;&#039;&amp;lt;/code&amp;gt;&lt;br /&gt;
|A variable number of arguments. A good example is Locale.{{Func5|Locale|ConvertTextKey}}.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Object-oriented concepts in Lua=&lt;br /&gt;
The concepts below originate from object-oriented languages. But since Lua is weakly typed, it offers richer possibilities than those languages. As a result those concepts may sometimes lack relevance and may need to be adapted or broaden. However they&#039;re still adequate since most of the API reflects the types defined in C++ by Firaxis.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Instance versus static types&#039;&#039;&#039;&lt;br /&gt;
* Instance types can be instanced, such as {{Type5|Player}}. &lt;br /&gt;
* Static types exist as a single global variable, such as {{Type5|Game}}. &lt;br /&gt;
* Some types can be both, such as {{Type5|InstanceManager}}: a global variable exists with this name and calling its {{Func5|InstanceManager|new}} method creates a new instance of {{Type5|InstanceManager}}.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Functions versus methods&#039;&#039;&#039;&lt;br /&gt;
* We call method any function stored as a type member.&lt;br /&gt;
* This is purely aesthetic: a function and a method are both called and used in the same way. We could store a method in a local variable and use it as a function.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Instance methods&#039;&#039;&#039;&lt;br /&gt;
* They are methods that require the caller to be passed as the first argument.&lt;br /&gt;
* The colon (&#039;&#039;&#039;:&#039;&#039;&#039;) operator implicitly passes the caller as the first argument. Those two expressions are equivalent: &amp;lt;code&amp;gt;caller.somefunc(caller, arg)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;caller:somefunc(arg)&amp;lt;/code&amp;gt;&lt;br /&gt;
* When declaring methods, the caller is referenced as the &#039;&#039;&#039;self&#039;&#039;&#039; keyword. It can be explicitly defined or not, see [[Lua introduction for confirmed developers]].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Events&#039;&#039;&#039;&lt;br /&gt;
* Events in the civ5 API can be (un-)subscribed this way: &amp;lt;code&amp;gt;Events.SomeEvent.Add(Handler)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;Events.SomeEvent.Remove(Handler)&amp;lt;/code&amp;gt;&lt;br /&gt;
* They can be invoked like regular methods: &amp;lt;code&amp;gt;Events.SomeEvent(arg1, arg2)&amp;lt;/code&amp;gt;&lt;br /&gt;
* Events typically do not expect any return type. But the ones in {{Type5|GameEvents}} usually expect an integer or a boolean, see their documentations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Reliability of the documentation=&lt;br /&gt;
&#039;&#039;&#039;All listed functions exist.&#039;&#039;&#039;&lt;br /&gt;
:But some of them may be malfunctioning. Ghost functions have been removed by checking the binaries strings tables.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Some functions may not be listed.&#039;&#039;&#039;&lt;br /&gt;
:Only the methods that can be enumerated by a Lua code, the ones mentioned on the 2k wiki, and the ones used by the Lua source code from Firaxis are listed. A few additional functions found in the binaries have been added but this scan is quite superficial.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Some functions could have hidden arguments/return types.&#039;&#039;&#039;&lt;br /&gt;
:There could be additional arguments not listed because they were never used or documented by Firaxis. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Some functions arguments could be actually optional.&#039;&#039;&#039;&lt;br /&gt;
:Reciprocally, some of the arguments listed could be optional: Firaxis always used them but it does not mean they always need to be used.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Arguments&#039; default values are not reliable.&#039;&#039;&#039;&lt;br /&gt;
:They are mostly here to notify you that an argument is optional. While &#039;&#039;&#039;nil&#039;&#039;&#039; is always an acceptable value to provide in such a case, a nil for a boolean will probably be interpreted as &#039;&#039;&#039;false&#039;&#039;&#039; (but it could be &#039;&#039;&#039;true&#039;&#039;&#039;) and an integer as &#039;&#039;&#039;0&#039;&#039;&#039; (but it could be anything else).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;The arguments&#039; types and returned types are not always reliable.&#039;&#039;&#039;&lt;br /&gt;
:While a lot of efforts were done to ensure the typing is reliable, this problem cannot be solved unambiguously. The current compromise between truthfulness and completeness is quite good but it could still be improved and, anyway, it cannot be perfect without human corrections.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Most of those types are only here for documentation purpose&#039;&#039;&#039;&lt;br /&gt;
:The structures and identifiers are never mentioned anywhere in the API, they have been introduced for documentation purposes only. Lua and the API just treat them as tables (for structures) and integers (for identifiers). That being said, the structures obviously have C++ counterparts behind them. There could be additional structures that are not listed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Pages generation process=&lt;br /&gt;
The initial versions of those pages were automatically generated by a bot written in C# by [[User:DonQuich|DonQuiche]]. &lt;br /&gt;
&lt;br /&gt;
Here are the first steps of this bot:&lt;br /&gt;
* We manually define the existing type names and their natures (identifier, structure, etc)&lt;br /&gt;
* The [http://wiki.2kgames.com/civ5/index.php/Lua_Game_Objects 2kgames wiki] is scanned. It is sparse, the types are rarely mentioned and the informations are sometimes incorrect or obsolete.&lt;br /&gt;
* Manual fixes are applied to core functions that will trigger type inference cascades later during the Lua source code analysis.&lt;br /&gt;
* Two lua dumps (with and without G&amp;amp;K) are scanned to collect members. They have been generated by a home-brewed mod that outputs the members on all types, enumerations and their metatables.&lt;br /&gt;
* The binaries are scanned to detect additional functions for a few types. The process is rudimentary and does not collect many informations.&lt;br /&gt;
* The database files are scanned, this will be used to infere types from calls to GameInfos and such during the Lua source code analysis.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Then we parse the Lua and UI source files from the base game, G&amp;amp;K and most DLC. This step produces an inference graph and assembles the code samples. This is the main information source for the bot and the most important step.&lt;br /&gt;
* The inference graph is a bastardized version of a minimalist AST (abstract syntax tree), specialized for type equations resolution. It describes relations such as: &#039;&#039;argument 0 in SomeType.SomeFunc is assigned by the third return type of OtherType.OtherFunc, and also by...&#039;&#039;.&lt;br /&gt;
* The inference graph is solved in order to infer all the arguments and return types. During this process we also update the arguments name, we detect unknown functions and arguments, new events, structures&#039; fields, etc.&lt;br /&gt;
* The whole process implements its custom version of the VFS to manage includes. It manages to test all the possible combinations of different file versions to simulate the presence of absence of the expansions and DLC.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally, the whole API is known and the type system complete. &lt;br /&gt;
* The binaries (dll and exe) are scanned a second time to search for all the strings they contain. If a function&#039;s name does not appear in those tables, it means it no longer exists. This is the primary source to detect methods that have been removed (from the base game and/or G&amp;amp;K) and, while simple, it is very reliable.&lt;br /&gt;
* We then import manually written texts to be included in some of the generated pages.&lt;br /&gt;
* Finally we consolidate everything and we categorize the methods according to the keywords found in their names.&lt;br /&gt;
* All pages are generated using T4 templates and we upload the new wiki thanks to the [http://dotnetwikibot.sourceforge.net/ DotNetWikiBot] library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Civ5_API_FAQ&amp;diff=14050</id>
		<title>Civ5 API FAQ</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Civ5_API_FAQ&amp;diff=14050"/>
		<updated>2012-09-25T12:10:31Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Firaxis Hungarian notation =&lt;br /&gt;
=== What is it? ===&lt;br /&gt;
Firaxis used a naming convention categorized as [http://en.wikipedia.org/wiki/Hungarian_notation Hungarian Notation]. The prefixes provide informations regarding the type.&lt;br /&gt;
* &#039;&#039;&#039;s&#039;&#039;&#039;, &#039;&#039;&#039;sz&#039;&#039;&#039; and &#039;&#039;&#039;str&#039;&#039;&#039; mean a string. &lt;br /&gt;
::Example: &#039;&#039;&#039;sName&#039;&#039;&#039; expects something like &amp;quot;Genghis Khan&amp;quot;.&lt;br /&gt;
* &#039;&#039;&#039;b&#039;&#039;&#039; means boolean. &lt;br /&gt;
::Example: &#039;&#039;&#039;bHide&#039;&#039;&#039; expects true or false.&lt;br /&gt;
* &#039;&#039;&#039;f&#039;&#039;&#039; means floating-point, a number. &lt;br /&gt;
::Example: &#039;&#039;&#039;fScale&#039;&#039;&#039; expects a scale factor, may be 0.5, 1.0, 2.0, etc.&lt;br /&gt;
* &#039;&#039;&#039;i&#039;&#039;&#039; means integer, a number. Sometimes it may be one of the identifiers listed on the main page. &lt;br /&gt;
::Example: &#039;&#039;&#039;iPlayer&#039;&#039;&#039; expects a {{Type5|PlayerID}} while &#039;&#039;&#039;iWidth&#039;&#039;&#039; expects a width in pixels (50, 200, etc).&lt;br /&gt;
* &#039;&#039;&#039;e&#039;&#039;&#039; means an identifier (integer) taken from a Lua enumeration. &lt;br /&gt;
::Example: &#039;&#039;&#039;eBuilding&#039;&#039;&#039; expects a {{Type5|BuildingType}}. You could assign it with 10 or &amp;lt;code&amp;gt;GameInfoTypes.BUILDING_SEAPORT &amp;lt;/code&amp;gt;, both are equivalent.&lt;br /&gt;
* &#039;&#039;&#039;p&#039;&#039;&#039; means an API object (p means pointer but pointer is a C term with no relevance in Lua). &lt;br /&gt;
::Example: &#039;&#039;&#039;pPlayer&#039;&#039;&#039; expects a {{Type5|Player}} object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Should you use the same notation? ===&lt;br /&gt;
* Pro: it&#039;s widely used in the community and your code will harmonize with the one from Firaxis.&lt;br /&gt;
* Pro: you always now the type of a variable by looking at its name, which is useful since ModBuddy does not inform us about the type.&lt;br /&gt;
* Con: it adds some clutter and it&#039;s not really necessary because most of the time a consistent naming is enough to know the type of a variable: for example playerID for a {{Type5|PlayerID}} and player for a {{Type5|Player}}.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14049</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14049"/>
		<updated>2012-09-25T12:10:25Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= About Lua =&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Syntax cheatsheet=&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Basics =&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
* &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
* &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned. This speeds up comparisons but it makes allocation of new strings slower.&lt;br /&gt;
* &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
* &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and other limitations. Now the Civ5 API tend to return regular tables whose metatable is of type userdata, this allows us to use the provided objects as regular Lua tables.&lt;br /&gt;
* &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
* &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strict equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is stricter than C and far stricter than PHP for example.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal.&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal.&lt;br /&gt;
&lt;br /&gt;
Regarding tables and C-made objects, they are compared by reference.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
a = { 5 }&lt;br /&gt;
b = { 5 }&lt;br /&gt;
c = a&lt;br /&gt;
assert(a == c) -- OK&lt;br /&gt;
assert(a == b) -- ERROR&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals, globals and includes ===&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* Another specificities of locals: they&#039;re only visible after the point they have been declared in the file, while globals are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Semi-advanced topics =&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Advanced topics=&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the running coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Specificities_of_the_Lua_implementation_in_Civ5&amp;diff=14048</id>
		<title>Specificities of the Lua implementation in Civ5</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Specificities_of_the_Lua_implementation_in_Civ5&amp;diff=14048"/>
		<updated>2012-09-25T12:09:42Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The Civ5 implementation is based on Lua 5.1.4. However it has been modified, mainly for sandboxing purposes.&lt;br /&gt;
&lt;br /&gt;
= Missing elements =&lt;br /&gt;
Those items do not exist in the Civ5 implmentation of Lua. See [http://www.lua.org/manual/5.1/#index Lua Reference#Index] if you want to learn what they are for.&lt;br /&gt;
&lt;br /&gt;
====Missing globals====&lt;br /&gt;
* &#039;&#039;&#039;__G&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Missing functions====&lt;br /&gt;
Use &#039;&#039;&#039;include&#039;&#039;&#039; instead of the &#039;&#039;&#039;load*&#039;&#039;&#039;, &#039;&#039;&#039;module&#039;&#039;&#039; and &#039;&#039;&#039;require&#039;&#039;&#039; functions. See the next section for more informations.&lt;br /&gt;
* &#039;&#039;&#039;getfenv&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;load&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;loadfile&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;loadstring&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;module&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;require&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;setfenv&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;setfenv&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Missing objects====&lt;br /&gt;
For I/O, use the methods from {{Type5|UI}} and {{Type5|Modding}} instead.&lt;br /&gt;
* &#039;&#039;&#039;file&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;io&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;package&#039;&#039;&#039;&lt;br /&gt;
* &#039;&#039;&#039;os&#039;&#039;&#039;: it still exists but only contains the &#039;&#039;&#039;clock&#039;&#039;&#039;, &#039;&#039;&#039;date&#039;&#039;&#039;, &#039;&#039;&#039;time&#039;&#039;&#039; and &#039;&#039;&#039;difftime&#039;&#039;&#039; functions.&lt;br /&gt;
* &amp;lt;s&amp;gt;debug&amp;lt;/s&amp;gt;: fortunately it has been added by Firaxis in May 2012. See [[Lua Debugging (Civ5)]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Include =&lt;br /&gt;
Instead of the usual functions for loading and requiring a Lua file from another, Civ5 provides a custom function to do so: &#039;&#039;&#039;include&#039;&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
====Usage====&lt;br /&gt;
&amp;lt;code&amp;gt;table(&#039;&#039;&#039;int&#039;&#039;&#039; =&amp;gt; &#039;&#039;&#039;string&#039;&#039;&#039;) include(&#039;&#039;&#039;string&#039;&#039;&#039; file, &#039;&#039;&#039;bool&#039;&#039;&#039; useRegex = false)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;file&#039;&#039;&#039;: the name of the file, with or without extension. It can also be a local path starting from &amp;quot;Assets\UI&amp;quot; (see examples). Finally, if useRegex is true, it can be a regular expression where the &#039;&#039;&#039;%&#039;&#039;&#039; character is used instead of &#039;&#039;&#039;\&#039;&#039;&#039;.&lt;br /&gt;
* &#039;&#039;&#039;useRegex&#039;&#039;&#039;: when true, the file argument will be treated as a [http://en.wikipedia.org/wiki/Regular_expression regular expression].&lt;br /&gt;
* &#039;&#039;&#039;returned value:&#039;&#039;&#039; an array that contains all the loaded files (a single one usually, many files if you did use a regular expression).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
include(&amp;quot;CityBannerManager&amp;quot;)&lt;br /&gt;
include(&amp;quot;CityBannerManager.lua&amp;quot;)&lt;br /&gt;
include(&amp;quot;Ingame\\CityBannerManager.lua&amp;quot;) -- loads Assets/UI/Ingame/CityBannerManager.lua&lt;br /&gt;
include(&amp;quot;CityBanner%w+.lua&amp;quot;, true) -- loads all files starting with &amp;quot;CityBanner&amp;quot; and ending with &amp;quot;.lua&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
-- Loads all &amp;quot;*Popup.lua&amp;quot; files in Assets/UI/Ingame/PopupsGeneric. &lt;br /&gt;
-- Then we print a statement for each one of the included files.&lt;br /&gt;
local files = include(&amp;quot;InGame\\PopupsGeneric\\%w+Popup.lua&amp;quot;, true);&lt;br /&gt;
for i, v in ipairs(files) do&lt;br /&gt;
    print(&amp;quot;Loaded Popup - &amp;quot;..v);&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Restrictions====&lt;br /&gt;
* Only the files that have been imported into the [[VFS (Civ5)|VFS]] may be included.&lt;br /&gt;
* Usually only the first eight characters are checked. This is likely only true if you do not specify the path. This means that if you registered two files named &#039;&#039;MapScannerA.lua&#039;&#039; and &#039;&#039;MapScannerB.lua&#039;&#039;, using &amp;lt;code&amp;gt;include(&amp;quot;MapScannerA&amp;quot;)&amp;lt;/code&amp;gt; could either load the A file or the B file!&lt;br /&gt;
* When called in reaction to an UI event, include can silently fail. For example if you use it inside a function and this function is called in reaction to a click on a button, include will report it has been successful but the globals declared in the included file will not be included. This does not happen if you call this function after a Context update or at the time the mod is loaded.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=XML-SQL_Cheat_Sheet_(Civ5)&amp;diff=14047</id>
		<title>XML-SQL Cheat Sheet (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=XML-SQL_Cheat_Sheet_(Civ5)&amp;diff=14047"/>
		<updated>2012-09-25T12:09:08Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 XML Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
= Things to remember =&lt;br /&gt;
* &#039;&#039;&#039;Booleans:&#039;&#039;&#039; SQLite does not have booleans, it uses integers. So do not use &amp;lt;code&amp;gt;true&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;false&amp;lt;/code&amp;gt;, use &amp;lt;code&amp;gt;1&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;0&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Inserting rows =&lt;br /&gt;
=== XML ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;xml&amp;quot; style=&amp;quot;left:40px;&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
	&amp;lt;Colors&amp;gt;&lt;br /&gt;
            &amp;lt;!-- Inserts a new color --&amp;gt;&lt;br /&gt;
            &amp;lt;Row&amp;gt;&lt;br /&gt;
                &amp;lt;Type&amp;gt;COLOR_CUSTOM&amp;lt;/Type&amp;gt;&lt;br /&gt;
                &amp;lt;Red&amp;gt;0.1&amp;lt;/Red&amp;gt;&lt;br /&gt;
                &amp;lt;Green&amp;gt;0.1&amp;lt;/Green&amp;gt;&lt;br /&gt;
                &amp;lt;Blue&amp;gt;0.1&amp;lt;/Blue&amp;gt;&lt;br /&gt;
                &amp;lt;Alpha&amp;gt;0.45&amp;lt;/Alpha&amp;gt;&lt;br /&gt;
            &amp;lt;/Row&amp;gt;	&lt;br /&gt;
	&amp;lt;/Colors&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== SQL ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;sql&amp;quot;&amp;gt;&lt;br /&gt;
/* Inserts a new color */&lt;br /&gt;
INSERT INTO Colors (Type, Red, Green, Blue, Alpha)&lt;br /&gt;
VALUES (&#039;COLOR_CUSTOM&#039;, 0.1, 0.1, 0.1, 0.45);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Deleting rows =&lt;br /&gt;
{{Warning}} See [http://forums.civfanatics.com/showthread.php?t=463429 Deleting data and issues, and how to avoid them] if you plan to delete rows and are not aware of the troubles that may arise.&lt;br /&gt;
=== XML ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
	&amp;lt;Colors&amp;gt;&lt;br /&gt;
            &amp;lt;!-- Deletes all colors named COLOR_CUSTOM (there is only one actually) --&amp;gt;&lt;br /&gt;
            &amp;lt;Delete Type=&amp;quot;COLOR_CUSTOM&amp;quot; /&amp;gt;&lt;br /&gt;
            &amp;lt;!-- You can specify as many conditions as you want --&amp;gt;&lt;br /&gt;
            &amp;lt;Delete R=&amp;quot;1&amp;quot; G=&amp;quot;1&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/Colors&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== SQL ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;sql&amp;quot;&amp;gt;&lt;br /&gt;
/* Deletes all colors named TYPE_CUSTOM whose red channel is equal to 1 */&lt;br /&gt;
DELETE FROM Colors&lt;br /&gt;
WHERE Type = &#039;COLOR_CUSTOM&#039; AND Red = 1;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Updating rows =&lt;br /&gt;
=== XML ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
	&amp;lt;Colors&amp;gt;&lt;br /&gt;
            &amp;lt;!-- Changes the red channel for all colors named COLOR_CUSTOM (there is only one actually)&lt;br /&gt;
            &amp;lt;Update&amp;gt;&lt;br /&gt;
                &amp;lt;Where Type=&amp;quot;COLOR_CUSTOM&amp;quot;/&amp;gt;&lt;br /&gt;
                &amp;lt;Set Red=&amp;quot;1&amp;quot;/&amp;gt;&lt;br /&gt;
            &amp;lt;/Update&amp;gt;&lt;br /&gt;
            &amp;lt;!-- You can specify as many conditions as you want and set as many properties as you want --&amp;gt;&lt;br /&gt;
            &amp;lt;Update&amp;gt;&lt;br /&gt;
                &amp;lt;Where Type=&amp;quot;COLOR_CUSTOM&amp;quot; Red=&amp;quot;0&amp;quot;/&amp;gt;&lt;br /&gt;
                &amp;lt;Set Red=&amp;quot;1&amp;quot; Green=&amp;quot;0&amp;quot;/&amp;gt;&lt;br /&gt;
            &amp;lt;/Update&amp;gt;&lt;br /&gt;
            &amp;lt;!-- As always, formatting rules are relaxed, use what&#039;s the most convenient for you --&amp;gt;&lt;br /&gt;
            &amp;lt;Update&amp;gt;&lt;br /&gt;
                &amp;lt;Where&amp;gt;&lt;br /&gt;
                    &amp;lt;Type&amp;gt;COLOR_CUSTOM&amp;lt;/Type&amp;gt;&lt;br /&gt;
                &amp;lt;/Where&amp;gt;&lt;br /&gt;
                &amp;lt;Set&amp;gt;&lt;br /&gt;
                    &amp;lt;Red&amp;gt;1&amp;lt;/Red&amp;gt;&lt;br /&gt;
                    &amp;lt;Green&amp;gt;1&amp;lt;/Green&amp;gt;&lt;br /&gt;
                &amp;lt;/Set&amp;gt;&lt;br /&gt;
            &amp;lt;/Update&amp;gt;&lt;br /&gt;
        &amp;lt;/Colors&amp;gt;&lt;br /&gt;
&amp;lt;/GameData&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== SQL ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;sql&amp;quot;&amp;gt;&lt;br /&gt;
/* Update all colors whose names are COLOR_CUSTOM and red channel is 0 */&lt;br /&gt;
UPDATE Colors&lt;br /&gt;
SET Red = 1, Green = 0&lt;br /&gt;
WHERE Type = &#039;COLOR_CUSTOM&#039; AND Red = 0;&lt;br /&gt;
&lt;br /&gt;
/* Makes everything brighter */&lt;br /&gt;
UPDATE Colors&lt;br /&gt;
SET Red = Red + 0.1, Green = Green + 0.1, Blue=Blue + 0.1;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= New tables =&lt;br /&gt;
=== XML ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
    &amp;lt;Table Name=&amp;quot;MyColors&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;Column name=&amp;quot;ID&amp;quot; type=&amp;quot;integer&amp;quot; primarykey=&amp;quot;true&amp;quot; autoincrement=&amp;quot;true&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;Column name=&amp;quot;Type&amp;quot; type=&amp;quot;text&amp;quot; notnull=&amp;quot;true&amp;quot; unique=&amp;quot;true&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/Table&amp;gt;&lt;br /&gt;
&amp;lt;/GameData&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== SQL ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;sql&amp;quot;&amp;gt;&lt;br /&gt;
/* Create one new table with two columns */&lt;br /&gt;
CREATE TABLE MyColors( id INTEGER PRIMARY KEY AUTOINCREMENT, Type TEXT UNIQUE );&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= New columns =&lt;br /&gt;
=== SQL ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;sql&amp;quot;&amp;gt;&lt;br /&gt;
/* Adds one Description column to Colors. */&lt;br /&gt;
ALTER TABLE Colors COLUMN &#039;Description&#039; TEXT DEFAULT NULL;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 XML Files]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Civ5_Useful_Programs&amp;diff=14046</id>
		<title>Civ5 Useful Programs</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Civ5_Useful_Programs&amp;diff=14046"/>
		<updated>2012-09-25T12:08:14Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: Titles harmonization with other articles&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page includes information on the Civ5 Modding Tools as well as links to other useful programs.&lt;br /&gt;
&lt;br /&gt;
= SDK =&lt;br /&gt;
&#039;&#039;&#039;World Builder&#039;&#039;&#039;&lt;br /&gt;
:The stand-alone world builder allows users to create and modify maps and scenarios for Civilization V.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Mod Buddy&#039;&#039;&#039;&lt;br /&gt;
:An editor (IDE) for the XML and Lua elements of the game and allows for the creation, packaging, and uploading of mods. To use it, you have to install the [http://www.microsoft.com/downloads/en/details.aspx?FamilyID=DFBA7AC4-5366-456E-ABD6-0E3E6BA83B7C&amp;amp;displaylang=enMicrosoft Visual Studio 2010 Shell (Isolated) Redistributable Package].&lt;br /&gt;
:[http://forums.civfanatics.com/showthread.php?t=387554 Installing ModBuddy Extensions]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Nexus&#039;&#039;&#039;&lt;br /&gt;
:A collection of tools to to work with the art in Civilization V.&lt;br /&gt;
:[http://forums.civfanatics.com/showthread.php?t=386972 Initial Look at Nexus, 3D Unit Art, and Reskinning]&lt;br /&gt;
:Note that Photoshop templates for icons are also bundled in the SDK, under the &#039;&#039;Art&#039;&#039; folder (in &#039;&#039;Programs Files/Steam/...&#039;&#039;).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;FireTuner&#039;&#039;&#039;&lt;br /&gt;
:An advanced debugging terminal. It displays the lua output, provides an interactive console and can be simply extended with custom controls and tables.&lt;br /&gt;
:Do not forget to modify your *.ini files, see [[Debugging (Civ5)#Configuration|Debugging#Configuration]].&lt;br /&gt;
:[http://forums.civfanatics.com/showthread.php?t=399821 Simple Tuner Modifications]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Digging the source code and the data tables =&lt;br /&gt;
Since the documentation is sparse, you need a tool to quickly inspect the civ5 source and data files and search in all of them at once. See also [http://forums.civfanatics.com/showthread.php?t=475076 this comparison of search tools].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Notepad++&#039;&#039;&#039;&lt;br /&gt;
:A great and renowned text editor with a &amp;quot;search in all files&amp;quot; feature (hit ctrl + shift + f). Used by many developers around the world. [http://sourceforge.net/projects/notepad-plus/ Download].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Browsing the art assets =&lt;br /&gt;
&#039;&#039;&#039;Dragon unpacker&#039;&#039;&#039;&lt;br /&gt;
:Can extract the Firaxis packages (.fpk files). [http://sourceforge.net/projects/dragonunpacker/ Download].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;DDS Unpacker&#039;&#039;&#039;&lt;br /&gt;
:Some DDS files have been compressed even further and look messed up if you open them in an image viewer. This tool rebuilds them. [http://forums.civfanatics.com/showthread.php?t=389316 Download].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;XnView&#039;&#039;&#039;&lt;br /&gt;
:An images browser to get a quick look at all the DDS files to spot the one you&#039;re looking for. [http://www.xnview.com/en/download.html Download].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;FireTuner: Textures Viewer&#039;&#039;&#039;&lt;br /&gt;
:A FireTuner panel to browse most of the game&#039;s textures. [http://forums.2kgames.com/showthread.php?118165-MOD-LiveTuner-Texture-Viewer Download].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;FireTuner: Icons Viewer&#039;&#039;&#039;&lt;br /&gt;
:A FireTuner panel to browse the game&#039;s icons. [http://forums.2kgames.com/showthread.php?118055-MOD-LiveTuner-Icon-Viewer Download].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Creating textures =&lt;br /&gt;
&#039;&#039;&#039;NVidia Texture Tools for Photoshop&#039;&#039;&#039;&lt;br /&gt;
:A Photoshop plugin to save textures under the DDS format. [http://developer.nvidia.com/content/nvidia-texture-tools-adobe-photoshop Download]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Paint.net&#039;&#039;&#039;&lt;br /&gt;
:An easy-to-use and moderately powerful open-source image editor for Windows that natively supports the DDS format. [http://www.getpaint.net/ Download]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Testing and debugging =&lt;br /&gt;
&lt;br /&gt;
=== SQLite tools ===&lt;br /&gt;
Anytime it starts a game, Civilization V saves a SQLite snapshot of the database, including the changes made by mods, under &#039;&#039;Civ5DebugDatabase.db&#039;&#039;. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;SQLite Manager&#039;&#039;&#039;&lt;br /&gt;
:A Firefox plug-in, slightly more powerful than the previous tool. [https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/ Download]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;SQLiteSpy&#039;&#039;&#039;&lt;br /&gt;
:A Windows software to inspect the SQLite files. [http://www.yunqa.de/delphi/doku.php/products/sqlitespy/index Download]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;SQLite Browser&#039;&#039;&#039;&lt;br /&gt;
:A Windows software to inspect the SQLite files. [http://sqlitebrowser.sourceforge.net/screenshots.html Download]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Cheating tools and game inspectors ===&lt;br /&gt;
&#039;&#039;&#039;In-game Editor (IGE)&#039;&#039;&#039;&lt;br /&gt;
:Add or remove units, cities, resources, change the terrain, trigger wars, etc. Convenient to quickly test your mod. [http://forums.civfanatics.com/showthread.php?t=436912 Download] (also on the Steam Workshop).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;FireTuner: Techs and policies panel&#039;&#039;&#039;&lt;br /&gt;
:A FireTuner panel to list, grant and revoke techs and policies. [http://forums.2kgames.com/showthread.php?108533-MOD-LiveTuner-Tech-and-Policy-Panels Download].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=VFS_(Civ5)&amp;diff=14045</id>
		<title>VFS (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=VFS_(Civ5)&amp;diff=14045"/>
		<updated>2012-09-25T12:07:47Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This article explains the Virtual File System (VFS) in Civ5. Lua developers looking for informations on the &#039;&#039;&#039;include&#039;&#039;&#039; function should look at [[Specificities of the Lua implementation in Civ5]].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= What is it? =&lt;br /&gt;
[[File:ModBuddy.ImportIntoVFS.png|frame|The &#039;&#039;import into VFS&#039;&#039; option.]] &lt;br /&gt;
VFS stands for Virtual File System. Rather than locating the files directly in the file system, Civ5 looks for them in its virtual file system. This system provides the following benefits:&lt;br /&gt;
* &#039;&#039;&#039;Modularity:&#039;&#039;&#039; each mod, expansion or DLC can provide its own version of a given file without overwriting the original one. At run-time the game sequentially loads those files into the VFS, performing virtual overwrites as needed. This contrasts with the mods hell in the Elders Scrolls series for example.&lt;br /&gt;
* &#039;&#039;&#039;Packaging:&#039;&#039;&#039; The files in the VFS can be either independent files or parts of packages (archives). The VFS behaves as a unified resource loader.&lt;br /&gt;
* &#039;&#039;&#039;Sandboxing:&#039;&#039;&#039; whenever a mod requests a file, civ5 only looks in the VFS. This prevents mods to be allowed to look at the physical file system since this could open a security breach.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Determining whether a file must be imported or not =&lt;br /&gt;
In doubt, import your files into the VFS. But you should better stick to what is written here.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Must be imported&#039;&#039;&#039; the files that are requested during the game.&lt;br /&gt;
* The XML UI files. &lt;br /&gt;
* The XML files for animations, scenes, etc.&lt;br /&gt;
* The Lua files (minus the exception detailed below).&lt;br /&gt;
* The art assets such as textures or models.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Should not be imported&#039;&#039;&#039; the files that are loaded through the project&#039;s content and actions tab (except the XML UI files, those ones should always be imported). While this is harmless most of the time, this can sometimes result in unexpected side-effects.&lt;br /&gt;
* The Lua files that are directly loaded through the project&#039;s content tab. This does not apply if the Lua file is associated with a XML file and you load this XML file instead. Note that if you want a Lua file to be included by other Lua or XML UI files, you will still have to import it into the VFS but you may see it loaded more times than necessary. &lt;br /&gt;
* The XML data and text files. Those ones are only ran at start up to modify the data tables.&lt;br /&gt;
* The SQL files. For the same reasons.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Importing a file into the VFS =&lt;br /&gt;
* In ModBuddy, select a file in the solution exlporer. &lt;br /&gt;
* Hit F4 (or click View &amp;gt; Properties Window) to open its properties.&lt;br /&gt;
* At the bottom of this new window, look for &#039;&#039;&#039;Import into VFS&#039;&#039;&#039; and set it to true.&lt;br /&gt;
* If Civ5 is opened, you will need to exit to the main menu for this change to be applied.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Civ5_Modding_Tutorials&amp;diff=14044</id>
		<title>Civ5 Modding Tutorials</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Civ5_Modding_Tutorials&amp;diff=14044"/>
		<updated>2012-09-25T12:07:23Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: Titles harmonization with other articles&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Getting started =&lt;br /&gt;
&#039;&#039;&#039;Get a tour.&#039;&#039;&#039; &lt;br /&gt;
:If you have no idea about modding and what are Lua and Xml, you should give a look at [http://www.weplayciv.com/forums/entry.php?15-Dale-s-Mod-Blog-Civ5-Modding-Explained Civ5 Modding Explained].&lt;br /&gt;
&#039;&#039;&#039;Read the guide.&#039;&#039;&#039; &lt;br /&gt;
:The best introduction to civ5 modding is still the &#039;&#039;&#039;[http://forums.civfanatics.com/showthread.php?t=385009 Kael&#039;s Guide]&#039;&#039;&#039;. However it was written a long time ago and some informations are obsolete or missing. &lt;br /&gt;
&#039;&#039;&#039;Import your files into VFS.&#039;&#039;&#039; &lt;br /&gt;
:The main change since Kael wrote his guide is about the [[VFS (Civ5)|VFS]] (Virtual File System). Basically you should include your art assets, UI and lua files into the VFS. In ModBuddy, select those files, hit F4 to open the properties window, check &amp;quot;import into VFS&amp;quot;. Forgetting this is a common cause of troubles for beginners. The VFS index only takes into account the first eight chars so beware of conflicts. &lt;br /&gt;
&#039;&#039;&#039;Get the right tools for the job.&#039;&#039;&#039; &lt;br /&gt;
:See [[Civ5 Useful Programs]]. You should have installed the SDK of course, but it is also strongly recommended that you get a tool to search in all civ5 files at once, to compensate for the lack of documentation. You may also need additional softwares to extract and read the textures, test and debug your mod, etc.&lt;br /&gt;
&#039;&#039;&#039;Modify your ini files.&#039;&#039;&#039;&lt;br /&gt;
:See [[Debugging (Civ5)#Configuration|Debugging#Configuration]].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Tutorials =&lt;br /&gt;
See also the [http://forums.civfanatics.com/forumdisplay.php?f=394&amp;amp;order=desc&amp;amp;page=2 Modding tutorials section] on the forums.&amp;lt;br/&amp;gt;&lt;br /&gt;
Also note that the [[Civ5 XML Reference|XML]] and [[Lua and UI Reference|Lua]] sections each contain specific tutorials, articles and extensive documentation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== General ===&lt;br /&gt;
* [[Modding Limits and Issues (Civ5)|Modding Limits and Issues]]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=459392 Create and use DDS textures]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=449431 Adding custom data and using them in Lua]&lt;br /&gt;
* [http://wiki.2kgames.com/civ5/index.php/Mods:LocalizationSyntax Localization Syntax]&lt;br /&gt;
* [[Debugging (Civ5)|Debugging]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Common tasks ===&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=391823 New Leaders (2D images)]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=389782 New Resources]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=470290 New Buildings]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=406877 New Specialists]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=392985 New Units]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Specific topics ===&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=468374 Culture buildings - vanilla and G&amp;amp;K cross compatibility]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=394056 Import civ4 units into civ5]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=405148 Locking techs on a civilization basis]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=396911 Making units that use Civ5 animations]&lt;br /&gt;
* [http://forums.civfanatics.com/showthread.php?t=474309 Guide to Adding a new Resource with Custom Reskins]&lt;br /&gt;
* [[Text icons and markups (Civ5)|Text icons and markups]]&lt;br /&gt;
* [[VFS (Civ5)|VFS]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14043</id>
		<title>Debugging (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14043"/>
		<updated>2012-09-25T12:06:31Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
= Checklist =&lt;br /&gt;
* Did you correctly import to the [[VFS (Civ5)|VFS]] the files that need to be?&lt;br /&gt;
* Did you correctly set up the actions and content tab in your project?&lt;br /&gt;
* Did you restart civ5 after you added new files?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= XML Debugging =&lt;br /&gt;
[[File:SQLiteManager.png|frame|View of the snapshot using SQLiteManager]]&lt;br /&gt;
=== Checking the logs ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves some logs under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;.&lt;br /&gt;
* If there were errors with the XML formatting of your data files (wrong column names for example), they will logged in XML.log. Some of those errors may be fatal: in such a case no mod is loaded!&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6904.323] Tag (TXT_KEYMODDING_SHOWDLCMODS) does not start with &#039;TXT_KEY_&#039;&amp;lt;/pre&amp;gt;&lt;br /&gt;
* If there were errors with the data integrity (missing foreign keys for example - types that reference rows from other tables), they will logged in database.log.&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6903.917] Invalid Reference on Leader_Flavors.LeaderType - &amp;quot;LEADER_HARALD&amp;quot; does not exist in Leaders&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Using the snapshots ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves a snapshot of the database under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;&lt;br /&gt;
* This allows you to check how your XML and SQL files have been merged with the standard game data.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Lua Debugging =&lt;br /&gt;
=== Using the Firetuner console ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], Civ5 will send all the Lua output to the Firetuner (and also to the &amp;lt;code&amp;gt;Lua.log&amp;lt;/code&amp;gt; file). This includes all the debugging output but also any error that may arise, with their calls stack traces. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 Runtime Error: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
stack traceback:&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: in function &#039;dumpObj&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:95: in function &#039;ScanAll&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:188: in main chunk&lt;br /&gt;
	[C]: ?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Here we can see that a C/C++ code (the game engine) ran the main chunk called (the Lua file), which then called the function &#039;&#039;ScanAll&#039;&#039; on line 188, which then called &#039;&#039;dumpObj&#039;&#039; on line 95. And this one caused an error on line 41.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note that paths are truncated in the provided example, which makes debugging harder sometimes. This happens when the file is in a {{Type5|context}} registered by the project&#039;s &#039;&#039;content&#039;&#039; tab. Here are the workarounds:&lt;br /&gt;
* Provide a custom stack trace, as explained in a further section.&lt;br /&gt;
* Register only a minimalist context, that will load additional contexts (through the UI LuaContext markup). Do not initiate any action from the root context, let the children context handle everything.&lt;br /&gt;
* Modifying your system paths is not recommended as it can cause incompatibilities with a few applications (old or badly written).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Print, assert and error ===&lt;br /&gt;
&amp;lt;code&amp;gt;print(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; can be used to print anything to the Firetuner output. This allows you to check the flow of a program, or the values of variables. Print calls &#039;&#039;&#039;tostring&#039;&#039;&#039; on every argument and displays them all on a single line with tabulations as separators between them. Nil values are not displayed, so it is advised you provide expressions such as: &amp;lt;code&amp;gt;(expr or &#039;nil&#039;)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;error(&#039;&#039;&#039;string&#039;&#039;&#039; message, &#039;&#039;&#039;int&#039;&#039;&#039; level = 1)&amp;lt;/code&amp;gt; throws an error with the specified message. The execution is then halted and the hand returned to the game engine (or the current protected call if you did use &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;). The level parameter controls the error position that will be reported. 1 for the line where error is located, 2 for the function call that contained an error, etc. 0 for no position.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;assert(&#039;&#039;&#039;variant&#039;&#039;&#039; condition, &#039;&#039;&#039;string&#039;&#039;&#039; message = &amp;quot;assertion failed&amp;quot;)&amp;lt;/code&amp;gt; can be used to assert the provided condition is neither nil nor false (everything else is evaluated to true in Lua). Otherwise, an error with the specified message is thrown. You can use them punctually, as a debugging technique. But they may also be used as a defensive programming technique similar to [http://en.wikipedia.org/wiki/Design_by_contract design-by-contract]: the idea is that whenever your program&#039;s correctness relies on an assumption, you should explicitly check it. For example, if a function takes an array as an argument and assumes that it is not empty, you should add two conditions at the beginning: &amp;lt;code&amp;gt;assert(type(t) == &amp;quot;table&amp;quot;)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;assert(#t &amp;gt; 0)&amp;lt;/code&amp;gt;. This makes the code more self-explanatory (implicit assumptions are now explicitly stated) and it allows you to catch bugs as soon as possible, which typically makes them easier to understand and fix.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== The end users&#039; feedback ===&lt;br /&gt;
Most of the time, when one of your user encounters an error with your mod, he just stops using it. A fraction of them will do the effort of reporting bugs but too often the informations they provide is unusable (from &amp;quot;it doesn&#039;t work&amp;quot; to wrong reproduction steps &amp;quot;play until turn 173 and wait for Mars being aligned with Venus&amp;quot;). The best way to increase the number of reports and their usefulness is to let your mod tell them the info it needs, as illustrated below.&lt;br /&gt;
&lt;br /&gt;
[[File:IGE-Error.png|none|frame|[http://forums.civfanatics.com/showthread.php?t=436912 In-game editor] tells its users what they must report, even including a calls stack trace when available. The user only needs to make a screenshot that will then land on his Steam profile (provided he didn&#039;t change the Steam settings). Reporting made easy!]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The [[Lua introduction for confirmed developers]] describes a number of techniques you can use to achieve similar results. Here we present an implementation you can use to handle errors in the most dangerous parts of your code in order to present them to the user. The message will even include a full stack trace when available (you can provide your users a link to the [[#Configuration]] section and ask them to modify their config.ini).&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Returns an array of strings, one for each call level. &lt;br /&gt;
-- We could use debug.traceback instead but this ones truncates path and we cannot easily ignore the topmost levels.&lt;br /&gt;
function getStackTrace()&lt;br /&gt;
    -- Level 1 is getStackTrace, 2 is its caller&lt;br /&gt;
    local level = 2 &lt;br /&gt;
    local trace = {}&lt;br /&gt;
    while true do&lt;br /&gt;
        -- Gets that level&#039;s informations: function name, source file and line.&lt;br /&gt;
        local info = debug.getinfo(level, &amp;quot;nSl&amp;quot;) &lt;br /&gt;
        if not info then break end&lt;br /&gt;
&lt;br /&gt;
        -- C code or Lua code?&lt;br /&gt;
        if info.what == &amp;quot;C&amp;quot; then&lt;br /&gt;
            table.insert(trace, &amp;quot;C function&amp;quot;);&lt;br /&gt;
        else   &lt;br /&gt;
            local userStr = Path.GetFileName(info.source)..&amp;quot;: &amp;quot;..info.currentline;&lt;br /&gt;
            if info.name and string.len(info.name) then&lt;br /&gt;
                userStr = userStr..&amp;quot; (&amp;quot;..info.name..&amp;quot;)&amp;quot;;&lt;br /&gt;
            end&lt;br /&gt;
            table.insert(trace, userStr);&lt;br /&gt;
        end&lt;br /&gt;
        level = level + 1&lt;br /&gt;
    end&lt;br /&gt;
    return trace;&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Gets a nicely formatted string of the error. &lt;br /&gt;
-- The second parameter is the number of levels to ignore in the calls stack (formatError excluded). Defaults to 0.&lt;br /&gt;
function formatError(err, levelsToIgnoreBelow)&lt;br /&gt;
    print(err);&lt;br /&gt;
&lt;br /&gt;
    -- We do not want to include formatError in the stack trace, hence the +1&lt;br /&gt;
    levelsToIgnoreBelow = (levelsToIgnoreBelow or 0) + 1;&lt;br /&gt;
&lt;br /&gt;
    -- &#039;err&#039; is like: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
    -- We retrieve important positions in this string. Remember: not all paths are truncated.&lt;br /&gt;
    local elipsisIndex = string.find(err, &amp;quot;...&amp;quot;, 1, true) or -5;&lt;br /&gt;
    local lineIndex = elipsisIndex + 6	&lt;br /&gt;
    local msgIndex = string.find(err, &amp;quot;:&amp;quot;, lineIndex, true) + 1&lt;br /&gt;
&lt;br /&gt;
    -- Can we append the stack trace?&lt;br /&gt;
    local result = &amp;quot;&amp;quot;&lt;br /&gt;
    if debug and debug.getinfo then&lt;br /&gt;
        result = string.sub(err, msgIndex)&lt;br /&gt;
&lt;br /&gt;
        local trace = getStackTrace()&lt;br /&gt;
        for i, v in ipairs(trace) do&lt;br /&gt;
            print(v)&lt;br /&gt;
            if (i &amp;gt; levelsToIgnoreBelow) then&lt;br /&gt;
                result = result..&amp;quot;[NEWLINE]&amp;quot;..v;&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    -- Otherwise just report the line and message, and the source file when not truncated.&lt;br /&gt;
    else&lt;br /&gt;
        result = &amp;quot;line &amp;quot;..string.sub(err, elipsisIndex)&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return result&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- The error handler to provide to xpcall&lt;br /&gt;
local function errorHandler(err)&lt;br /&gt;
    -- The stack trace at this point is:&lt;br /&gt;
    -- 1: this error handler (must not be reported), &lt;br /&gt;
    -- 2: C function calling the handler (kept for security)&lt;br /&gt;
    -- 3: the error source&lt;br /&gt;
    err = formatError(err, 1);&lt;br /&gt;
&lt;br /&gt;
    -- Show a popup to the user&lt;br /&gt;
    local str = L(&amp;quot;Oops, an error occured:&amp;quot;)..&amp;quot;[NEWLINE][ICON_PIRATE] &amp;quot;..err;&lt;br /&gt;
    Events.SerialEventGameMessagePopup( { Type = ButtonPopupTypes.BUTTONPOPUP_TEXT, Data1 = 800, Option1 = true, Text = str } );&lt;br /&gt;
&lt;br /&gt;
    -- Restore things up here when needed. Beware to not cause any error as it would cause an infinite recursive call up to the stack overflow!&lt;br /&gt;
    return false&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Calls someDangerousFunction with the given error handler&lt;br /&gt;
xpcall(someDangerousFunction, errorHandler)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Troubleshooting =&lt;br /&gt;
The [[Civ5 Useful Programs]] page presents you a number of tools you can use to inspect or modify the game. This is especially useful if you want to quickly reproduce a bug or test something, or to understand what is happening.&lt;br /&gt;
* Let&#039;s say your mod adds a tech but you do not see in the techs panel. There is a FireTuner panel you can use to see a flat list of all the techs in-game.&lt;br /&gt;
* Let&#039;s say your mod adds a unit or a wonder, the IGE mod allows you to quickly create an unit or build that wonder (including the splash screen).&lt;br /&gt;
* Let&#039;s say your mod modifies the yields when the player acquire a specific tech. Once again IGE allows you to grant you that tech and see how the yields are modified.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Configuration =&lt;br /&gt;
Look for the following files under &amp;lt;code&amp;gt;My Documents/My Games/Sid Meiers&#039; Civilization V&amp;lt;/code&amp;gt; and open them in a text editor like the notepad (not in a word processor).&lt;br /&gt;
* &#039;&#039;&#039;config.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableTuner&amp;lt;/code&amp;gt; to 1. Civ5 will duplicate the Lua output to FireTuner this one is when present.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;LoggingEnabled&amp;lt;/code&amp;gt; to 1. Civ5 will write log files under the &amp;lt;code&amp;gt;Logs&amp;lt;/code&amp;gt; folder.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableLuaDebugLibrary&amp;lt;/code&amp;gt; to 1. Civ5 will display stack traces on Lua errors and you will be able to use the [http://www.lua.org/manual/5.1/manual.html#pdf-debug.debug debug] object.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugPanel&amp;lt;/code&amp;gt; to 1. By pressing the &#039;&#039;&#039;²&#039;&#039;&#039; key (may be &#039;&#039;&#039;ù&#039;&#039;&#039; or something else depending on your computer&#039;s language) during a game, Civ5 will display a debug panel.&lt;br /&gt;
* &#039;&#039;&#039;usersettings.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugMode&amp;lt;/code&amp;gt; to 1. Needed to enable other features previously mentioned.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14042</id>
		<title>Debugging (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14042"/>
		<updated>2012-09-25T12:05:15Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
== Checklist ==&lt;br /&gt;
* Did you correctly import to the [[VFS (Civ5)|VFS]] the files that need to be?&lt;br /&gt;
* Did you correctly set up the actions and content tab in your project?&lt;br /&gt;
* Did you restart civ5 after you added new files?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== XML Debugging ==&lt;br /&gt;
[[File:SQLiteManager.png|frame|View of the snapshot using SQLiteManager]]&lt;br /&gt;
=== Checking the logs ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves some logs under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;.&lt;br /&gt;
* If there were errors with the XML formatting of your data files (wrong column names for example), they will logged in XML.log. Some of those errors may be fatal: in such a case no mod is loaded!&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6904.323] Tag (TXT_KEYMODDING_SHOWDLCMODS) does not start with &#039;TXT_KEY_&#039;&amp;lt;/pre&amp;gt;&lt;br /&gt;
* If there were errors with the data integrity (missing foreign keys for example - types that reference rows from other tables), they will logged in database.log.&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6903.917] Invalid Reference on Leader_Flavors.LeaderType - &amp;quot;LEADER_HARALD&amp;quot; does not exist in Leaders&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Using the snapshots ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves a snapshot of the database under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;&lt;br /&gt;
* This allows you to check how your XML and SQL files have been merged with the standard game data.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Lua Debugging ==&lt;br /&gt;
=== Using the Firetuner console ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], Civ5 will send all the Lua output to the Firetuner (and also to the &amp;lt;code&amp;gt;Lua.log&amp;lt;/code&amp;gt; file). This includes all the debugging output but also any error that may arise, with their calls stack traces. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 Runtime Error: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
stack traceback:&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: in function &#039;dumpObj&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:95: in function &#039;ScanAll&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:188: in main chunk&lt;br /&gt;
	[C]: ?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Here we can see that a C/C++ code (the game engine) ran the main chunk called (the Lua file), which then called the function &#039;&#039;ScanAll&#039;&#039; on line 188, which then called &#039;&#039;dumpObj&#039;&#039; on line 95. And this one caused an error on line 41.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note that paths are truncated in the provided example, which makes debugging harder sometimes. This happens when the file is in a {{Type5|context}} registered by the project&#039;s &#039;&#039;content&#039;&#039; tab. Here are the workarounds:&lt;br /&gt;
* Provide a custom stack trace, as explained in a further section.&lt;br /&gt;
* Register only a minimalist context, that will load additional contexts (through the UI LuaContext markup). Do not initiate any action from the root context, let the children context handle everything.&lt;br /&gt;
* Modifying your system paths is not recommended as it can cause incompatibilities with a few applications (old or badly written).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Print, assert and error ===&lt;br /&gt;
&amp;lt;code&amp;gt;print(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; can be used to print anything to the Firetuner output. This allows you to check the flow of a program, or the values of variables. Print calls &#039;&#039;&#039;tostring&#039;&#039;&#039; on every argument and displays them all on a single line with tabulations as separators between them. Nil values are not displayed, so it is advised you provide expressions such as: &amp;lt;code&amp;gt;(expr or &#039;nil&#039;)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;error(&#039;&#039;&#039;string&#039;&#039;&#039; message, &#039;&#039;&#039;int&#039;&#039;&#039; level = 1)&amp;lt;/code&amp;gt; throws an error with the specified message. The execution is then halted and the hand returned to the game engine (or the current protected call if you did use &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;). The level parameter controls the error position that will be reported. 1 for the line where error is located, 2 for the function call that contained an error, etc. 0 for no position.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;assert(&#039;&#039;&#039;variant&#039;&#039;&#039; condition, &#039;&#039;&#039;string&#039;&#039;&#039; message = &amp;quot;assertion failed&amp;quot;)&amp;lt;/code&amp;gt; can be used to assert the provided condition is neither nil nor false (everything else is evaluated to true in Lua). Otherwise, an error with the specified message is thrown. You can use them punctually, as a debugging technique. But they may also be used as a defensive programming technique similar to [http://en.wikipedia.org/wiki/Design_by_contract design-by-contract]: the idea is that whenever your program&#039;s correctness relies on an assumption, you should explicitly check it. For example, if a function takes an array as an argument and assumes that it is not empty, you should add two conditions at the beginning: &amp;lt;code&amp;gt;assert(type(t) == &amp;quot;table&amp;quot;)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;assert(#t &amp;gt; 0)&amp;lt;/code&amp;gt;. This makes the code more self-explanatory (implicit assumptions are now explicitly stated) and it allows you to catch bugs as soon as possible, which typically makes them easier to understand and fix.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== The end users&#039; feedback ===&lt;br /&gt;
Most of the time, when one of your user encounters an error with your mod, he just stops using it. A fraction of them will do the effort of reporting bugs but too often the informations they provide is unusable (from &amp;quot;it doesn&#039;t work&amp;quot; to wrong reproduction steps &amp;quot;play until turn 173 and wait for Mars being aligned with Venus&amp;quot;). The best way to increase the number of reports and their usefulness is to let your mod tell them the info it needs, as illustrated below.&lt;br /&gt;
&lt;br /&gt;
[[File:IGE-Error.png|none|frame|[http://forums.civfanatics.com/showthread.php?t=436912 In-game editor] tells its users what they must report, even including a calls stack trace when available. The user only needs to make a screenshot that will then land on his Steam profile (provided he didn&#039;t change the Steam settings). Reporting made easy!]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The [[Lua introduction for confirmed developers]] describes a number of techniques you can use to achieve similar results. Here we present an implementation you can use to handle errors in the most dangerous parts of your code in order to present them to the user. The message will even include a full stack trace when available (you can provide your users a link to the [[#Configuration]] section and ask them to modify their config.ini).&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Returns an array of strings, one for each call level. &lt;br /&gt;
-- We could use debug.traceback instead but this ones truncates path and we cannot easily ignore the topmost levels.&lt;br /&gt;
function getStackTrace()&lt;br /&gt;
    -- Level 1 is getStackTrace, 2 is its caller&lt;br /&gt;
    local level = 2 &lt;br /&gt;
    local trace = {}&lt;br /&gt;
    while true do&lt;br /&gt;
        -- Gets that level&#039;s informations: function name, source file and line.&lt;br /&gt;
        local info = debug.getinfo(level, &amp;quot;nSl&amp;quot;) &lt;br /&gt;
        if not info then break end&lt;br /&gt;
&lt;br /&gt;
        -- C code or Lua code?&lt;br /&gt;
        if info.what == &amp;quot;C&amp;quot; then&lt;br /&gt;
            table.insert(trace, &amp;quot;C function&amp;quot;);&lt;br /&gt;
        else   &lt;br /&gt;
            local userStr = Path.GetFileName(info.source)..&amp;quot;: &amp;quot;..info.currentline;&lt;br /&gt;
            if info.name and string.len(info.name) then&lt;br /&gt;
                userStr = userStr..&amp;quot; (&amp;quot;..info.name..&amp;quot;)&amp;quot;;&lt;br /&gt;
            end&lt;br /&gt;
            table.insert(trace, userStr);&lt;br /&gt;
        end&lt;br /&gt;
        level = level + 1&lt;br /&gt;
    end&lt;br /&gt;
    return trace;&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Gets a nicely formatted string of the error. &lt;br /&gt;
-- The second parameter is the number of levels to ignore in the calls stack (formatError excluded). Defaults to 0.&lt;br /&gt;
function formatError(err, levelsToIgnoreBelow)&lt;br /&gt;
    print(err);&lt;br /&gt;
&lt;br /&gt;
    -- We do not want to include formatError in the stack trace, hence the +1&lt;br /&gt;
    levelsToIgnoreBelow = (levelsToIgnoreBelow or 0) + 1;&lt;br /&gt;
&lt;br /&gt;
    -- &#039;err&#039; is like: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
    -- We retrieve important positions in this string. Remember: not all paths are truncated.&lt;br /&gt;
    local elipsisIndex = string.find(err, &amp;quot;...&amp;quot;, 1, true) or -5;&lt;br /&gt;
    local lineIndex = elipsisIndex + 6	&lt;br /&gt;
    local msgIndex = string.find(err, &amp;quot;:&amp;quot;, lineIndex, true) + 1&lt;br /&gt;
&lt;br /&gt;
    -- Can we append the stack trace?&lt;br /&gt;
    local result = &amp;quot;&amp;quot;&lt;br /&gt;
    if debug and debug.getinfo then&lt;br /&gt;
        result = string.sub(err, msgIndex)&lt;br /&gt;
&lt;br /&gt;
        local trace = getStackTrace()&lt;br /&gt;
        for i, v in ipairs(trace) do&lt;br /&gt;
            print(v)&lt;br /&gt;
            if (i &amp;gt; levelsToIgnoreBelow) then&lt;br /&gt;
                result = result..&amp;quot;[NEWLINE]&amp;quot;..v;&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    -- Otherwise just report the line and message, and the source file when not truncated.&lt;br /&gt;
    else&lt;br /&gt;
        result = &amp;quot;line &amp;quot;..string.sub(err, elipsisIndex)&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return result&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- The error handler to provide to xpcall&lt;br /&gt;
local function errorHandler(err)&lt;br /&gt;
    -- The stack trace at this point is:&lt;br /&gt;
    -- 1: this error handler (must not be reported), &lt;br /&gt;
    -- 2: C function calling the handler (kept for security)&lt;br /&gt;
    -- 3: the error source&lt;br /&gt;
    err = formatError(err, 1);&lt;br /&gt;
&lt;br /&gt;
    -- Show a popup to the user&lt;br /&gt;
    local str = L(&amp;quot;Oops, an error occured:&amp;quot;)..&amp;quot;[NEWLINE][ICON_PIRATE] &amp;quot;..err;&lt;br /&gt;
    Events.SerialEventGameMessagePopup( { Type = ButtonPopupTypes.BUTTONPOPUP_TEXT, Data1 = 800, Option1 = true, Text = str } );&lt;br /&gt;
&lt;br /&gt;
    -- Restore things up here when needed. Beware to not cause any error as it would cause an infinite recursive call up to the stack overflow!&lt;br /&gt;
    return false&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Calls someDangerousFunction with the given error handler&lt;br /&gt;
xpcall(someDangerousFunction, errorHandler)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Troubleshooting ==&lt;br /&gt;
The [[Civ5 Useful Programs]] page presents you a number of tools you can use to inspect or modify the game. This is especially useful if you want to quickly reproduce a bug or test something, or to understand what is happening.&lt;br /&gt;
* Let&#039;s say your mod adds a tech but you do not see in the techs panel. There is a FireTuner panel you can use to see a flat list of all the techs in-game.&lt;br /&gt;
* Let&#039;s say your mod adds a unit or a wonder, the IGE mod allows you to quickly create an unit or build that wonder (including the splash screen).&lt;br /&gt;
* Let&#039;s say your mod modifies the yields when the player acquire a specific tech. Once again IGE allows you to grant you that tech and see how the yields are modified.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Configuration ==&lt;br /&gt;
Look for the following files under &amp;lt;code&amp;gt;My Documents/My Games/Sid Meiers&#039; Civilization V&amp;lt;/code&amp;gt; and open them in a text editor like the notepad (not in a word processor).&lt;br /&gt;
* &#039;&#039;&#039;config.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableTuner&amp;lt;/code&amp;gt; to 1. Civ5 will duplicate the Lua output to FireTuner this one is when present.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;LoggingEnabled&amp;lt;/code&amp;gt; to 1. Civ5 will write log files under the &amp;lt;code&amp;gt;Logs&amp;lt;/code&amp;gt; folder.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableLuaDebugLibrary&amp;lt;/code&amp;gt; to 1. Civ5 will display stack traces on Lua errors and you will be able to use the [http://www.lua.org/manual/5.1/manual.html#pdf-debug.debug debug] object.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugPanel&amp;lt;/code&amp;gt; to 1. By pressing the &#039;&#039;&#039;²&#039;&#039;&#039; key (may be &#039;&#039;&#039;ù&#039;&#039;&#039; or something else depending on your computer&#039;s language) during a game, Civ5 will display a debug panel.&lt;br /&gt;
* &#039;&#039;&#039;usersettings.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugMode&amp;lt;/code&amp;gt; to 1. Needed to enable other features previously mentioned.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14041</id>
		<title>Debugging (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14041"/>
		<updated>2012-09-25T11:59:28Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
== Checklist ==&lt;br /&gt;
* Did you correctly import to the [[VFS (Civ5)|VFS]] the files that need to be?&lt;br /&gt;
* Did you correctly set up the actions and content tab in your project?&lt;br /&gt;
* Did you restart civ5 after you added new files?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== XML Debugging ==&lt;br /&gt;
[[File:SQLiteManager.png|frame|View of the snapshot using SQLiteManager]]&lt;br /&gt;
=== Checking the logs ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves some logs under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;.&lt;br /&gt;
* If there were errors with the XML formatting of your data files (wrong column names for example), they will logged in XML.log. Some of those errors may be fatal: in such a case no mod is loaded!&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6904.323] Tag (TXT_KEYMODDING_SHOWDLCMODS) does not start with &#039;TXT_KEY_&#039;&amp;lt;/pre&amp;gt;&lt;br /&gt;
* If there were errors with the data integrity (missing foreign keys for example - types that reference rows from other tables), they will logged in database.log.&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6903.917] Invalid Reference on Leader_Flavors.LeaderType - &amp;quot;LEADER_HARALD&amp;quot; does not exist in Leaders&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Using the snapshots ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves a snapshot of the database under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;&lt;br /&gt;
* This allows you to check how your XML and SQL files have been merged with the standard game data.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Lua Debugging ==&lt;br /&gt;
=== Using the Firetuner console ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], Civ5 will send all the Lua output to the Firetuner (and also to the &amp;lt;code&amp;gt;Lua.log&amp;lt;/code&amp;gt; file). This includes all the debugging output but also any error that may arise, with their calls stack traces. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 Runtime Error: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
stack traceback:&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: in function &#039;dumpObj&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:95: in function &#039;ScanAll&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:188: in main chunk&lt;br /&gt;
	[C]: ?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Here we can see that a C/C++ code (the game engine) ran the main chunk called (the Lua file), which then called the function &#039;&#039;ScanAll&#039;&#039; on line 188, which then called &#039;&#039;dumpObj&#039;&#039; on line 95. And this one caused an error on line 41.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note that paths are truncated in the provided example, which makes debugging harder sometimes. This happens when the file is in a {{Type5|context}} registered by the project&#039;s &#039;&#039;content&#039;&#039; tab. Here are the workarounds:&lt;br /&gt;
* Provide a custom stack trace, as explained in a further section.&lt;br /&gt;
* Register only a minimalist context, that will load additional contexts (through the UI LuaContext markup). Do not initiate any action from the root context, let the children context handle everything.&lt;br /&gt;
* Modifying your system paths is not recommended as it can cause incompatibilities with a few applications (old or badly written).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Print, assert and error ===&lt;br /&gt;
&amp;lt;code&amp;gt;print(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; can be used to print anything to the Firetuner output. This allows you to check the flow of a program, or the values of variables. Print calls &#039;&#039;&#039;tostring&#039;&#039;&#039; on every argument and displays them all on a single line with tabulations as separators between them. Nil values are not displayed, so it is advised you provide expressions such as: &amp;lt;code&amp;gt;(expr or &#039;nil&#039;)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;error(&#039;&#039;&#039;string&#039;&#039;&#039; message, &#039;&#039;&#039;int&#039;&#039;&#039; level = 1)&amp;lt;/code&amp;gt; throws an error with the specified message. The execution is then halted and the hand returned to the game engine (or the current protected call if you did use &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;). The level parameter controls the error position that will be reported. 1 for the line where error is located, 2 for the function call that contained an error, etc. 0 for no position.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;assert(&#039;&#039;&#039;variant&#039;&#039;&#039; condition, &#039;&#039;&#039;string&#039;&#039;&#039; message = &amp;quot;assertion failed&amp;quot;)&amp;lt;/code&amp;gt; can be used to assert the provided condition is neither nil nor false (everything else is evaluated to true in Lua). Otherwise, an error with the specified message is thrown. You can use them punctually, as a debugging technique. But they may also be used as a defensive programming technique similar to [http://en.wikipedia.org/wiki/Design_by_contract design-by-contract]: the idea is that whenever your program&#039;s correctness relies on an assumption, you should explicitly check it. For example, if a function takes an array as an argument and assumes that it is not empty, you should add two conditions at the beginning: &amp;lt;code&amp;gt;assert(type(t) == &amp;quot;table&amp;quot;)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;assert(#t &amp;gt; 0)&amp;lt;/code&amp;gt;. This makes the code more self-explanatory (implicit assumptions are now explicitly stated) and it allows you to catch bugs as soon as possible, which typically makes them easier to understand and fix.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== The end users&#039; feedback ===&lt;br /&gt;
Most of the time, when one of your user encounters an error with your mod, he just stops using it. A fraction of them will do the effort of reporting bugs but too often the informations they provide is unusable (from &amp;quot;it doesn&#039;t work&amp;quot; to wrong reproduction steps &amp;quot;play until turn 173 and wait for Mars being aligned with Venus&amp;quot;). The best way to increase the number of reports and their usefulness is to let your mod tell them the info it needs, as illustrated below.&lt;br /&gt;
&lt;br /&gt;
[[File:IGE-Error.png|none|frame|[http://forums.civfanatics.com/showthread.php?t=436912 In-game editor] tells its users what they must report, even including a calls stack trace when available. The user only needs to make a screenshot that will then land on his Steam profile (provided he didn&#039;t change the Steam settings). Reporting made easy!]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The [[Lua introduction for confirmed developers]] describes a number of techniques you can use to achieve similar results. Here we present an implementation you can use to handle errors in the most dangerous parts of your code in order to present them to the user with a full stack trace when available.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Returns an array of strings, one for each call level. &lt;br /&gt;
-- We could use debug.traceback instead but this ones truncates path and we cannot easily ignore the topmost levels.&lt;br /&gt;
function getStackTrace()&lt;br /&gt;
    -- Level 1 is getStackTrace, 2 is its caller&lt;br /&gt;
    local level = 2 &lt;br /&gt;
    local trace = {}&lt;br /&gt;
    while true do&lt;br /&gt;
        -- Gets that level&#039;s informations: function name, source file and line.&lt;br /&gt;
        local info = debug.getinfo(level, &amp;quot;nSl&amp;quot;) &lt;br /&gt;
        if not info then break end&lt;br /&gt;
&lt;br /&gt;
        -- C code or Lua code?&lt;br /&gt;
        if info.what == &amp;quot;C&amp;quot; then&lt;br /&gt;
            table.insert(trace, &amp;quot;C function&amp;quot;);&lt;br /&gt;
        else   &lt;br /&gt;
            local userStr = Path.GetFileName(info.source)..&amp;quot;: &amp;quot;..info.currentline;&lt;br /&gt;
            if info.name and string.len(info.name) then&lt;br /&gt;
                userStr = userStr..&amp;quot; (&amp;quot;..info.name..&amp;quot;)&amp;quot;;&lt;br /&gt;
            end&lt;br /&gt;
            table.insert(trace, userStr);&lt;br /&gt;
        end&lt;br /&gt;
        level = level + 1&lt;br /&gt;
    end&lt;br /&gt;
    return trace;&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Gets a nicely formatted string of the error. &lt;br /&gt;
-- The second parameter is the number of levels to ignore in the calls stack (formatError excluded). Defaults to 0.&lt;br /&gt;
function formatError(err, levelsToIgnoreBelow)&lt;br /&gt;
    print(err);&lt;br /&gt;
&lt;br /&gt;
    -- We do not want to include formatError in the stack trace, hence the +1&lt;br /&gt;
    levelsToIgnoreBelow = (levelsToIgnoreBelow or 0) + 1;&lt;br /&gt;
&lt;br /&gt;
    -- &#039;err&#039; is like: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
    -- We retrieve important positions in this string. Remember: not all paths are truncated.&lt;br /&gt;
    local elipsisIndex = string.find(err, &amp;quot;...&amp;quot;, 1, true) or -5;&lt;br /&gt;
    local lineIndex = elipsisIndex + 6	&lt;br /&gt;
    local msgIndex = string.find(err, &amp;quot;:&amp;quot;, lineIndex, true) + 1&lt;br /&gt;
&lt;br /&gt;
    -- Can we append the stack trace?&lt;br /&gt;
    local result = &amp;quot;&amp;quot;&lt;br /&gt;
    if debug and debug.getinfo then&lt;br /&gt;
        result = string.sub(err, msgIndex)&lt;br /&gt;
&lt;br /&gt;
        local trace = getStackTrace()&lt;br /&gt;
        for i, v in ipairs(trace) do&lt;br /&gt;
            print(v)&lt;br /&gt;
            if (i &amp;gt; levelsToIgnoreBelow) then&lt;br /&gt;
                result = result..&amp;quot;[NEWLINE]&amp;quot;..v;&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    -- Otherwise just report the line and message, and the source file when not truncated.&lt;br /&gt;
    else&lt;br /&gt;
        result = &amp;quot;line &amp;quot;..string.sub(err, elipsisIndex)&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return result&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- The error handler to provide to xpcall&lt;br /&gt;
local function errorHandler(err)&lt;br /&gt;
    -- The stack trace at this point is:&lt;br /&gt;
    -- 1: this error handler (must not be reported), &lt;br /&gt;
    -- 2: C function calling the handler (kept for security)&lt;br /&gt;
    -- 3: the error source&lt;br /&gt;
    err = formatError(err, 1);&lt;br /&gt;
&lt;br /&gt;
    -- Show a popup to the user&lt;br /&gt;
    local str = L(&amp;quot;Oops, an error occured:&amp;quot;)..&amp;quot;[NEWLINE][ICON_PIRATE] &amp;quot;..err;&lt;br /&gt;
    Events.SerialEventGameMessagePopup( { Type = ButtonPopupTypes.BUTTONPOPUP_TEXT, Data1 = 800, Option1 = true, Text = str } );&lt;br /&gt;
&lt;br /&gt;
    -- Restore things up here when needed. Beware to not cause any error as it would cause an infinite recursive call up to the stack overflow!&lt;br /&gt;
    return false&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Calls someDangerousFunction with the given error handler&lt;br /&gt;
xpcall(someDangerousFunction, errorHandler)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Troubleshooting ==&lt;br /&gt;
The [[Civ5 Useful Programs]] page presents you a number of tools you can use to inspect or modify the game. This is especially useful if you want to quickly reproduce a bug or test something, or to understand what is happening.&lt;br /&gt;
* Let&#039;s say your mod adds a tech but you do not see in the techs panel. There is a FireTuner panel you can use to see a flat list of all the techs in-game.&lt;br /&gt;
* Let&#039;s say your mod adds a unit or a wonder, the IGE mod allows you to quickly create an unit or build that wonder (including the splash screen).&lt;br /&gt;
* Let&#039;s say your mod modifies the yields when the player acquire a specific tech. Once again IGE allows you to grant you that tech and see how the yields are modified.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Configuration ==&lt;br /&gt;
Look for the following files under &amp;lt;code&amp;gt;My Documents/My Games/Sid Meiers&#039; Civilization V&amp;lt;/code&amp;gt; and open them in a text editor like the notepad (not in a word processor).&lt;br /&gt;
* &#039;&#039;&#039;config.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableTuner&amp;lt;/code&amp;gt; to 1. Civ5 will duplicate the Lua output to FireTuner this one is when present.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;LoggingEnabled&amp;lt;/code&amp;gt; to 1. Civ5 will write log files under the &amp;lt;code&amp;gt;Logs&amp;lt;/code&amp;gt; folder.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableLuaDebugLibrary&amp;lt;/code&amp;gt; to 1. Civ5 will display stack traces on Lua errors and you will be able to use the [http://www.lua.org/manual/5.1/manual.html#pdf-debug.debug debug] object.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugPanel&amp;lt;/code&amp;gt; to 1. By pressing the &#039;&#039;&#039;²&#039;&#039;&#039; key (may be &#039;&#039;&#039;ù&#039;&#039;&#039; or something else depending on your computer&#039;s language) during a game, Civ5 will display a debug panel.&lt;br /&gt;
* &#039;&#039;&#039;usersettings.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugMode&amp;lt;/code&amp;gt; to 1. Needed to enable other features previously mentioned.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14040</id>
		<title>Debugging (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14040"/>
		<updated>2012-09-25T10:11:32Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
== Checklist ==&lt;br /&gt;
* Did you correctly import to the [[VFS (Civ5)|VFS]] the files that need to be?&lt;br /&gt;
* Did you correctly set up the actions and content tab in your project?&lt;br /&gt;
* Did you restart civ5 after you added new files?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== XML Debugging ==&lt;br /&gt;
[[File:SQLiteManager.png|frame|View of the snapshot using SQLiteManager]]&lt;br /&gt;
=== Checking the logs ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves some logs under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;.&lt;br /&gt;
* If there were errors with the XML formatting of your data files (wrong column names for example), they will logged in XML.log. Some of those errors may be fatal: in such a case no mod is loaded!&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6904.323] Tag (TXT_KEYMODDING_SHOWDLCMODS) does not start with &#039;TXT_KEY_&#039;&amp;lt;/pre&amp;gt;&lt;br /&gt;
* If there were errors with the data integrity (missing foreign keys for example - types that reference rows from other tables), they will logged in database.log.&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6903.917] Invalid Reference on Leader_Flavors.LeaderType - &amp;quot;LEADER_HARALD&amp;quot; does not exist in Leaders&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Using the snapshots ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves a snapshot of the database under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;&lt;br /&gt;
* This allows you to check how your XML and SQL files have been merged with the standard game data.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Lua Debugging ==&lt;br /&gt;
=== Using the Firetuner console ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], Civ5 will send all the Lua output to the Firetuner (and also to the &amp;lt;code&amp;gt;Lua.log&amp;lt;/code&amp;gt; file). This includes all the debugging output but also any error that may arise, with their calls stack traces. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 Runtime Error: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
stack traceback:&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: in function &#039;dumpObj&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:95: in function &#039;ScanAll&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:188: in main chunk&lt;br /&gt;
	[C]: ?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Here we can see that a C/C++ code (the game engine) ran the main chunk called (the Lua file), which then called the function &#039;&#039;ScanAll&#039;&#039; on line 188, which then called &#039;&#039;dumpObj&#039;&#039; on line 95. And this one caused an error on line 41.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note that paths are truncated in the provided example, which makes debugging harder sometimes. This happens when the file is in a {{Type5|context}} registered by the project&#039;s &#039;&#039;content&#039;&#039; tab. Here are the workarounds:&lt;br /&gt;
* Provide a custom stack trace, as explained in a further section.&lt;br /&gt;
* Register only a minimalist context, that will load additional contexts (through the UI LuaContext markup). Do not initiate any action from the root context, let the children context handle everything.&lt;br /&gt;
* Modifying your system paths is not recommended as it can cause incompatibilities with a few applications (old or badly written).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Print, assert and error ===&lt;br /&gt;
&amp;lt;code&amp;gt;print(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; can be used to print anything to the Firetuner output. This allows you to check the flow of a program, or the values of variables. Print calls &#039;&#039;&#039;tostring&#039;&#039;&#039; on every argument and displays them all on a single line with tabulations as separators between them. Nil values are not displayed, so it is advised you provide expressions such as: &amp;lt;code&amp;gt;(expr or &#039;nil&#039;)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;error(&#039;&#039;&#039;string&#039;&#039;&#039; message, &#039;&#039;&#039;int&#039;&#039;&#039; level = 1)&amp;lt;/code&amp;gt; throws an error with the specified message. The execution is then halted and the hand returned to the game engine (or the current protected call if you did use &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;). The level parameter controls the error position that will be reported. 1 for the line where error is located, 2 for the function call that contained an error, etc. 0 for no position.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;assert(&#039;&#039;&#039;variant&#039;&#039;&#039; condition, &#039;&#039;&#039;string&#039;&#039;&#039; message = &amp;quot;assertion failed&amp;quot;)&amp;lt;/code&amp;gt; can be used to assert the provided condition is neither nil nor false (everything else is evaluated to true in Lua). Otherwise, an error with the specified message is thrown. You can use them punctually, as a debugging technique. But they may also be used as a defensive programming technique similar to [http://en.wikipedia.org/wiki/Design_by_contract design-by-contract]: the idea is that whenever your program&#039;s correctness relies on an assumption, you should explicitly check it. For example, if a function takes an array as an argument and assumes that it is not empty, you should add two conditions at the beginning: &amp;lt;code&amp;gt;assert(type(t) == &amp;quot;table&amp;quot;)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;assert(#t &amp;gt; 0)&amp;lt;/code&amp;gt;. This makes the code more self-explanatory (implicit assumptions are now explicitly stated) and it allows you to catch bugs as soon as possible, which typically makes them easier to understand and fix.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Handling errors for the end user ===&lt;br /&gt;
Most of the time, when one of your user encounters an error with your mod, he just stops using it. A fraction of them will do the effort of reporting bugs but too often the informations they provide is unusable (from &amp;quot;it doesn&#039;t work&amp;quot; to wrong reproduction steps &amp;quot;play until turn 173 and wait for Mars being aligned with Venus&amp;quot;). The best way to increase the number of reports and their usefulness is to let your mod tell them the info it needs, as illustrated below.&lt;br /&gt;
&lt;br /&gt;
[[File:IGE-Error.png|none|frame|[http://forums.civfanatics.com/showthread.php?t=436912 In-game editor] tells its users what they must report, even including a calls stack trace when available. The user only needs to make a screenshot that will then land on his Steam profile (provided he didn&#039;t change the Steam settings). Reporting made easy!]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The [[Lua introduction for confirmed developers]] describes a number of techniques you can use to achieve similar results. Here we present an implementation you can use to handle errors in the most dangerous parts of your code in order to present them to the user with a full stack trace when available.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Returns an array of strings, one for each call level. &lt;br /&gt;
-- We could use debug.traceback instead but this ones truncates path and we cannot easily ignore the topmost levels.&lt;br /&gt;
function getStackTrace()&lt;br /&gt;
    -- Level 1 is getStackTrace, 2 is its caller&lt;br /&gt;
    local level = 2 &lt;br /&gt;
    local trace = {}&lt;br /&gt;
    while true do&lt;br /&gt;
        -- Gets that level&#039;s informations: function name, source file and line.&lt;br /&gt;
        local info = debug.getinfo(level, &amp;quot;nSl&amp;quot;) &lt;br /&gt;
        if not info then break end&lt;br /&gt;
&lt;br /&gt;
        -- C code or Lua code?&lt;br /&gt;
        if info.what == &amp;quot;C&amp;quot; then&lt;br /&gt;
            table.insert(trace, &amp;quot;C function&amp;quot;);&lt;br /&gt;
        else   &lt;br /&gt;
            local userStr = Path.GetFileName(info.source)..&amp;quot;: &amp;quot;..info.currentline;&lt;br /&gt;
            if info.name and string.len(info.name) then&lt;br /&gt;
                userStr = userStr..&amp;quot; (&amp;quot;..info.name..&amp;quot;)&amp;quot;;&lt;br /&gt;
            end&lt;br /&gt;
            table.insert(trace, userStr);&lt;br /&gt;
        end&lt;br /&gt;
        level = level + 1&lt;br /&gt;
    end&lt;br /&gt;
    return trace;&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Gets a nicely formatted string of the error. &lt;br /&gt;
-- The second parameter is the number of levels to ignore in the calls stack (formatError excluded). Defaults to 0.&lt;br /&gt;
function formatError(err, levelsToIgnoreBelow)&lt;br /&gt;
    print(err);&lt;br /&gt;
&lt;br /&gt;
    -- We do not want to include formatError in the stack trace, hence the +1&lt;br /&gt;
    levelsToIgnoreBelow = (levelsToIgnoreBelow or 0) + 1;&lt;br /&gt;
&lt;br /&gt;
    -- &#039;err&#039; is like: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
    -- We retrieve important positions in this string. Remember: not all paths are truncated.&lt;br /&gt;
    local elipsisIndex = string.find(err, &amp;quot;...&amp;quot;, 1, true) or -5;&lt;br /&gt;
    local lineIndex = elipsisIndex + 6	&lt;br /&gt;
    local msgIndex = string.find(err, &amp;quot;:&amp;quot;, lineIndex, true) + 1&lt;br /&gt;
&lt;br /&gt;
    -- Can we append the stack trace?&lt;br /&gt;
    local result = &amp;quot;&amp;quot;&lt;br /&gt;
    if debug and debug.getinfo then&lt;br /&gt;
        result = string.sub(err, msgIndex)&lt;br /&gt;
&lt;br /&gt;
        local trace = getStackTrace()&lt;br /&gt;
        for i, v in ipairs(trace) do&lt;br /&gt;
            print(v)&lt;br /&gt;
            if (i &amp;gt; levelsToIgnoreBelow) then&lt;br /&gt;
                result = result..&amp;quot;[NEWLINE]&amp;quot;..v;&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    -- Otherwise just report the line and message, and the source file when not truncated.&lt;br /&gt;
    else&lt;br /&gt;
        result = &amp;quot;line &amp;quot;..string.sub(err, elipsisIndex)&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return result&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- The error handler to provide to xpcall&lt;br /&gt;
local function errorHandler(err)&lt;br /&gt;
    -- The stack trace at this point is:&lt;br /&gt;
    -- 1: this error handler (must not be reported), &lt;br /&gt;
    -- 2: C function calling the handler (kept for security)&lt;br /&gt;
    -- 3: the error source&lt;br /&gt;
    err = formatError(err, 1);&lt;br /&gt;
&lt;br /&gt;
    -- Show a popup to the user&lt;br /&gt;
    local str = L(&amp;quot;Oops, an error occured:&amp;quot;)..&amp;quot;[NEWLINE][ICON_PIRATE] &amp;quot;..err;&lt;br /&gt;
    Events.SerialEventGameMessagePopup( { Type = ButtonPopupTypes.BUTTONPOPUP_TEXT, Data1 = 800, Option1 = true, Text = str } );&lt;br /&gt;
&lt;br /&gt;
    -- Restore things up here when needed. Beware to not cause any error as it would cause an infinite recursive call up to the stack overflow!&lt;br /&gt;
    return false&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Calls someDangerousFunction with the given error handler&lt;br /&gt;
xpcall(someDangerousFunction, errorHandler)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Troubleshooting ==&lt;br /&gt;
The [[Civ5 Useful Programs]] page presents you a number of tools you can use to inspect or modify the game. This is especially useful if you want to quickly reproduce a bug or test something, or to understand what is happening.&lt;br /&gt;
* Let&#039;s say your mod adds a tech but you do not see in the techs panel. There is a FireTuner panel you can use to see a flat list of all the techs in-game.&lt;br /&gt;
* Let&#039;s say your mod adds a unit or a wonder, the IGE mod allows you to quickly create an unit or build that wonder (including the splash screen).&lt;br /&gt;
* Let&#039;s say your mod modifies the yields when the player acquire a specific tech. Once again IGE allows you to grant you that tech and see how the yields are modified.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Configuration ==&lt;br /&gt;
Look for the following files under &amp;lt;code&amp;gt;My Documents/My Games/Sid Meiers&#039; Civilization V&amp;lt;/code&amp;gt; and open them in a text editor like the notepad (not in a word processor).&lt;br /&gt;
* &#039;&#039;&#039;config.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableTuner&amp;lt;/code&amp;gt; to 1. Civ5 will duplicate the Lua output to FireTuner this one is when present.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;LoggingEnabled&amp;lt;/code&amp;gt; to 1. Civ5 will write log files under the &amp;lt;code&amp;gt;Logs&amp;lt;/code&amp;gt; folder.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableLuaDebugLibrary&amp;lt;/code&amp;gt; to 1. Civ5 will display stack traces on Lua errors and you will be able to use the [http://www.lua.org/manual/5.1/manual.html#pdf-debug.debug debug] object.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugPanel&amp;lt;/code&amp;gt; to 1. By pressing the &#039;&#039;&#039;²&#039;&#039;&#039; key (may be &#039;&#039;&#039;ù&#039;&#039;&#039; or something else depending on your computer&#039;s language) during a game, Civ5 will display a debug panel.&lt;br /&gt;
* &#039;&#039;&#039;usersettings.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugMode&amp;lt;/code&amp;gt; to 1. Needed to enable other features previously mentioned.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14039</id>
		<title>Debugging (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14039"/>
		<updated>2012-09-25T10:10:01Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
== Checklist ==&lt;br /&gt;
* Did you correctly import to the [[VFS (Civ5)|VFS]] the files that need to be?&lt;br /&gt;
* Did you correctly set up the actions and content tab in your project?&lt;br /&gt;
* Did you restart civ5 after you added new files?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== XML Debugging ==&lt;br /&gt;
[[File:SQLiteManager.png|frame|View of the snapshot using SQLiteManager]]&lt;br /&gt;
=== Checking the logs ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves some logs under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;.&lt;br /&gt;
* If there were errors with the XML formatting of your data files (wrong column names for example), they will logged in XML.log. Some of those errors may be fatal: in such a case no mod is loaded!&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6904.323] Tag (TXT_KEYMODDING_SHOWDLCMODS) does not start with &#039;TXT_KEY_&#039;&amp;lt;/pre&amp;gt;&lt;br /&gt;
* If there were errors with the data integrity (missing foreign keys for example - types that reference rows from other tables), they will logged in database.log.&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6903.917] Invalid Reference on Leader_Flavors.LeaderType - &amp;quot;LEADER_HARALD&amp;quot; does not exist in Leaders&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Using the snapshots ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves a snapshot of the database under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;&lt;br /&gt;
* This allows you to check how your XML and SQL files have been merged with the standard game data.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Lua Debugging ==&lt;br /&gt;
=== Using the Firetuner console ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], Civ5 will send all the Lua output to the Firetuner. This includes all the debugging output but also any error that may arise, with their calls stack traces. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 Runtime Error: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
stack traceback:&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: in function &#039;dumpObj&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:95: in function &#039;ScanAll&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:188: in main chunk&lt;br /&gt;
	[C]: ?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Here we can see that a C/C++ code (the game engine) ran the main chunk called (the Lua file), which then called the function &#039;&#039;ScanAll&#039;&#039; on line 188, which then called &#039;&#039;dumpObj&#039;&#039; on line 95. And this one caused an error on line 41.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note that paths are truncated in the provided example, which makes debugging harder sometimes. This happens when the file is in a {{Type5|context}} registered by the project&#039;s &#039;&#039;content&#039;&#039; tab. Here are the workarounds:&lt;br /&gt;
* Register only a minimalist context, that will load additional contexts (through the UI LuaContext markup). Do not initiate any action from the root context, let the children context handle everything.&lt;br /&gt;
* Provide a custom stack trace, as explained in a further section.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Print, assert and error ===&lt;br /&gt;
&amp;lt;code&amp;gt;print(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; can be used to print anything to the Firetuner output. This allows you to check the flow of a program, or the values of variables. Print calls &#039;&#039;&#039;tostring&#039;&#039;&#039; on every argument and displays them all on a single line with tabulations as separators between them. Nil values are not displayed, so it is advised you provide expressions such as: &amp;lt;code&amp;gt;(expr or &#039;nil&#039;)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;error(&#039;&#039;&#039;string&#039;&#039;&#039; message, &#039;&#039;&#039;int&#039;&#039;&#039; level = 1)&amp;lt;/code&amp;gt; throws an error with the specified message. The execution is then halted and the hand returned to the game engine (or the current protected call if you did use &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;). The level parameter controls the error position that will be reported. 1 for the line where error is located, 2 for the function call that contained an error, etc. 0 for no position.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;assert(&#039;&#039;&#039;variant&#039;&#039;&#039; condition, &#039;&#039;&#039;string&#039;&#039;&#039; message = &amp;quot;assertion failed&amp;quot;)&amp;lt;/code&amp;gt; can be used to assert the provided condition is neither nil nor false (everything else is evaluated to true in Lua). Otherwise, an error with the specified message is thrown. You can use them punctually, as a debugging technique. But they may also be used as a defensive programming technique similar to [http://en.wikipedia.org/wiki/Design_by_contract design-by-contract]: the idea is that whenever your program&#039;s correctness relies on an assumption, you should explicitly check it. For example, if a function takes an array as an argument and assumes that it is not empty, you should add two conditions at the beginning: &amp;lt;code&amp;gt;assert(type(t) == &amp;quot;table&amp;quot;)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;assert(#t &amp;gt; 0)&amp;lt;/code&amp;gt;. This makes the code more self-explanatory (implicit assumptions are now explicitly stated) and it allows you to catch bugs as soon as possible, which typically makes them easier to understand and fix.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Handling errors for the end user ===&lt;br /&gt;
Most of the time, when one of your user encounters an error with your mod, he just stops using it. A fraction of them will do the effort of reporting bugs but too often the informations they provide is unusable (from &amp;quot;it doesn&#039;t work&amp;quot; to wrong reproduction steps &amp;quot;play until turn 173 and wait for Mars being aligned with Venus&amp;quot;). The best way to increase the number of reports and their usefulness is to let your mod tell them the info it needs, as illustrated below.&lt;br /&gt;
&lt;br /&gt;
[[File:IGE-Error.png|none|frame|[http://forums.civfanatics.com/showthread.php?t=436912 In-game editor] tells its users what they must report, even including a calls stack trace when available. The user only needs to make a screenshot that will then land on his Steam profile (provided he didn&#039;t change the Steam settings). Reporting made easy!]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The [[Lua introduction for confirmed developers]] describes a number of techniques you can use to achieve similar results. Here we present an implementation you can use to handle errors in the most dangerous parts of your code in order to present them to the user with a full stack trace when available.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Returns an array of strings, one for each call level. &lt;br /&gt;
-- We could use debug.traceback instead but this ones truncates path and we cannot easily ignore the topmost levels.&lt;br /&gt;
function getStackTrace()&lt;br /&gt;
    -- Level 1 is getStackTrace, 2 is its caller&lt;br /&gt;
    local level = 2 &lt;br /&gt;
    local trace = {}&lt;br /&gt;
    while true do&lt;br /&gt;
        -- Gets that level&#039;s informations: function name, source file and line.&lt;br /&gt;
        local info = debug.getinfo(level, &amp;quot;nSl&amp;quot;) &lt;br /&gt;
        if not info then break end&lt;br /&gt;
&lt;br /&gt;
        -- C code or Lua code?&lt;br /&gt;
        if info.what == &amp;quot;C&amp;quot; then&lt;br /&gt;
            table.insert(trace, &amp;quot;C function&amp;quot;);&lt;br /&gt;
        else   &lt;br /&gt;
            local userStr = Path.GetFileName(info.source)..&amp;quot;: &amp;quot;..info.currentline;&lt;br /&gt;
            if info.name and string.len(info.name) then&lt;br /&gt;
                userStr = userStr..&amp;quot; (&amp;quot;..info.name..&amp;quot;)&amp;quot;;&lt;br /&gt;
            end&lt;br /&gt;
            table.insert(trace, userStr);&lt;br /&gt;
        end&lt;br /&gt;
        level = level + 1&lt;br /&gt;
    end&lt;br /&gt;
    return trace;&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Gets a nicely formatted string of the error. &lt;br /&gt;
-- The second parameter is the number of levels to ignore in the calls stack (formatError excluded). Defaults to 0.&lt;br /&gt;
function formatError(err, levelsToIgnoreBelow)&lt;br /&gt;
    print(err);&lt;br /&gt;
&lt;br /&gt;
    -- We do not want to include formatError in the stack trace, hence the +1&lt;br /&gt;
    levelsToIgnoreBelow = (levelsToIgnoreBelow or 0) + 1;&lt;br /&gt;
&lt;br /&gt;
    -- &#039;err&#039; is like: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
    -- We retrieve important positions in this string. Remember: not all paths are truncated.&lt;br /&gt;
    local elipsisIndex = string.find(err, &amp;quot;...&amp;quot;, 1, true) or -5;&lt;br /&gt;
    local lineIndex = elipsisIndex + 6	&lt;br /&gt;
    local msgIndex = string.find(err, &amp;quot;:&amp;quot;, lineIndex, true) + 1&lt;br /&gt;
&lt;br /&gt;
    -- Can we append the stack trace?&lt;br /&gt;
    local result = &amp;quot;&amp;quot;&lt;br /&gt;
    if debug and debug.getinfo then&lt;br /&gt;
        result = string.sub(err, msgIndex)&lt;br /&gt;
&lt;br /&gt;
        local trace = getStackTrace()&lt;br /&gt;
        for i, v in ipairs(trace) do&lt;br /&gt;
            print(v)&lt;br /&gt;
            if (i &amp;gt; levelsToIgnoreBelow) then&lt;br /&gt;
                result = result..&amp;quot;[NEWLINE]&amp;quot;..v;&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    -- Otherwise just report the line and message, and the source file when not truncated.&lt;br /&gt;
    else&lt;br /&gt;
        result = &amp;quot;line &amp;quot;..string.sub(err, elipsisIndex)&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return result&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- The error handler to provide to xpcall&lt;br /&gt;
local function errorHandler(err)&lt;br /&gt;
    -- The stack trace at this point is:&lt;br /&gt;
    -- 1: this error handler (must not be reported), &lt;br /&gt;
    -- 2: C function calling the handler (kept for security)&lt;br /&gt;
    -- 3: the error source&lt;br /&gt;
    err = formatError(err, 1);&lt;br /&gt;
&lt;br /&gt;
    -- Show a popup to the user&lt;br /&gt;
    local str = L(&amp;quot;Oops, an error occured:&amp;quot;)..&amp;quot;[NEWLINE][ICON_PIRATE] &amp;quot;..err;&lt;br /&gt;
    Events.SerialEventGameMessagePopup( { Type = ButtonPopupTypes.BUTTONPOPUP_TEXT, Data1 = 800, Option1 = true, Text = str } );&lt;br /&gt;
&lt;br /&gt;
    -- Restore things up here when needed. Beware to not cause any error as it would cause an infinite recursive call up to the stack overflow!&lt;br /&gt;
    return false&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Calls someDangerousFunction with the given error handler&lt;br /&gt;
xpcall(someDangerousFunction, errorHandler)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Troubleshooting ==&lt;br /&gt;
The [[Civ5 Useful Programs]] page presents you a number of tools you can use to inspect or modify the game. This is especially useful if you want to quickly reproduce a bug or test something, or to understand what is happening.&lt;br /&gt;
* Let&#039;s say your mod adds a tech but you do not see in the techs panel. There is a FireTuner panel you can use to see a flat list of all the techs in-game.&lt;br /&gt;
* Let&#039;s say your mod adds a unit or a wonder, the IGE mod allows you to quickly create an unit or build that wonder (including the splash screen).&lt;br /&gt;
* Let&#039;s say your mod modifies the yields when the player acquire a specific tech. Once again IGE allows you to grant you that tech and see how the yields are modified.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Configuration ==&lt;br /&gt;
Look for the following files under &amp;lt;code&amp;gt;My Documents/My Games/Sid Meiers&#039; Civilization V&amp;lt;/code&amp;gt; and open them in a text editor like the notepad (not in a word processor).&lt;br /&gt;
* &#039;&#039;&#039;config.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableTuner&amp;lt;/code&amp;gt; to 1. Civ5 will duplicate the Lua output to FireTuner this one is when present.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;LoggingEnabled&amp;lt;/code&amp;gt; to 1. Civ5 will write log files under the &amp;lt;code&amp;gt;Logs&amp;lt;/code&amp;gt; folder.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableLuaDebugLibrary&amp;lt;/code&amp;gt; to 1. Civ5 will display stack traces on Lua errors and you will be able to use the [http://www.lua.org/manual/5.1/manual.html#pdf-debug.debug debug] object.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugPanel&amp;lt;/code&amp;gt; to 1. By pressing the &#039;&#039;&#039;²&#039;&#039;&#039; key (may be &#039;&#039;&#039;ù&#039;&#039;&#039; or something else depending on your computer&#039;s language) during a game, Civ5 will display a debug panel.&lt;br /&gt;
* &#039;&#039;&#039;usersettings.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugMode&amp;lt;/code&amp;gt; to 1. Needed to enable other features previously mentioned.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=XML-SQL_Cheat_Sheet_(Civ5)&amp;diff=14038</id>
		<title>XML-SQL Cheat Sheet (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=XML-SQL_Cheat_Sheet_(Civ5)&amp;diff=14038"/>
		<updated>2012-09-25T08:44:53Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 XML Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
== Things to remember ==&lt;br /&gt;
* &#039;&#039;&#039;Booleans:&#039;&#039;&#039; SQLite does not have booleans, it uses integers. So do not use &amp;lt;code&amp;gt;true&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;false&amp;lt;/code&amp;gt;, use &amp;lt;code&amp;gt;1&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;0&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Inserting rows ==&lt;br /&gt;
=== XML ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;xml&amp;quot; style=&amp;quot;left:40px;&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
	&amp;lt;Colors&amp;gt;&lt;br /&gt;
            &amp;lt;!-- Inserts a new color --&amp;gt;&lt;br /&gt;
            &amp;lt;Row&amp;gt;&lt;br /&gt;
                &amp;lt;Type&amp;gt;COLOR_CUSTOM&amp;lt;/Type&amp;gt;&lt;br /&gt;
                &amp;lt;Red&amp;gt;0.1&amp;lt;/Red&amp;gt;&lt;br /&gt;
                &amp;lt;Green&amp;gt;0.1&amp;lt;/Green&amp;gt;&lt;br /&gt;
                &amp;lt;Blue&amp;gt;0.1&amp;lt;/Blue&amp;gt;&lt;br /&gt;
                &amp;lt;Alpha&amp;gt;0.45&amp;lt;/Alpha&amp;gt;&lt;br /&gt;
            &amp;lt;/Row&amp;gt;	&lt;br /&gt;
	&amp;lt;/Colors&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== SQL ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;sql&amp;quot;&amp;gt;&lt;br /&gt;
/* Inserts a new color */&lt;br /&gt;
INSERT INTO Colors (Type, Red, Green, Blue, Alpha)&lt;br /&gt;
VALUES (&#039;COLOR_CUSTOM&#039;, 0.1, 0.1, 0.1, 0.45);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Deleting rows ==&lt;br /&gt;
{{Warning}} See [http://forums.civfanatics.com/showthread.php?t=463429 Deleting data and issues, and how to avoid them] if you plan to delete rows and are not aware of the troubles that may arise.&lt;br /&gt;
=== XML ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
	&amp;lt;Colors&amp;gt;&lt;br /&gt;
            &amp;lt;!-- Deletes all colors named COLOR_CUSTOM (there is only one actually) --&amp;gt;&lt;br /&gt;
            &amp;lt;Delete Type=&amp;quot;COLOR_CUSTOM&amp;quot; /&amp;gt;&lt;br /&gt;
            &amp;lt;!-- You can specify as many conditions as you want --&amp;gt;&lt;br /&gt;
            &amp;lt;Delete R=&amp;quot;1&amp;quot; G=&amp;quot;1&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/Colors&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== SQL ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;sql&amp;quot;&amp;gt;&lt;br /&gt;
/* Deletes all colors named TYPE_CUSTOM whose red channel is equal to 1 */&lt;br /&gt;
DELETE FROM Colors&lt;br /&gt;
WHERE Type = &#039;COLOR_CUSTOM&#039; AND Red = 1;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Updating rows ==&lt;br /&gt;
=== XML ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
	&amp;lt;Colors&amp;gt;&lt;br /&gt;
            &amp;lt;!-- Changes the red channel for all colors named COLOR_CUSTOM (there is only one actually)&lt;br /&gt;
            &amp;lt;Update&amp;gt;&lt;br /&gt;
                &amp;lt;Where Type=&amp;quot;COLOR_CUSTOM&amp;quot;/&amp;gt;&lt;br /&gt;
                &amp;lt;Set Red=&amp;quot;1&amp;quot;/&amp;gt;&lt;br /&gt;
            &amp;lt;/Update&amp;gt;&lt;br /&gt;
            &amp;lt;!-- You can specify as many conditions as you want and set as many properties as you want --&amp;gt;&lt;br /&gt;
            &amp;lt;Update&amp;gt;&lt;br /&gt;
                &amp;lt;Where Type=&amp;quot;COLOR_CUSTOM&amp;quot; Red=&amp;quot;0&amp;quot;/&amp;gt;&lt;br /&gt;
                &amp;lt;Set Red=&amp;quot;1&amp;quot; Green=&amp;quot;0&amp;quot;/&amp;gt;&lt;br /&gt;
            &amp;lt;/Update&amp;gt;&lt;br /&gt;
            &amp;lt;!-- As always, formatting rules are relaxed, use what&#039;s the most convenient for you --&amp;gt;&lt;br /&gt;
            &amp;lt;Update&amp;gt;&lt;br /&gt;
                &amp;lt;Where&amp;gt;&lt;br /&gt;
                    &amp;lt;Type&amp;gt;COLOR_CUSTOM&amp;lt;/Type&amp;gt;&lt;br /&gt;
                &amp;lt;/Where&amp;gt;&lt;br /&gt;
                &amp;lt;Set&amp;gt;&lt;br /&gt;
                    &amp;lt;Red&amp;gt;1&amp;lt;/Red&amp;gt;&lt;br /&gt;
                    &amp;lt;Green&amp;gt;1&amp;lt;/Green&amp;gt;&lt;br /&gt;
                &amp;lt;/Set&amp;gt;&lt;br /&gt;
            &amp;lt;/Update&amp;gt;&lt;br /&gt;
        &amp;lt;/Colors&amp;gt;&lt;br /&gt;
&amp;lt;/GameData&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== SQL ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;sql&amp;quot;&amp;gt;&lt;br /&gt;
/* Update all colors whose names are COLOR_CUSTOM and red channel is 0 */&lt;br /&gt;
UPDATE Colors&lt;br /&gt;
SET Red = 1, Green = 0&lt;br /&gt;
WHERE Type = &#039;COLOR_CUSTOM&#039; AND Red = 0;&lt;br /&gt;
&lt;br /&gt;
/* Makes everything brighter */&lt;br /&gt;
UPDATE Colors&lt;br /&gt;
SET Red = Red + 0.1, Green = Green + 0.1, Blue=Blue + 0.1;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== New tables ==&lt;br /&gt;
=== XML ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;xml&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;GameData&amp;gt;&lt;br /&gt;
    &amp;lt;Table Name=&amp;quot;MyColors&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;Column name=&amp;quot;ID&amp;quot; type=&amp;quot;integer&amp;quot; primarykey=&amp;quot;true&amp;quot; autoincrement=&amp;quot;true&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;Column name=&amp;quot;Type&amp;quot; type=&amp;quot;text&amp;quot; notnull=&amp;quot;true&amp;quot; unique=&amp;quot;true&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/Table&amp;gt;&lt;br /&gt;
&amp;lt;/GameData&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== SQL ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;sql&amp;quot;&amp;gt;&lt;br /&gt;
/* Create one new table with two columns */&lt;br /&gt;
CREATE TABLE MyColors( id INTEGER PRIMARY KEY AUTOINCREMENT, Type TEXT UNIQUE );&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== New columns ==&lt;br /&gt;
=== SQL ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;sql&amp;quot;&amp;gt;&lt;br /&gt;
/* Adds one Description column to Colors. */&lt;br /&gt;
ALTER TABLE Colors COLUMN &#039;Description&#039; TEXT DEFAULT NULL;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 XML Files]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Category:Civ5_API_Images&amp;diff=14035</id>
		<title>Category:Civ5 API Images</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Category:Civ5_API_Images&amp;diff=14035"/>
		<updated>2012-09-24T15:42:53Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Images used in the [[Lua and UI Reference|Lua and UI Reference (Civ5)]].&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Images]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=File:SQLiteManager.png&amp;diff=14034</id>
		<title>File:SQLiteManager.png</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=File:SQLiteManager.png&amp;diff=14034"/>
		<updated>2012-09-24T15:40:56Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;:&#039;&#039;&#039;Author:&#039;&#039;&#039; [[User:DonQuich]]&lt;br /&gt;
:&#039;&#039;&#039;License:&#039;&#039;&#039; Public Domain&lt;br /&gt;
:&#039;&#039;&#039;Software:&#039;&#039;&#039; SQLite Manager&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Images]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=File:SQLiteManager.png&amp;diff=14033</id>
		<title>File:SQLiteManager.png</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=File:SQLiteManager.png&amp;diff=14033"/>
		<updated>2012-09-24T15:40:35Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;:&#039;&#039;&#039;Author:&#039;&#039;&#039; [[User:DonQuich]]&lt;br /&gt;
:&#039;&#039;&#039;License:&#039;&#039;&#039; Public Domain&lt;br /&gt;
:&#039;&#039;&#039;Software:&#039;&#039;&#039; SQLite Manager&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=File:ModBuddy.ImportIntoVFS.png&amp;diff=14032</id>
		<title>File:ModBuddy.ImportIntoVFS.png</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=File:ModBuddy.ImportIntoVFS.png&amp;diff=14032"/>
		<updated>2012-09-24T15:39:57Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;:&#039;&#039;&#039;Author:&#039;&#039;&#039; [[User:DonQuich]]&lt;br /&gt;
:&#039;&#039;&#039;License:&#039;&#039;&#039; Public Domain&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Images]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Civ5_Useful_Programs&amp;diff=14031</id>
		<title>Civ5 Useful Programs</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Civ5_Useful_Programs&amp;diff=14031"/>
		<updated>2012-09-24T15:37:27Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page includes information on the Civ5 Modding Tools as well as links to other useful programs.&lt;br /&gt;
&lt;br /&gt;
== SDK ==&lt;br /&gt;
&#039;&#039;&#039;World Builder&#039;&#039;&#039;&lt;br /&gt;
:The stand-alone world builder allows users to create and modify maps and scenarios for Civilization V.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Mod Buddy&#039;&#039;&#039;&lt;br /&gt;
:An editor (IDE) for the XML and Lua elements of the game and allows for the creation, packaging, and uploading of mods. To use it, you have to install the [http://www.microsoft.com/downloads/en/details.aspx?FamilyID=DFBA7AC4-5366-456E-ABD6-0E3E6BA83B7C&amp;amp;displaylang=enMicrosoft Visual Studio 2010 Shell (Isolated) Redistributable Package].&lt;br /&gt;
:[http://forums.civfanatics.com/showthread.php?t=387554 Installing ModBuddy Extensions]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Nexus&#039;&#039;&#039;&lt;br /&gt;
:A collection of tools to to work with the art in Civilization V.&lt;br /&gt;
:[http://forums.civfanatics.com/showthread.php?t=386972 Initial Look at Nexus, 3D Unit Art, and Reskinning]&lt;br /&gt;
:Note that Photoshop templates for icons are also bundled in the SDK, under the &#039;&#039;Art&#039;&#039; folder (in &#039;&#039;Programs Files/Steam/...&#039;&#039;).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;FireTuner&#039;&#039;&#039;&lt;br /&gt;
:An advanced debugging terminal. It displays the lua output, provides an interactive console and can be simply extended with custom controls and tables.&lt;br /&gt;
:Do not forget to modify your *.ini files, see [[Debugging (Civ5)#Configuration|Debugging#Configuration]].&lt;br /&gt;
:[http://forums.civfanatics.com/showthread.php?t=399821 Simple Tuner Modifications]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Digging the source code and the data tables ==&lt;br /&gt;
Since the documentation is sparse, you need a tool to quickly inspect the civ5 source and data files and search in all of them at once. See also [http://forums.civfanatics.com/showthread.php?t=475076 this comparison of search tools].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Notepad++&#039;&#039;&#039;&lt;br /&gt;
:A great and renowned text editor with a &amp;quot;search in all files&amp;quot; feature (hit ctrl + shift + f). Used by many developers around the world. [http://sourceforge.net/projects/notepad-plus/ Download].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Browsing the art assets ==&lt;br /&gt;
&#039;&#039;&#039;Dragon unpacker&#039;&#039;&#039;&lt;br /&gt;
:Can extract the Firaxis packages (.fpk files). [http://sourceforge.net/projects/dragonunpacker/ Download].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;DDS Unpacker&#039;&#039;&#039;&lt;br /&gt;
:Some DDS files have been compressed even further and look messed up if you open them in an image viewer. This tool rebuilds them. [http://forums.civfanatics.com/showthread.php?t=389316 Download].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;XnView&#039;&#039;&#039;&lt;br /&gt;
:An images browser to get a quick look at all the DDS files to spot the one you&#039;re looking for. [http://www.xnview.com/en/download.html Download].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;FireTuner: Textures Viewer&#039;&#039;&#039;&lt;br /&gt;
:A FireTuner panel to browse most of the game&#039;s textures. [http://forums.2kgames.com/showthread.php?118165-MOD-LiveTuner-Texture-Viewer Download].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;FireTuner: Icons Viewer&#039;&#039;&#039;&lt;br /&gt;
:A FireTuner panel to browse the game&#039;s icons. [http://forums.2kgames.com/showthread.php?118055-MOD-LiveTuner-Icon-Viewer Download].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Creating textures ==&lt;br /&gt;
&#039;&#039;&#039;NVidia Texture Tools for Photoshop&#039;&#039;&#039;&lt;br /&gt;
:A Photoshop plugin to save textures under the DDS format. [http://developer.nvidia.com/content/nvidia-texture-tools-adobe-photoshop Download]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Paint.net&#039;&#039;&#039;&lt;br /&gt;
:An easy-to-use and moderately powerful open-source image editor for Windows that natively supports the DDS format. [http://www.getpaint.net/ Download]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Testing and debugging ==&lt;br /&gt;
&lt;br /&gt;
=== SQLite tools ===&lt;br /&gt;
Anytime it starts a game, Civilization V saves a SQLite snapshot of the database, including the changes made by mods, under &#039;&#039;Civ5DebugDatabase.db&#039;&#039;. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;SQLite Manager&#039;&#039;&#039;&lt;br /&gt;
:A Firefox plug-in, slightly more powerful than the previous tool. [https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/ Download]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;SQLiteSpy&#039;&#039;&#039;&lt;br /&gt;
:A Windows software to inspect the SQLite files. [http://www.yunqa.de/delphi/doku.php/products/sqlitespy/index Download]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;SQLite Browser&#039;&#039;&#039;&lt;br /&gt;
:A Windows software to inspect the SQLite files. [http://sqlitebrowser.sourceforge.net/screenshots.html Download]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Cheating tools and game inspectors ===&lt;br /&gt;
&#039;&#039;&#039;In-game Editor (IGE)&#039;&#039;&#039;&lt;br /&gt;
:Add or remove units, cities, resources, change the terrain, trigger wars, etc. Convenient to quickly test your mod. [http://forums.civfanatics.com/showthread.php?t=436912 Download] (also on the Steam Workshop).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;FireTuner: Techs and policies panel&#039;&#039;&#039;&lt;br /&gt;
:A FireTuner panel to list, grant and revoke techs and policies. [http://forums.2kgames.com/showthread.php?108533-MOD-LiveTuner-Tech-and-Policy-Panels Download].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14030</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14030"/>
		<updated>2012-09-24T15:30:23Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== About Lua ==&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Syntax cheatsheet==&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Basics ==&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
* &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
* &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned. This speeds up comparisons but it makes allocation of new strings slower.&lt;br /&gt;
* &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
* &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and other limitations. Now the Civ5 API tend to return regular tables whose metatable is of type userdata, this allows us to use the provided objects as regular Lua tables.&lt;br /&gt;
* &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
* &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strict equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is stricter than C and far stricter than PHP for example.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal.&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal.&lt;br /&gt;
&lt;br /&gt;
Regarding tables and C-made objects, they are compared by reference.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
a = { 5 }&lt;br /&gt;
b = { 5 }&lt;br /&gt;
c = a&lt;br /&gt;
assert(a == c) -- OK&lt;br /&gt;
assert(a == b) -- ERROR&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals, globals and includes ===&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* Another specificities of locals: they&#039;re only visible after the point they have been declared in the file, while globals are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Semi-advanced topics ==&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advanced topics==&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the running coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14029</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14029"/>
		<updated>2012-09-24T15:29:05Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== About Lua ==&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Syntax cheatsheet==&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Basics ==&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
* &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
* &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned. This speeds up comparisons but it makes allocation of new strings slower.&lt;br /&gt;
* &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
* &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and other limitations. Now the Civ5 API tend to return regular tables whose metatable is of type userdata, this allows us to use the provided objects as regular Lua tables.&lt;br /&gt;
* &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
* &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strict equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is stricter than C and far stricter than PHP for example.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal.&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal.&lt;br /&gt;
&lt;br /&gt;
Regarding tables and C-made objects, they are compared by reference.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
a = { 5 }&lt;br /&gt;
b = { 5 }&lt;br /&gt;
c = a&lt;br /&gt;
assert(a == c) -- OK&lt;br /&gt;
assert(a == b) -- ERROR&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals, globals and includes ===&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* Another specificities of locals: they&#039;re only visible after the point they have been declared in the file, while globals are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Semi-advanced topics ==&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advanced topics==&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14028</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14028"/>
		<updated>2012-09-24T15:27:30Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== About Lua ==&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Syntax cheatsheet==&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Basics ==&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
* &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
* &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned. This speeds up comparisons but it makes allocation of new strings slower.&lt;br /&gt;
* &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
* &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and other limitations. Now the Civ5 API tend to return regular tables whose metatable is of type userdata, this allows us to use the provided objects as regular Lua tables.&lt;br /&gt;
* &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
* &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strict equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is stricter than C and far stricter than PHP for example.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal.&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal.&lt;br /&gt;
&lt;br /&gt;
Regarding tables and C-made objects, they are compared by reference.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
a = { 5 }&lt;br /&gt;
b = { 5 }&lt;br /&gt;
c = a&lt;br /&gt;
assert(a == c) -- OK&lt;br /&gt;
assert(a == b) -- ERROR&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals, globals and includes ===&lt;br /&gt;
* For a documentation on the &#039;&#039;&#039;include&#039;&#039;&#039; statement, see [[Specificities of the Lua implementation in Civ5#Include]].&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* Another specificities of locals: they&#039;re only visible after the point they have been declared in the file, while globals are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Semi-advanced topics ==&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advanced topics==&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|UIElement|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14027</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14027"/>
		<updated>2012-09-24T15:26:37Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== About Lua ==&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Syntax cheatsheet==&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Basics ==&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
* &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
* &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned. This speeds up comparisons but it makes allocation of new strings slower.&lt;br /&gt;
* &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
* &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and other limitations. Now the Civ5 API tend to return regular tables whose metatable is of type userdata, this allows us to use the provided objects as regular Lua tables.&lt;br /&gt;
* &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
* &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strict equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is stricter than C and far stricter than PHP for example.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal.&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal.&lt;br /&gt;
&lt;br /&gt;
Regarding tables and C-made objects, they are compared by reference.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
a = { 5 }&lt;br /&gt;
b = { 5 }&lt;br /&gt;
c = a&lt;br /&gt;
assert(a == c) -- OK&lt;br /&gt;
assert(a == b) -- ERROR&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals, globals and includes ===&lt;br /&gt;
* For a documentation on the &#039;&#039;&#039;include&#039;&#039;&#039; statement, see [[Specificities of the Lua implementation in Civ5#Include]].&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* Another specificities of locals: they&#039;re only visible after the point they have been declared in the file, while globals are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Semi-advanced topics ==&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advanced topics==&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking.&lt;br /&gt;
* However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|Context|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14026</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14026"/>
		<updated>2012-09-24T15:24:25Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== About Lua ==&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Syntax cheatsheet==&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Basics ==&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
* &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
* &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned. This speeds up comparisons but it makes allocation of new strings slower.&lt;br /&gt;
* &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
* &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and other limitations. Now the Civ5 API tend to return regular tables whose metatable is of type userdata, this allows us to use the provided objects as regular Lua tables.&lt;br /&gt;
* &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
* &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strict equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is stricter than C and far stricter than PHP for example.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal.&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal.&lt;br /&gt;
&lt;br /&gt;
Regarding tables and C-made objects, they are compared by reference.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
a = { 5 }&lt;br /&gt;
b = { 5 }&lt;br /&gt;
c = a&lt;br /&gt;
assert(a == c) -- OK&lt;br /&gt;
assert(a == b) -- ERROR&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals, globals and includes ===&lt;br /&gt;
* For a documentation on the &#039;&#039;&#039;include&#039;&#039;&#039; statement, see [[Specificities of the Lua implementation in Civ5#Include]].&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* Another specificities of locals: they&#039;re only visible after the point they have been declared in the file, while globals are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Semi-advanced topics ==&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advanced topics==&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking. However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|Context|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14025</id>
		<title>Lua introduction for confirmed developers</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Lua_introduction_for_confirmed_developers&amp;diff=14025"/>
		<updated>2012-09-24T15:21:50Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Lua and UI Reference (Civ5)|Lua and UI Reference]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== About Lua ==&lt;br /&gt;
===Lua, not LUA===&lt;br /&gt;
This is a Portuguese word meaning &amp;quot;moon&amp;quot;, not an acronym. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Presentation===&lt;br /&gt;
Lua is an interpreted, dynamically typed, multi-paradigm language. It was designed in 1993 with the following objectives in mind:&lt;br /&gt;
* Extensible semantics. A small set of features allows the support of multiple paradigms, from functional programming to object programming. For example, while inheritance is not natively supported, it can be easily set up through metatables. The same features allow events in civ5 to behave both as functions and objects with Add and Remove methods.&lt;br /&gt;
* Highly portable. The con is a lightweight and somewhat lacking API.&lt;br /&gt;
* Easy to embed and to interface from other languages.&lt;br /&gt;
* Well suited for data description (&#039;&#039;à la&#039;&#039; JSON).&lt;br /&gt;
* A beginners-friendly syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Performances===&lt;br /&gt;
As usual with interpreted and dynamically typed languages (hereby abusively named &amp;quot;scripting languages&amp;quot;), expect a 10 to 100 order of magnitude in performances decrease when compared to compiled and statically typed languages like C, C++ or C#. While it is possible for scripting languages to drastically improve the performances through more or less sophisticated means (expression trees/opcodes caching, JIT compiler, type inference to perform static resolutions), no such solution has been used in Civ5 (aside, probably, of the caching). And while an external JIT library exists, it causes compatibility problems with most mods using Lua.&lt;br /&gt;
&lt;br /&gt;
That being said, Lua is still pretty good for a scripting language, better than the Python implementation from Civ4 for example. And all in all, it is fast enough for most of what modders want to achieve without the need to compromise code elegance, readability and maintainability for performances. So keep in mind that &amp;quot;premature optimization is the root of all evil&amp;quot; (Donald Knuth).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Syntax cheatsheet==&lt;br /&gt;
=== Basics ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Literals&lt;br /&gt;
local x = 5&lt;br /&gt;
local x = 5.0&lt;br /&gt;
local x = nil       -- A nil value is the same as an undefined value&lt;br /&gt;
local x = true&lt;br /&gt;
local x = false&lt;br /&gt;
&lt;br /&gt;
-- Strings (single and double quotes can be used indifferently, there is no difference)&lt;br /&gt;
local x = &amp;quot;five&amp;quot;    &lt;br /&gt;
local x = &#039;five&#039;    &lt;br /&gt;
local x = &amp;quot;five\n&amp;quot;  -- Escape characters with &amp;quot;\&amp;quot;.&lt;br /&gt;
local x = [[Five is a number.&lt;br /&gt;
Did you know?]]     -- Multi-line string: equivalent to &amp;quot;Five is number.\nDid you know?&amp;quot;&lt;br /&gt;
&lt;br /&gt;
-- Globals versus locals&lt;br /&gt;
x = 5               -- For globals, assigning is declaring.&lt;br /&gt;
local x = 5         &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Operators ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local x = a or b&lt;br /&gt;
local x = a and b&lt;br /&gt;
&lt;br /&gt;
local x = &amp;quot;hello &amp;quot;..&amp;quot;world&amp;quot; .. &amp;quot;!&amp;quot;    -- concatenation: two dots&lt;br /&gt;
local x = 4..5                        -- Result is &amp;quot;45&amp;quot;. On concatenation, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = (a + b - d) * f ^ g % h     -- ^ is exponentiation, % is modulo&lt;br /&gt;
local x = &amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;                   -- Result is 9. On arithmetic operations, conversions occur.&lt;br /&gt;
&lt;br /&gt;
local x = a == b -- equality          -- True only if a and b have the same values and types.&lt;br /&gt;
local x = a ~= b -- inequality&lt;br /&gt;
&lt;br /&gt;
local x = ((a &amp;lt;= b) == not (a &amp;gt; b)) == ((a &amp;gt;= b) == not (a &amp;lt; b))&lt;br /&gt;
local x = &amp;quot;abc&amp;quot; &amp;lt; &amp;quot;def&amp;quot;               -- Byte-wise comparison, not Unicode-compliant. Use Locale&#039;s methods instead.&lt;br /&gt;
&lt;br /&gt;
local x = #&amp;quot;abc&amp;quot;                      -- Returns 3, the number of bytes in the string (3 characters, 1 byte each).&lt;br /&gt;
local x = #&amp;quot;您好世界&amp;quot;                   -- Returns 8, the number of bytes in the string (4 characters, 2 bytes each).&lt;br /&gt;
local x = #SomeTable                  -- Returns the biggest integer key in the table, or nil if there is no integer key.&lt;br /&gt;
&lt;br /&gt;
-- No increment operator (++ --), no binary-assign operator (+= *=), no ternary operator (? :), no coalescence operator (??)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Tables and multiple assignments ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Table declaration&lt;br /&gt;
SomeTable = {}  &lt;br /&gt;
&lt;br /&gt;
SomeArray = { &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot; }  &lt;br /&gt;
    -- 1 =&amp;gt; &amp;quot;abc&amp;quot;, 2 =&amp;gt; &amp;quot;def&amp;quot;&lt;br /&gt;
&lt;br /&gt;
SomeComplexTable = { name = &amp;quot;John&amp;quot;, surname = &amp;quot;Doe&amp;quot;, age = 25, 43, [7] = 8 } &lt;br /&gt;
    -- &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;surname&amp;quot; =&amp;gt; &amp;quot;Doe&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25, 1 =&amp;gt; 43, 7 =&amp;gt; 8.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Member access (all equivalent)&lt;br /&gt;
SomeTable.SomeMember = 5&lt;br /&gt;
SomeTable[&amp;quot;SomeMember&amp;quot;] = 5&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple assignment&lt;br /&gt;
-- Both statements are equivalent since SomeArray contains &amp;quot;abc&amp;quot; and &amp;quot;def&amp;quot;.&lt;br /&gt;
local x, y = &amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;&lt;br /&gt;
local x, y = unpack(SomeArray) &lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Functions ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Functions declarations (all equivalent)&lt;br /&gt;
function HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end    &lt;br /&gt;
    -- Functions are first-class objects and can be assigned like any other value!&lt;br /&gt;
&lt;br /&gt;
-- Methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorld(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
SomeTable.HelloWorld = function(a, b) print(&amp;quot;Hello world&amp;quot;) end&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods declarations (all equivalent)&lt;br /&gt;
SomeTable.HelloWorldInstanced(self, a, b) print(self.SomeMember) end&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b) print(self.SomeMember) end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Functions and methods calls&lt;br /&gt;
HelloWorld(a)                  -- b will be nil in the function&lt;br /&gt;
HelloWorld(a, b)&lt;br /&gt;
SomeTable.HelloWorld(a, b)&lt;br /&gt;
&lt;br /&gt;
-- Instanced methods calls (all equivalent)&lt;br /&gt;
SomeTable:HelloWorldInstanced(a, b)&lt;br /&gt;
SomeTable.HelloWorldInstanced(SomeTable, a, b)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Multiple return values&lt;br /&gt;
function func(a, b) return a, b end&lt;br /&gt;
local x, y, z = func(5, 6)        -- Assigns 5 to x and 6 to y, z will be nil&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
-- Variable arguments&lt;br /&gt;
function SomeFunc(a, b, ...)&lt;br /&gt;
   print(a)&lt;br /&gt;
   print(b)&lt;br /&gt;
   for i, v in ipairs(arg) do   -- arg is a keyword for a table containing the variable arguments&lt;br /&gt;
      print(v)&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
SomeFunc(1, 2, 3, 4, 5)         -- prints 1, 2, 3, 4, 5&lt;br /&gt;
SomeFunc(1, 2)                  -- prints 1, 2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Control flow ===&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- If &lt;br /&gt;
if name == &amp;quot;Wu Zetian&amp;quot; then&lt;br /&gt;
    print(&amp;quot;Hello China&amp;quot;)&lt;br /&gt;
elseif name == &amp;quot;Napoleon&amp;quot; then   -- &amp;quot;elseif&amp;quot;, not &amp;quot;else if&amp;quot;. Beware C developers!&lt;br /&gt;
    print(&amp;quot;Hello France&amp;quot;)&lt;br /&gt;
else                             -- no &amp;quot;then&amp;quot; after &amp;quot;else&amp;quot;!&lt;br /&gt;
    print(&amp;quot;Hello unknown&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- For loop (with counter)&lt;br /&gt;
for i = 1, 8 do print(i) end     -- Prints 1, 2, 3, 4, 5, 6, 7, 8&lt;br /&gt;
for i = 1, 8, 2 do print(i) end  -- Prints 1, 3, 5, 7&lt;br /&gt;
&lt;br /&gt;
-- For loop (with iterator)&lt;br /&gt;
for playerID, pPlayer in pairs(Players) do    -- Prints 1 Wu Zetian, 2 Napoleon, ...&lt;br /&gt;
    print(playerID, pPlayer:GetName()) &lt;br /&gt;
end  &lt;br /&gt;
for plot in Plots() do                        -- Prints 0 0, 0 1, 0 2, ...&lt;br /&gt;
    print(plot:GetX(), plot:GetY()) &lt;br /&gt;
end  &lt;br /&gt;
&lt;br /&gt;
-- While (i will be 5 in the end)&lt;br /&gt;
while i &amp;lt; 5 do &lt;br /&gt;
   i = i + 1&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Repeat until (i will be 5 in the end)&lt;br /&gt;
repeat&lt;br /&gt;
   i = i + 1&lt;br /&gt;
until i == 5&lt;br /&gt;
&lt;br /&gt;
-- Infinite loops&lt;br /&gt;
-- Lua supports &amp;quot;break&amp;quot; for all loops but not &amp;quot;continue&amp;quot; instruction does not exist!&lt;br /&gt;
do&lt;br /&gt;
   i = i + 1&lt;br /&gt;
   if i &amp;gt; 5 then break end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Basics ==&lt;br /&gt;
=== Type system ===&lt;br /&gt;
You can get a variable&#039;s type by using the &#039;&#039;&#039;type&#039;&#039;&#039; function. It takes any value and returns a string. Here are the possible results:&lt;br /&gt;
* &#039;&#039;&#039;nil&#039;&#039;&#039;: Lua makes do distinction between an undefined variable and a variable with a nil value. Assigning nil to a variable or table member is equivalent to undefining it.&lt;br /&gt;
* &#039;&#039;&#039;number&#039;&#039;&#039;: a 64 bits floating-point number. Lua has no support for integers and only use floating-points. See also [[#No integer type]].&lt;br /&gt;
* &#039;&#039;&#039;string&#039;&#039;&#039;: your usual string of characters. In Lua all strings are interned. This speeds up comparisons but it makes allocation of new strings slower.&lt;br /&gt;
* &#039;&#039;&#039;boolean&#039;&#039;&#039;: true or false obviously.&lt;br /&gt;
* &#039;&#039;&#039;table&#039;&#039;&#039;: any table.&lt;br /&gt;
* &#039;&#039;&#039;userdata&#039;&#039;&#039;: objects defined in C for use in Lua. They may not be enumerated through pairs and other limitations. Now the Civ5 API tend to return regular tables whose metatable is of type userdata, this allows us to use the provided objects as regular Lua tables.&lt;br /&gt;
* &#039;&#039;&#039;function&#039;&#039;&#039;: remember that functions are first-class objects in Lua.&lt;br /&gt;
* &#039;&#039;&#039;thread&#039;&#039;&#039;: coroutines actually. Lua does not support threads.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implicit conversions ===&lt;br /&gt;
* Whenever you concatenate two values (and possibly when you invoke a standard function that takes a string), an automatic conversion to string occurs, as if you had used the &#039;&#039;&#039;tostring&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;4..5&amp;lt;/code&amp;gt; returns &amp;quot;45&amp;quot;.&lt;br /&gt;
* Whenever you perform an arithmetic operation, the operands are both converted to numbers, as if you had used the &#039;&#039;&#039;tonumber&#039;&#039;&#039; function. The expression &amp;lt;code&amp;gt;&amp;quot;4&amp;quot; + &amp;quot;5&amp;quot;&amp;lt;/code&amp;gt; returns 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Strict equality comparisons ===&lt;br /&gt;
&#039;&#039;&#039;Two values are equal only if their types are the same.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is stricter than C and far stricter than PHP for example.&lt;br /&gt;
* 4 is not equal to &amp;quot;4&amp;quot;. (number type and string type). In PHP they would be equal. &lt;br /&gt;
* 0 is not equal to false (number type and bool type). In C they would be equal.&lt;br /&gt;
* 0 is not equal to nil. (number type and nil type). In C they would be equal.&lt;br /&gt;
&lt;br /&gt;
Regarding tables and C-made objects, they are compared by reference.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
a = { 5 }&lt;br /&gt;
b = { 5 }&lt;br /&gt;
c = a&lt;br /&gt;
assert(a == c) -- OK&lt;br /&gt;
assert(a == b) -- ERROR&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Boolean logic ===&lt;br /&gt;
&#039;&#039;&#039;Anything that is neither false nor nil is evaluated to true.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is pretty simple. Especially, an empty string or the zero number are evaluated to true.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
if 0 then print(&amp;quot;hello world&amp;quot;) end -- prints hello world&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now regarding the and/or operators, two rules to remember:&lt;br /&gt;
* &#039;&#039;&#039;The right operand is only evaluated when needed.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;false and x()&amp;lt;/code&amp;gt; does not call x() since the result will be false anyway.&lt;br /&gt;
** &amp;lt;code&amp;gt;true or x()&amp;lt;/code&amp;gt; does not call x() since the result will be true anyway.&lt;br /&gt;
* &#039;&#039;&#039;The result is the last operand to have been evaluated.&#039;&#039;&#039;&lt;br /&gt;
** &amp;lt;code&amp;gt;x() and y()&amp;lt;/code&amp;gt; returns x() if it was false, y() otherwise.&lt;br /&gt;
** &amp;lt;code&amp;gt;x() or y()&amp;lt;/code&amp;gt; returns x() if it was true, y() otherwise.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ternary and coalescence statements ===&lt;br /&gt;
We can exploit the and/or operators behavior:&lt;br /&gt;
* &#039;&#039;&#039;Coalescence:&#039;&#039;&#039; &amp;lt;code&amp;gt;x or y&amp;lt;/code&amp;gt;. It returns x if x is neither nil nor false, y otherwise.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if x then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &#039;&#039;&#039;Ternary:&#039;&#039;&#039; &amp;lt;code&amp;gt;condition and x or y&amp;lt;/code&amp;gt; (as long as x is not nil or false). It returns x if condition was true, y if it was false. &lt;br /&gt;
:Indeed the expression becomes: &amp;lt;code&amp;gt;(condition and x) or y&amp;lt;/code&amp;gt;. If condition is true the &#039;&#039;&#039;and&#039;&#039;&#039; operator returns x, and since x is true, y is not evaluated and &#039;&#039;&#039;or&#039;&#039;&#039; returns x.&lt;br /&gt;
:In other words &amp;lt;code&amp;gt;result = condition and x or y&amp;lt;/code&amp;gt; is equivalent to: &amp;lt;code&amp;gt;if condition then result = x else result = y end&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Arrays versus tables ===&lt;br /&gt;
&#039;&#039;&#039;In Lua, an array is a table whose keys are integers.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Since this is a common programming pattern, a number of things are designed for arrays:&lt;br /&gt;
* &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; starts at index 1, up to index 3. Arrays typically start at 1.&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({}, &amp;quot;abc&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided empty table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;}, &amp;quot;ghi&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.insert({&amp;quot;abc&amp;quot;, &amp;quot;ghi&amp;quot;}, 2, &amp;quot;def&amp;quot;)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;table.remove({&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}, 2)&amp;lt;/code&amp;gt; will transform the provided table to &amp;lt;code&amp;gt;{&amp;quot;abc&amp;quot;, &amp;quot;&amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt;&lt;br /&gt;
* &amp;lt;code&amp;gt;#{&amp;quot;abc&amp;quot;, &amp;quot;def&amp;quot;, &amp;quot;ghi&amp;quot;}&amp;lt;/code&amp;gt; returns 3, the biggest integer key.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Ipairs versus pairs ===&lt;br /&gt;
You could say that &#039;&#039;&#039;pairs&#039;&#039;&#039; is for table and &#039;&#039;&#039;ipairs&#039;&#039;&#039; for arrays.&lt;br /&gt;
* &#039;&#039;&#039;Pairs&#039;&#039;&#039; enumerate all the key/value pairs in an unordered matter.&lt;br /&gt;
* &#039;&#039;&#039;Ipairs&#039;&#039;&#039; only enumerates the key/value pairs for consecutive integer keys, in an ascending order, starting from 1 up to the largest key. If at some point a key is missing, the enumeration stops.&lt;br /&gt;
::It does not matter whether the table was crated with table.insert or directly by inserting the values through, for example &amp;lt;code&amp;gt;table[i] = value&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Produces: { 1 =&amp;gt; &amp;quot;one&amp;quot;, 2 =&amp;gt; &amp;quot;two&amp;quot;, 4 =&amp;gt; &amp;quot;four&amp;quot;, &amp;quot;name&amp;quot; =&amp;gt; &amp;quot;John&amp;quot;, &amp;quot;age&amp;quot; =&amp;gt; 25 }&lt;br /&gt;
local t = { &amp;quot;one&amp;quot;, &amp;quot;two&amp;quot;, name = &amp;quot;John&amp;quot;, age = 25, [4] = &amp;quot;four&amp;quot; }&lt;br /&gt;
&lt;br /&gt;
-- Will print (for example, the order is undetermined): &amp;quot;name&amp;quot;, 2, 4, &amp;quot;age&amp;quot;, 1&lt;br /&gt;
for k in pairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Will print 1, 2&lt;br /&gt;
for k in ipairs(t) do print(k) end&lt;br /&gt;
&lt;br /&gt;
-- Both ipairs and pairs return a key and a value, so you could also use:&lt;br /&gt;
for k, v in pairs(t) do print(k, v) end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Semicolons and line breaks ===&lt;br /&gt;
&#039;&#039;&#039;Statements need to be separated either by a line break or a semicolon.&#039;&#039;&#039;&lt;br /&gt;
* You can use both a semicolon and a line break but then the semicolon is redundant and not required, although it does not cause any problem.&lt;br /&gt;
* Line breaks can also be freely added about everywhere and behave as whitespaces most of the time (you can add them after most keywords for example, so you can keep if...then...end structures on one line or split them across multiple lines).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Locals, globals and includes ===&lt;br /&gt;
* For a documentation on the &#039;&#039;&#039;include&#039;&#039;&#039; statement, see [[Specificities of the Lua implementation in Civ5#Include]].&lt;br /&gt;
* The include statement allows you to include a lua file into another one (see [[Specificities of the Lua implementation in Civ5]]). When you do so, the globals defined in the included file are imported in the parent file. However the local variables are only visible from within the file that declared them.&lt;br /&gt;
* Another specificities of locals: they&#039;re only visible after the point they have been declared in the file, while globals are always visible. An example is worth thousand of words.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function Func1()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local someLocal = &amp;quot;foo&amp;quot;&lt;br /&gt;
function Func2()&lt;br /&gt;
   print(someLocal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
   print(someGlobal or &amp;quot;nil&amp;quot;)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
someGlobal = &amp;quot;global&amp;quot;&lt;br /&gt;
someLocal = &amp;quot;local&amp;quot;&lt;br /&gt;
Func1()  -- prints &amp;quot;nil&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned but not visible from Func1&lt;br /&gt;
Func2()  -- prints &amp;quot;local&amp;quot;, then &amp;quot;global&amp;quot;: someLocal is assigned and visible from Func2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Performances-wise, Lua first searches a variable name in the current scope, then in the parent scope, etcetera until it reaches the highest scope, and finally it searches the global scope. So the deeper a local is declared, the faster it is accessed. On the contrary, globals are the slowest to retrieve.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Semi-advanced topics ==&lt;br /&gt;
=== Closures ===&lt;br /&gt;
&#039;&#039;&#039;Closures are functions that embed variables that are persisted across calls.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
This is typically achieved through a &amp;quot;parent&amp;quot; function that declares a local &amp;quot;closed&amp;quot; variable and returns another child &amp;quot;closure&amp;quot; function using this local. The &amp;quot;closed&amp;quot; variable is then unreachable for anyone but the &amp;quot;closure&amp;quot;. And since it the &amp;quot;closed&amp;quot; variable is not in the &amp;quot;closure&amp;quot;&#039;s scope, it is not reinitialized on every call of &amp;quot;closure&amp;quot;.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function GiveMeAFunc()         -- the parent function&lt;br /&gt;
   local x = 0                 -- the closed variable&lt;br /&gt;
   return function()           -- the closure function embedding &amp;quot;closed&amp;quot;&lt;br /&gt;
       x = x + 1&lt;br /&gt;
       return closure&lt;br /&gt;
   end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local func = GiveMeAFunc()&lt;br /&gt;
print(func()) -- Prints 1&lt;br /&gt;
print(func()) -- Prints 2&lt;br /&gt;
print(func()) -- Prints 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Iterators ===&lt;br /&gt;
&#039;&#039;&#039;Iterators are functions for use in &amp;lt;code&amp;gt;for...in&amp;lt;/code&amp;gt; loops.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Let&#039;s consider the following code: &amp;lt;code&amp;gt;for var1, var2, var3 in iterable() do&amp;lt;/code&amp;gt;.&lt;br /&gt;
* iterable has the following signature: &amp;lt;code&amp;gt;iterator, state, var1 iterable()&amp;lt;/code&amp;gt;. It returns a function, a state, and the initial value of var1. &lt;br /&gt;
* iterator has the following signature: &amp;lt;code&amp;gt;var1, var2, var3 iterator(state, var1)&amp;lt;/code&amp;gt;. It takes the state and the last value of var1 and returns var1, var2 and var3.&lt;br /&gt;
* The loop stops when var1 is nil.&lt;br /&gt;
* The for...in loop is equivalent to:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local iterator, state, var1, var2, var3&lt;br /&gt;
iterator, state, var1 = iterable()&lt;br /&gt;
do&lt;br /&gt;
   var1, var2, var3 = iterator(state, var1)&lt;br /&gt;
   if var1 == nil then break end&lt;br /&gt;
&lt;br /&gt;
   -- Inserts here the user code defined in the for..in loop&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
* Note that we used var1, var2 and var3 for the example but there is no restriction to the number of variables. You could have one or hundred.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#039;s write the &amp;quot;ipairs&amp;quot; function.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local iterator = function(table, key)   -- The iterator function&lt;br /&gt;
        key = key + 1&lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator, table, 0&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The same with closures: it&#039;s easier.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local function ipairs(table)                -- The iterable function&lt;br /&gt;
    local key = 0                           -- Both &amp;quot;table&amp;quot; and &amp;quot;key&amp;quot; are closed variables.&lt;br /&gt;
    local iterator = function()             -- The iterator function, a closure: it ignores the arguments provided to it&lt;br /&gt;
        key = key + 1                     &lt;br /&gt;
        return key, table[key]&lt;br /&gt;
    end&lt;br /&gt;
    return iterator                         -- No need to return anything since we do not require any argument.&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== No integer type ===&lt;br /&gt;
&#039;&#039;&#039;Lua offers no support for integers and only has a 64-bits floating point number type.&#039;&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
Actually, this is only troublesome for a few algorithms that use very large integers (&amp;gt;2^52) or require fast integer arithmetics. But many developers misunderstand floating points and believe the problem is broader than it is. For example, does the following assertion surprise you at least a bit: &amp;quot;any integer smaller than 2^52 can be accurately represented with a 64-bits floating point without any error&amp;quot;? If it did, you suffer from some misconceptions and you should better read carefully what&#039;s coming.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Many developers are confusing rounding errors with representation errors. &lt;br /&gt;
* &#039;&#039;&#039;Rounding errors&#039;&#039;&#039; actually only happen if you need a very high number of digits to represent a number. For example if you are adding a very large number with a small number. Rounding errors are very rarely encountered in day to day to applications. Actually most developers work their whole career without ever encountering them.&lt;br /&gt;
* &#039;&#039;&#039;Representation errors&#039;&#039;&#039; are the real problem: 0.1 is expressed in a decimal basis, but it has no finite representation in binary: it requires an infinite number of binary digits. This means that if you write 0.1 in your code it will be translated to a binary number close enough from 0.1 bot not exactly equal to it. So if you sum ten times 0.1, you sill sum ten times something close from 0.1 and the result will not be 1.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;So the real problem for most developers only lies in the decimal-binary conversion that arises when you manipulate numbers in your code that do not have a finite representation in binary. As long as you do not use such numbers, there will be no problem. And here are the good news: integers do not suffer from any representation problem!&#039;&#039;&#039; Indeed, any integer can be represented with a finite number of binary digits. This is why the absence of an integer type typically does not cause problems, minus the performance penalty.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are a few examples to illustrate that point.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- This loop works as intended: no representation error and the upper bound is far below 2^52.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 10000000000, 1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 10000000001)&lt;br /&gt;
&lt;br /&gt;
-- This loop works as intended: 1/16 is a floating-point with an exact representation in binary&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 1/16 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 17/16)&lt;br /&gt;
&lt;br /&gt;
-- This loop does NOT work as intended: 0.1 does not have an exact representation in binary. &lt;br /&gt;
-- It&#039;s the same for Lua, C and almost every programming language.&lt;br /&gt;
local sum = 0&lt;br /&gt;
for i = 0, 1, 0.1 do sum = sum + 1 end&lt;br /&gt;
assert(sum == 1.1) -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Errors management ===&lt;br /&gt;
Lua offers a error handling mechanism similar to exception handling but unfortunately not very convenient.&lt;br /&gt;
* Errors are thrown using the &#039;&#039;&#039;error&#039;&#039;&#039; function. It takes a string and it immediately aborts Lua execution until the game handles the error and prints it in Firetuner (when enabled).&lt;br /&gt;
* Errors are caught before that point using &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;, in order to let you resume execution by managing the error. &amp;quot;pcall&amp;quot; stands for &amp;quot;protected call&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the syntaxes for pcall and xpcall:&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... pcall(func, ...)&amp;lt;/code&amp;gt;&lt;br /&gt;
** The function is called with the specified arguments.&lt;br /&gt;
** Pcall returns either true followed by the values returned by func, or false followed by the error text.&lt;br /&gt;
* &amp;lt;code&amp;gt;bool, ... xpcall(func, errorHandler)&amp;lt;/code&amp;gt;:&lt;br /&gt;
** The function is called without any argument. If an error occurs the specified errorHandler is invoked with the error text as the only argument.&lt;br /&gt;
** Xpcall returns either true followed by the values returned by func, or false followed by the returned values from errorHandler.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Examples to invoke &amp;quot;someFunc&amp;quot; with &amp;quot;someArg&amp;quot; as the only argument. In both examples we want to display the error on the console, or the result if it was a success. A complete errors management example with a reporting mechanism for the end-user is presented in [[Debugging (Civ5)]].&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- pcall&lt;br /&gt;
local status, result = pcall(someFunc, someArg)&lt;br /&gt;
if not status then&lt;br /&gt;
    print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;))&lt;br /&gt;
else&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- xpcall&lt;br /&gt;
local status, result = xpcall(&lt;br /&gt;
    function() someFunc(someArg) end,&lt;br /&gt;
    function(err) print(&amp;quot;error was: &amp;quot;..(result or &amp;quot;?&amp;quot;)) end)&lt;br /&gt;
&lt;br /&gt;
if status then&lt;br /&gt;
    print(&amp;quot;success: &amp;quot;..result)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advanced topics==&lt;br /&gt;
=== Metatables and metamethods ===&lt;br /&gt;
* Every value in Lua, from a number to a userdata, has a metatable. &lt;br /&gt;
** Many objects can share the same metatable. &lt;br /&gt;
** Tables and userdata each have their own metatables by default. Numbers, bools, nils and strings all share the same metatable.&lt;br /&gt;
* A metatable may contain a few metamethods and index tables.&lt;br /&gt;
** Metamethods are methods stored under special fields names. They implement operators overloads.&lt;br /&gt;
** Index tables behave as &amp;quot;base classes&amp;quot;: if a field name is not defined on an table, then Lua looks for this field on the index.&lt;br /&gt;
** In a way, metatables are analogous to virtual tables in object languages, but they are not just for methods, but also for fields and operators.&lt;br /&gt;
* You can get an object&#039;s metatable through &#039;&#039;&#039;getmetatable&#039;&#039;&#039; and assign it with &#039;&#039;&#039;setmetatable&#039;&#039;&#039;.&lt;br /&gt;
* See also the [http://www.lua.org/manual/5.1/manual.html#2.8 official metatables reference]&lt;br /&gt;
&lt;br /&gt;
One example.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Define two tables A and B, and set &amp;quot;meta&amp;quot; their metatable&lt;br /&gt;
local a, b, meta = {}, {}, {} &lt;br /&gt;
setmetatable(a, meta)         &lt;br /&gt;
setmetatable(b, meta)&lt;br /&gt;
&lt;br /&gt;
-- Define an __index table on the metatable. It contains one key/value pair.&lt;br /&gt;
meta.__index = { &amp;quot;hello world&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
-- Print &amp;quot;hello world&amp;quot; twice&lt;br /&gt;
print(a[1]) &lt;br /&gt;
print(b[1]) &lt;br /&gt;
&lt;br /&gt;
-- Now make our tables read-only&lt;br /&gt;
meta.__newindex = function(table, key, value) error(&amp;quot;this table is read-only!&amp;quot;) end&lt;br /&gt;
a[1] = &amp;quot;foo&amp;quot;      -- throws an error&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the most important fields a metatable can have:&lt;br /&gt;
* &#039;&#039;&#039;__index&#039;&#039;&#039;: used when you read a member from an object. On tables, Lua will first search for a regular field on the table itself (not its index) before it looks at the index. The index may be a table or a function: &amp;lt;code&amp;gt;value func(object, key)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__newindex&#039;&#039;&#039;: used when you assign a value to an object&#039;s member. On tables, newindex is only called if the table itself (not its index) does not already contains the specified key. May be a table or a function: &amp;lt;code&amp;gt;func(object, key, value)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__call&#039;&#039;&#039;: used when you invoke the object as a function. Must be a function: &amp;lt;code&amp;gt;func(object, &amp;lt;args&amp;gt;)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__tostring&#039;&#039;&#039;: used when you invoke the &#039;&#039;&#039;tostring&#039;&#039;&#039; function with this object in argument. Must be a function: &amp;lt;code&amp;gt;string func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Besides of that it can have fields for binary operators. When each of the two operands defined overloads, the left one is used. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__add&#039;&#039;&#039;: addition&lt;br /&gt;
* &#039;&#039;&#039;__sub&#039;&#039;&#039;: subtraction&lt;br /&gt;
* &#039;&#039;&#039;__mul&#039;&#039;&#039;: multiplication&lt;br /&gt;
* &#039;&#039;&#039;__div&#039;&#039;&#039;: division&lt;br /&gt;
* &#039;&#039;&#039;__mod&#039;&#039;&#039;: module&lt;br /&gt;
* &#039;&#039;&#039;__pow&#039;&#039;&#039;: exponentiation&lt;br /&gt;
* &#039;&#039;&#039;__eq&#039;&#039;&#039;: equality comparison. Prior to calling this overload, Lua checks that types are equal.&lt;br /&gt;
* &#039;&#039;&#039;__neq&#039;&#039;&#039;: inequality comparison. Prior to calling this overload, Lua checks whether types are different.&lt;br /&gt;
* &#039;&#039;&#039;__lt&#039;&#039;&#039;: lesser than comparison. (b &amp;gt;= a) is considered equivalent to (a &amp;lt; b)&lt;br /&gt;
* &#039;&#039;&#039;__le&#039;&#039;&#039;: lesser than or equal to comparison. (b &amp;gt; a) is considered equivalent to (a &amp;lt;= b). If __le is not defined, lua will use __lt, considering that (a &amp;lt;= b) is equivalent to not (b &amp;lt; a).&lt;br /&gt;
* &#039;&#039;&#039;__concat&#039;&#039;&#039;: concatenation&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally it can have the following fields for unary operators. They must be functions: &amp;lt;code&amp;gt;result func(object)&amp;lt;/code&amp;gt;&lt;br /&gt;
* &#039;&#039;&#039;__unm&#039;&#039;&#039;: unary minus&lt;br /&gt;
* &#039;&#039;&#039;__len&#039;&#039;&#039;: the sharp operator (#). Can only be used on userdata ; on tables the default operator will always be called.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Implementing inheritance ===&lt;br /&gt;
The most common use of metatables is to mimic the behavior of object languages&#039; types hierarchy. Here is how to do it:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
local Dog = {}&lt;br /&gt;
function Dog:specie() &lt;br /&gt;
   return &amp;quot;dog&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:race() &lt;br /&gt;
   return &amp;quot;unknown&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
function Dog:description()&lt;br /&gt;
   return self.specie()..&amp;quot; - &amp;quot;..self.race() &lt;br /&gt;
end&lt;br /&gt;
function Dog:new() &lt;br /&gt;
   local instance = {}&lt;br /&gt;
   setmetatable(instance, { __index = self})&lt;br /&gt;
   return instance&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local Pitbull = dog:new()&lt;br /&gt;
function Pitbull:race()&lt;br /&gt;
   return &amp;quot;pitbull&amp;quot; &lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
pitbull = Pitbull:new()&lt;br /&gt;
print(pitbull:description()) -- prints &amp;quot;dog - pitbull&amp;quot;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This implementation is very elegant: the &amp;quot;new&amp;quot; method both creates a new instance and subtypes the creator, since &amp;quot;pitbull&amp;quot;&#039;s index is now &amp;quot;Pitbull&amp;quot;. However, should you define an operator overload on Dog&#039;s metatable, Pitbull would not inherit it. This is the limit of inheritance in Lua: operator overloads must be defined on the metatable itself, they cannot be defined on the metatable&#039;s index. As a result, there is no way to inherit those overloads while subtyping.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Coroutines ===&lt;br /&gt;
Coroutines provide a way to slice a function in many shorter calls and optionally return intermediate results. On each call, the function execution is resumed to the point where it stopped previously, with all locals being properly restored with the value they had at this time.&lt;br /&gt;
* Coroutines are often compared to threads. Indeed, when there are more threads than CPU cores, the operating system slices threads&#039; execution into many little time frames and sequentially runs them in order to achieve multitasking. However while coroutines allows you to implement cooperative multitasking (the coroutines need to explicitly give the hand back), they cannot be used for preemptive multitasking or to use more than one system thread or CPU Core.&lt;br /&gt;
* As a result, coroutines are rather used as syntactic sugar (mostly to write iterators), or as a way to split a long function execution across many frames (through Context.{{Func5|Context|SetUpdate}}).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The following methods are mainly used:&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;coroutine&#039;&#039;&#039; coroutine.create(&#039;&#039;&#039;function&#039;&#039;&#039; func)&amp;lt;/code&amp;gt; creates a coroutine for the specified function. The function signature can be anything.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;bool&#039;&#039;&#039;, &#039;&#039;&#039;...&#039;&#039;&#039; coroutine.resume(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co, &#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; resumes the coroutine with the specified arguments. Then it returns either &#039;&#039;&#039;true&#039;&#039;&#039; followed by the returned results (either though &#039;&#039;&#039;return&#039;&#039;&#039; or &#039;&#039;&#039;yield&#039;&#039;&#039;), or &#039;&#039;&#039;false&#039;&#039;&#039; followed by an error message.&lt;br /&gt;
* &amp;lt;code&amp;gt;coroutine.yield(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; suspends the execution of the coroutine and gives the hand back to the caller of coroutine.resume. The arguments will be returned by coroutine.resume.&lt;br /&gt;
* &amp;lt;code&amp;gt;&#039;&#039;&#039;string&#039;&#039;&#039; coroutine.status(&#039;&#039;&#039;coroutine&#039;&#039;&#039; co)&amp;lt;/code&amp;gt; returns either &amp;quot;running&amp;quot; (the active coroutine), &amp;quot;normal&amp;quot; (a parent of the active coroutine), &amp;quot;suspended&amp;quot; (not started or waiting to be resumed) or &amp;quot;dead&amp;quot; (finished or threw an error).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a base example:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighborsCoroutine(plot)&lt;br /&gt;
    for i = 0, 5 do   &lt;br /&gt;
        coroutine.yield(Map.PlotDirection(plot:GetX(), plot:GetY(), i))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
local co = coroutine.create(neighborsCoroutine)&lt;br /&gt;
while coroutine.status(co) == &amp;quot;suspended&amp;quot;&lt;br /&gt;
    local _, neighbor = co.resume(plot)&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is how to transform it into an iterator:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function neighbors(plot)&lt;br /&gt;
    local co = coroutine.create(neighbors)&lt;br /&gt;
    return function()&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then return end&lt;br /&gt;
        return select(2, coroutine.resume(plot))&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
for neighbor in neighbors(plot) do&lt;br /&gt;
    -- Do something with plot&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is an example that spreads a long function call across many frames:&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
function SpreadAcrossFrames(longFunctionCall, ...)&lt;br /&gt;
    local co = coroutine.create(longFunctionCall)&lt;br /&gt;
    ContextPtr.SetUpdate(function()&lt;br /&gt;
        coroutine.resume(unpack(arg))&lt;br /&gt;
        if coroutine.status(co) ~= &amp;quot;suspended&amp;quot; then&lt;br /&gt;
            ContextPtr:ClearUpdate()&lt;br /&gt;
            return&lt;br /&gt;
        end&lt;br /&gt;
    end)&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
SpreadAcrossFrames(SomeLongFunction, arg1, arg2)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Design philosophy for Lua ===&lt;br /&gt;
Do not use a butter knife as you would use a chainsaw (the opposite is even more true and usually ends up badly). When designing your code, remember that:&lt;br /&gt;
* Lua is not an object language. While you can use objects and inheritance in some extent, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is not a functional language. While you can use lambdas and similar concepts, you do not have to and there may be better alternatives sometimes.&lt;br /&gt;
* Lua is a multi-paradigm and dynamic language, take advantage of those.&lt;br /&gt;
* Lua is very suited for prototyping and small programs, and this is perfect for mods. Try to adjust your mindset: you&#039;re not writing a framework that a whole team will still use and maintain in twenty years.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 API]]&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14024</id>
		<title>Debugging (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14024"/>
		<updated>2012-09-24T14:02:52Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
== Checklist ==&lt;br /&gt;
* Did you correctly import to the [[VFS (Civ5)|VFS]] the files that need to be?&lt;br /&gt;
* Did you correctly set up the actions and content tab in your project?&lt;br /&gt;
* Did you restart civ5 after you added new files?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== XML Debugging ==&lt;br /&gt;
[[File:SQLiteManager.png|frame|View of the snapshot using SQLiteManager]]&lt;br /&gt;
=== Checking the logs ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves some logs under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;.&lt;br /&gt;
* If there were errors with the XML formatting of your data files (wrong column names for example), they will logged in XML.log. Some of those errors may be fatal: in such a case no mod is loaded!&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6904.323] Tag (TXT_KEYMODDING_SHOWDLCMODS) does not start with &#039;TXT_KEY_&#039;&amp;lt;/pre&amp;gt;&lt;br /&gt;
* If there were errors with the data integrity (missing foreign keys for example - types that reference rows from other tables), they will logged in database.log.&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6903.917] Invalid Reference on Leader_Flavors.LeaderType - &amp;quot;LEADER_HARALD&amp;quot; does not exist in Leaders&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Using the snapshots ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves a snapshot of the database under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;&lt;br /&gt;
* This allows you to check how your XML and SQL files have been merged with the standard game data.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Lua Debugging ==&lt;br /&gt;
=== Using the Firetuner console ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], Civ5 will send all the Lua output to the Firetuner. This includes all the debugging output but also any error that may arise, with their calls stack traces. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 Runtime Error: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
stack traceback:&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: in function &#039;dumpObj&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:95: in function &#039;ScanAll&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:188: in main chunk&lt;br /&gt;
	[C]: ?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Here we can see that a C/C++ code (the game engine) ran the main chunk called (the Lua file), which then called the function &#039;&#039;ScanAll&#039;&#039; on line 188, which then called &#039;&#039;dumpObj&#039;&#039; on line 95. And this one caused an error on line 41.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note that paths are truncated in the provided example, which makes debugging harder sometimes. This happens when the file is in a {{Type5|context}} registered by the project&#039;s &#039;&#039;content&#039;&#039; tab. Here are the workarounds:&lt;br /&gt;
* Register only a minimalist context, that will load additional contexts (through the UI LuaContext markup). Do not initiate any action from the root context, let the children context handle everything.&lt;br /&gt;
* Provide a custom stack trace, as explained in a further section.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Print, assert and error ===&lt;br /&gt;
&amp;lt;code&amp;gt;print(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; can be used to print anything to the Firetuner output. This allows you to check the flow of a program, or the values of variables. Print calls &#039;&#039;&#039;tostring&#039;&#039;&#039; on every argument and displays them all on a single line with tabulations as separators between them. Nil values are not displayed, so it is advised you provide expressions such as: &amp;lt;code&amp;gt;(expr or &#039;nil&#039;)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;error(&#039;&#039;&#039;string&#039;&#039;&#039; message, &#039;&#039;&#039;int&#039;&#039;&#039; level = 1)&amp;lt;/code&amp;gt; throws an error with the specified message. The execution is then halted and the hand returned to the game engine (or the current protected call if you did use &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;). The level parameter controls the error position that will be reported. 1 for the line where error is located, 2 for the function call that contained an error, etc. 0 for no position.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;assert(&#039;&#039;&#039;variant&#039;&#039;&#039; condition, &#039;&#039;&#039;string&#039;&#039;&#039; message = &amp;quot;assertion failed&amp;quot;)&amp;lt;/code&amp;gt; can be used to assert the provided condition is neither nil nor false (everything else is evaluated to true in Lua). Otherwise, an error with the specified message is thrown. You can use them punctually, as a debugging technique. But they may also be used as a defensive programming technique similar to [http://en.wikipedia.org/wiki/Design_by_contract design-by-contract]: the idea is that whenever your program&#039;s correctness relies on an assumption, you should explicitly check it. For example, if a function takes an array as an argument and assumes that it is not empty, you should add two conditions at the beginning: &amp;lt;code&amp;gt;assert(type(t) == &amp;quot;table&amp;quot;)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;assert(#t &amp;gt; 0)&amp;lt;/code&amp;gt;. This makes the code more self-explanatory (implicit assumptions are now explicitly stated) and it allows you to catch bugs as soon as possible, which typically makes them easier to understand and fix.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Handling errors for the end user ===&lt;br /&gt;
Most of the time, when one of your user encounters an error with your mod, he just stops using it. A fraction of them will do the effort of reporting bugs but too often the informations they provide is unusable (from &amp;quot;it doesn&#039;t work&amp;quot; to wrong reproduction steps &amp;quot;play until turn 173 and wait for Mars being aligned with Venus&amp;quot;). The best way to increase the number of reports and their usefulness is to let your mod tell them the info it needs, as illustrated below.&lt;br /&gt;
&lt;br /&gt;
[[File:IGE-Error.png|none|frame|[http://forums.civfanatics.com/showthread.php?t=436912 In-game editor] tells its users what they must report, even including a calls stack trace when available. The user only needs to make a screenshot that will then land on his Steam profile (provided he didn&#039;t change the Steam settings). Reporting made easy!]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The [[Lua introduction for confirmed developers]] describes a number of techniques you can use to achieve similar results. Here we present an implementation you can use to handle errors in the most dangerous parts of your code in order to present them to the user with a full stack trace when available.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Returns an array of strings, one for each call level. &lt;br /&gt;
-- We could use debug.traceback instead but this ones truncates path and we cannot easily ignore the topmost levels.&lt;br /&gt;
function getStackTrace()&lt;br /&gt;
    -- Level 1 is getStackTrace, 2 is its caller&lt;br /&gt;
    local level = 2 &lt;br /&gt;
    local trace = {}&lt;br /&gt;
    while true do&lt;br /&gt;
        -- Gets that level&#039;s informations: function name, source file and line.&lt;br /&gt;
        local info = debug.getinfo(level, &amp;quot;nSl&amp;quot;) &lt;br /&gt;
        if not info then break end&lt;br /&gt;
&lt;br /&gt;
        -- C code or Lua code?&lt;br /&gt;
        if info.what == &amp;quot;C&amp;quot; then&lt;br /&gt;
            table.insert(trace, &amp;quot;C function&amp;quot;);&lt;br /&gt;
        else   &lt;br /&gt;
            local userStr = Path.GetFileName(info.source)..&amp;quot;: &amp;quot;..info.currentline;&lt;br /&gt;
            if info.name and string.len(info.name) then&lt;br /&gt;
                userStr = userStr..&amp;quot; (&amp;quot;..info.name..&amp;quot;)&amp;quot;;&lt;br /&gt;
            end&lt;br /&gt;
            table.insert(trace, userStr);&lt;br /&gt;
        end&lt;br /&gt;
        level = level + 1&lt;br /&gt;
    end&lt;br /&gt;
    return trace;&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Gets a nicely formatted string of the error. &lt;br /&gt;
-- The second parameter is the number of levels to ignore in the calls stack (formatError excluded). Defaults to 0.&lt;br /&gt;
function formatError(err, levelsToIgnoreBelow)&lt;br /&gt;
    print(err);&lt;br /&gt;
&lt;br /&gt;
    -- We do not want to include formatError in the stack trace, hence the +1&lt;br /&gt;
    levelsToIgnoreBelow = (levelsToIgnoreBelow or 0) + 1;&lt;br /&gt;
&lt;br /&gt;
    -- &#039;err&#039; is like: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
    -- We retrieve important positions in this string. Remember: not all paths are truncated.&lt;br /&gt;
    local elipsisIndex = string.find(err, &amp;quot;...&amp;quot;, 1, true) or -5;&lt;br /&gt;
    local lineIndex = elipsisIndex + 6	&lt;br /&gt;
    local msgIndex = string.find(err, &amp;quot;:&amp;quot;, lineIndex, true) + 1&lt;br /&gt;
&lt;br /&gt;
    -- Can we append the stack trace?&lt;br /&gt;
    local result = &amp;quot;&amp;quot;&lt;br /&gt;
    if debug and debug.getinfo then&lt;br /&gt;
        result = string.sub(err, msgIndex)&lt;br /&gt;
&lt;br /&gt;
        local trace = getStackTrace()&lt;br /&gt;
        for i, v in ipairs(trace) do&lt;br /&gt;
            print(v)&lt;br /&gt;
            if (i &amp;gt; levelsToIgnoreBelow) then&lt;br /&gt;
                result = result..&amp;quot;[NEWLINE]&amp;quot;..v;&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    -- Otherwise just report the line and message, and the source file when not truncated.&lt;br /&gt;
    else&lt;br /&gt;
        result = &amp;quot;line &amp;quot;..string.sub(err, elipsisIndex)&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return result&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- The error handler to provide to xpcall&lt;br /&gt;
local function errorHandler(err)&lt;br /&gt;
    -- The stack trace at this point is:&lt;br /&gt;
    -- 1: this error handler (must not be reported), &lt;br /&gt;
    -- 2: C function calling the handler (kept for security)&lt;br /&gt;
    -- 3: the error source&lt;br /&gt;
    err = formatError(err, 1);&lt;br /&gt;
&lt;br /&gt;
    -- Show a popup to the user&lt;br /&gt;
    local str = L(&amp;quot;Oops, an error occured:&amp;quot;)..&amp;quot;[NEWLINE][ICON_PIRATE] &amp;quot;..err;&lt;br /&gt;
    Events.SerialEventGameMessagePopup( { Type = ButtonPopupTypes.BUTTONPOPUP_TEXT, Data1 = 800, Option1 = true, Text = str } );&lt;br /&gt;
&lt;br /&gt;
    -- Restore things up here when needed. Beware to not cause any error as it would cause an infinite recursive call up to the stack overflow!&lt;br /&gt;
    return false&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Calls someDangerousFunction with the given error handler&lt;br /&gt;
xpcall(someDangerousFunction, errorHandler)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Troubleshooting ==&lt;br /&gt;
The [[Civ5 Useful Programs]] page presents you a number of tools you can use to inspect or modify the game. This is especially useful if you want to quickly reproduce a bug or test something, or to understand what is happening.&lt;br /&gt;
* Let&#039;s say your mod adds a tech but you do not see in the techs panel. There is a FireTuner panel you can use to see a flat list of all the techs in-game.&lt;br /&gt;
* Let&#039;s say your mod adds a unit or a wonder, the IGE mod allows you to quickly create an unit or build that wonder (including the splash screen).&lt;br /&gt;
* Let&#039;s say your mod modifies the yields when the player acquire a specific tech. Once again IGE allows you to grant you that tech and see how the yields are modified.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Configuration ==&lt;br /&gt;
Look for the following files under &amp;lt;code&amp;gt;My Documents/My Games/Sid Meiers&#039; Civilization V&amp;lt;/code&amp;gt; and open them in a text editor like the notepad (not in a word processor).&lt;br /&gt;
* &#039;&#039;&#039;config.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;LoggingEnabled&amp;lt;/code&amp;gt; to 1. Civ5 will write log files under the &amp;lt;code&amp;gt;Logs&amp;lt;/code&amp;gt; folder.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableLuaDebugLibrary&amp;lt;/code&amp;gt; to 1. Civ5 will display stack traces on Lua errors and you will be able to use the [http://www.lua.org/manual/5.1/manual.html#pdf-debug.debug debug] object.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugPanel&amp;lt;/code&amp;gt; to 1. By pressing the &#039;&#039;&#039;²&#039;&#039;&#039; key (may be &#039;&#039;&#039;ù&#039;&#039;&#039; or something else depending on your computer&#039;s language) during a game, Civ5 will display a debug panel.&lt;br /&gt;
* &#039;&#039;&#039;usersettings.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugMode&amp;lt;/code&amp;gt; to 1. Needed to enable other features previously mentioned.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14023</id>
		<title>Debugging (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14023"/>
		<updated>2012-09-24T14:00:38Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
== Checklist ==&lt;br /&gt;
* Did you correctly import to the [[VFS (Civ5)|VFS]] the files that need to be?&lt;br /&gt;
* Did you correctly set up the actions and content tab in your project?&lt;br /&gt;
* Did you restart civ5 after you added new files?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== XML Debugging ==&lt;br /&gt;
[[File:SQLiteManager.png|frame|View of the snapshot using SQLiteManager]]&lt;br /&gt;
=== Checking the logs ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves some logs under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;.&lt;br /&gt;
* If there were errors with the XML formatting of your data files (wrong column names for example), they will logged in XML.log. Some of those errors may be fatal: in such a case no mod is loaded!&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6904.323] Tag (TXT_KEYMODDING_SHOWDLCMODS) does not start with &#039;TXT_KEY_&#039;&amp;lt;/pre&amp;gt;&lt;br /&gt;
* If there were errors with the data integrity (missing foreign keys for example - types that reference rows from other tables), they will logged in database.log.&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6903.917] Invalid Reference on Leader_Flavors.LeaderType - &amp;quot;LEADER_HARALD&amp;quot; does not exist in Leaders&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Using the snapshots ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves a snapshot of the database under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;&lt;br /&gt;
* This allows you to check how your XML and SQL files have been merged with the standard game data.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Lua Debugging ==&lt;br /&gt;
=== Using the Firetuner console ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], Civ5 will send all the Lua output to the Firetuner. This includes all the debugging output but also any error that may arise, with their calls stack traces. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 Runtime Error: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
stack traceback:&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: in function &#039;dumpObj&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:95: in function &#039;ScanAll&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:188: in main chunk&lt;br /&gt;
	[C]: ?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Here we can see that a C/C++ code (the game engine) ran the main chunk called (the Lua file), which then called the function &#039;&#039;ScanAll&#039;&#039; on line 188, which then called &#039;&#039;dumpObj&#039;&#039; on line 95. And this one caused an error on line 41.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note that paths are truncated in the provided example, which makes debugging harder sometimes. This happens when the file is in a {{Type5|context}} registered by the project&#039;s &#039;&#039;content&#039;&#039; tab. Here are the workarounds:&lt;br /&gt;
* Register only a minimalist context, that will load additional contexts (through the UI LuaContext markup). Do not initiate any action from the root context, let the children context handle everything.&lt;br /&gt;
* Provide a custom stack trace, as explained in a further section.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Print, assert and error ===&lt;br /&gt;
&amp;lt;code&amp;gt;print(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; can be used to print anything to the Firetuner output. This allows you to check the flow of a program, or the values of variables. Print calls &#039;&#039;&#039;tostring&#039;&#039;&#039; on every argument and displays them all on a single line with tabulations as separators between them. Nil values are not displayed, so it is advised you provide expressions such as: &amp;lt;code&amp;gt;(expr or &#039;nil&#039;)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;error(&#039;&#039;&#039;string&#039;&#039;&#039; message, &#039;&#039;&#039;int&#039;&#039;&#039; level = 1)&amp;lt;/code&amp;gt; throws an error with the specified message. The execution is then halted and the hand returned to the game engine (or the current protected call if you did use &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;). The level parameter controls the error position that will be reported. 1 for the line where error is located, 2 for the function call that contained an error, etc. 0 for no position.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;assert(&#039;&#039;&#039;variant&#039;&#039;&#039; condition, &#039;&#039;&#039;string&#039;&#039;&#039; message = &amp;quot;assertion failed&amp;quot;)&amp;lt;/code&amp;gt; can be used to assert the provided condition is neither nil nor false (everything else is evaluated to true in Lua). Otherwise, an error with the specified message is thrown. You can use them punctually, as a debugging technique. But they may also be used as a defensive programming technique similar to [http://en.wikipedia.org/wiki/Design_by_contract design-by-contract]: the idea is that whenever your program&#039;s correctness relies on an assumption, you should explicitly check it. For example, if a function takes an array as an argument and assumes that it is not empty, you should add two conditions at the beginning: &amp;lt;code&amp;gt;assert(type(t) == &amp;quot;table&amp;quot;)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;assert(#t &amp;gt; 0)&amp;lt;/code&amp;gt;. This makes the code more self-explanatory (implicit assumptions are now explicitly stated) and it allows you to catch bugs as soon as possible, which typically makes them easier to understand and fix.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Handling errors for the end user ===&lt;br /&gt;
Most of the time, when one of your user encounters an error with your mod, he just stops using it. A fraction of them will do the effort of reporting bugs but too often the informations they provide is unusable (from &amp;quot;it doesn&#039;t work&amp;quot; to wrong reproduction steps &amp;quot;play until turn 173 and wait for Mars being aligned with Venus&amp;quot;). The best way to increase the number of reports and their usefulness is to let your mod tell them the info it needs, as illustrated below.&lt;br /&gt;
&lt;br /&gt;
[[File:IGE-Error.png|none|frame|[http://forums.civfanatics.com/showthread.php?t=436912 In-game editor] tells its users what they must report, even including a calls stack trace when available. The user only needs to make a screenshot that will then land on his Steam profile (provided he didn&#039;t change the Steam settings). Reporting made easy!]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The [[Lua introduction for confirmed developers]] describes a number of techniques you can use to achieve similar results. Here we present an implementation you can use to handle errors in the most dangerous parts of your code in order to present them to the user with a full stack trace when available.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Returns an array of strings, one for each call level.&lt;br /&gt;
function getStackTrace()&lt;br /&gt;
    -- Level 1 is getStackTrace, 2 is its caller&lt;br /&gt;
    local level = 2 &lt;br /&gt;
    local trace = {}&lt;br /&gt;
    while true do&lt;br /&gt;
        -- Gets that level&#039;s informations: function name, source file and line.&lt;br /&gt;
        local info = debug.getinfo(level, &amp;quot;nSl&amp;quot;) &lt;br /&gt;
        if not info then break end&lt;br /&gt;
&lt;br /&gt;
        -- C code or Lua code?&lt;br /&gt;
        if info.what == &amp;quot;C&amp;quot; then&lt;br /&gt;
            table.insert(trace, &amp;quot;C function&amp;quot;);&lt;br /&gt;
        else   &lt;br /&gt;
            local userStr = Path.GetFileName(info.source)..&amp;quot;: &amp;quot;..info.currentline;&lt;br /&gt;
            if info.name and string.len(info.name) then&lt;br /&gt;
                userStr = userStr..&amp;quot; (&amp;quot;..info.name..&amp;quot;)&amp;quot;;&lt;br /&gt;
            end&lt;br /&gt;
            table.insert(trace, userStr);&lt;br /&gt;
        end&lt;br /&gt;
        level = level + 1&lt;br /&gt;
    end&lt;br /&gt;
    return trace;&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Gets a nicely formatted string of the error. &lt;br /&gt;
-- The second parameter is the number of levels to ignore in the calls stack (formatError excluded). Defaults to 0.&lt;br /&gt;
function formatError(err, levelsToIgnoreBelow)&lt;br /&gt;
    print(err);&lt;br /&gt;
&lt;br /&gt;
    -- We do not want to include formatError in the stack trace, hence the +1&lt;br /&gt;
    levelsToIgnoreBelow = (levelsToIgnoreBelow or 0) + 1;&lt;br /&gt;
&lt;br /&gt;
    -- &#039;err&#039; is like: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
    -- We retrieve important positions in this string. Remember: not all paths are truncated.&lt;br /&gt;
    local elipsisIndex = string.find(err, &amp;quot;...&amp;quot;, 1, true) or -5;&lt;br /&gt;
    local lineIndex = elipsisIndex + 6	&lt;br /&gt;
    local msgIndex = string.find(err, &amp;quot;:&amp;quot;, lineIndex, true) + 1&lt;br /&gt;
&lt;br /&gt;
    -- Can we append the stack trace?&lt;br /&gt;
    local result = &amp;quot;&amp;quot;&lt;br /&gt;
    if debug and debug.getinfo then&lt;br /&gt;
        result = string.sub(err, msgIndex)&lt;br /&gt;
&lt;br /&gt;
        local trace = getStackTrace()&lt;br /&gt;
        for i, v in ipairs(trace) do&lt;br /&gt;
            print(v)&lt;br /&gt;
            if (i &amp;gt; levelsToIgnoreBelow) then&lt;br /&gt;
                result = result..&amp;quot;[NEWLINE]&amp;quot;..v;&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    -- Otherwise just report the line and message, and the source file when not truncated.&lt;br /&gt;
    else&lt;br /&gt;
        result = &amp;quot;line &amp;quot;..string.sub(err, elipsisIndex)&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return result&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- The error handler to provide to xpcall&lt;br /&gt;
local function errorHandler(err)&lt;br /&gt;
    -- The stack trace at this point is:&lt;br /&gt;
    -- 1: this error handler (must not be reported), &lt;br /&gt;
    -- 2: C function calling the handler (kept for security)&lt;br /&gt;
    -- 3: the error source&lt;br /&gt;
    err = formatError(err, 1);&lt;br /&gt;
&lt;br /&gt;
    -- Show a popup to the user&lt;br /&gt;
    local str = L(&amp;quot;Oops, an error occured:&amp;quot;)..&amp;quot;[NEWLINE][ICON_PIRATE] &amp;quot;..err;&lt;br /&gt;
    Events.SerialEventGameMessagePopup( { Type = ButtonPopupTypes.BUTTONPOPUP_TEXT, Data1 = 800, Option1 = true, Text = str } );&lt;br /&gt;
&lt;br /&gt;
    -- Restore things up here when needed. Beware to not cause any error as it would cause an infinite recursive call up to the stack overflow!&lt;br /&gt;
    return false&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Calls someDangerousFunction with the given error handler&lt;br /&gt;
xpcall(someDangerousFunction, errorHandler)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Troubleshooting ==&lt;br /&gt;
The [[Civ5 Useful Programs]] page presents you a number of tools you can use to inspect or modify the game. This is especially useful if you want to quickly reproduce a bug or test something, or to understand what is happening.&lt;br /&gt;
* Let&#039;s say your mod adds a tech but you do not see in the techs panel. There is a FireTuner panel you can use to see a flat list of all the techs in-game.&lt;br /&gt;
* Let&#039;s say your mod adds a unit or a wonder, the IGE mod allows you to quickly create an unit or build that wonder (including the splash screen).&lt;br /&gt;
* Let&#039;s say your mod modifies the yields when the player acquire a specific tech. Once again IGE allows you to grant you that tech and see how the yields are modified.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Configuration ==&lt;br /&gt;
Look for the following files under &amp;lt;code&amp;gt;My Documents/My Games/Sid Meiers&#039; Civilization V&amp;lt;/code&amp;gt; and open them in a text editor like the notepad (not in a word processor).&lt;br /&gt;
* &#039;&#039;&#039;config.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;LoggingEnabled&amp;lt;/code&amp;gt; to 1. Civ5 will write log files under the &amp;lt;code&amp;gt;Logs&amp;lt;/code&amp;gt; folder.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableLuaDebugLibrary&amp;lt;/code&amp;gt; to 1. Civ5 will display stack traces on Lua errors and you will be able to use the [http://www.lua.org/manual/5.1/manual.html#pdf-debug.debug debug] object.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugPanel&amp;lt;/code&amp;gt; to 1. By pressing the &#039;&#039;&#039;²&#039;&#039;&#039; key (may be &#039;&#039;&#039;ù&#039;&#039;&#039; or something else depending on your computer&#039;s language) during a game, Civ5 will display a debug panel.&lt;br /&gt;
* &#039;&#039;&#039;usersettings.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugMode&amp;lt;/code&amp;gt; to 1. Needed to enable other features previously mentioned.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
	<entry>
		<id>https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14022</id>
		<title>Debugging (Civ5)</title>
		<link rel="alternate" type="text/html" href="https://modiki.civfanatics.com/index.php?title=Debugging_(Civ5)&amp;diff=14022"/>
		<updated>2012-09-24T13:59:53Z</updated>

		<summary type="html">&lt;p&gt;DonQuich: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;This page is a part of the [[Civ5 Modding Tutorials]].&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
== Checklist ==&lt;br /&gt;
* Did you correctly import to the [[VFS (Civ5)|VFS]] the files that need to be?&lt;br /&gt;
* Did you correctly set up the actions and content tab in your project?&lt;br /&gt;
* Did you restart civ5 after you added new files?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== XML Debugging ==&lt;br /&gt;
[[File:SQLiteManager.png|frame|View of the snapshot using SQLiteManager]]&lt;br /&gt;
=== Checking the logs ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves some logs under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;.&lt;br /&gt;
* If there were errors with the XML formatting of your data files (wrong column names for example), they will logged in XML.log. Some of those errors may be fatal: in such a case no mod is loaded!&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6904.323] Tag (TXT_KEYMODDING_SHOWDLCMODS) does not start with &#039;TXT_KEY_&#039;&amp;lt;/pre&amp;gt;&lt;br /&gt;
* If there were errors with the data integrity (missing foreign keys for example - types that reference rows from other tables), they will logged in database.log.&lt;br /&gt;
:&amp;lt;pre&amp;gt;[6903.917] Invalid Reference on Leader_Flavors.LeaderType - &amp;quot;LEADER_HARALD&amp;quot; does not exist in Leaders&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Using the snapshots ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], whenever you start a game, Civ5 saves a snapshot of the database under &amp;lt;code&amp;gt;My Games/Sid Medier&#039;s Civilization V/cache/Civ5DebugDatabase.db&amp;lt;/code&amp;gt;&lt;br /&gt;
* This allows you to check how your XML and SQL files have been merged with the standard game data.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Lua Debugging ==&lt;br /&gt;
=== Using the Firetuner console ===&lt;br /&gt;
If you correctly set up your [[#Configuration]], Civ5 will send all the Lua output to the Firetuner. This includes all the debugging output but also any error that may arise, with their calls stack traces. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 Runtime Error: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
stack traceback:&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: in function &#039;dumpObj&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:95: in function &#039;ScanAll&#039;&lt;br /&gt;
	[string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:188: in main chunk&lt;br /&gt;
	[C]: ?&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Here we can see that a C/C++ code (the game engine) ran the main chunk called (the Lua file), which then called the function &#039;&#039;ScanAll&#039;&#039; on line 188, which then called &#039;&#039;dumpObj&#039;&#039; on line 95. And this one caused an error on line 41.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Note that paths are truncated in the provided example, which makes debugging harder sometimes. This happens when the file is in a {{Type5|context}} registered by the project&#039;s &#039;&#039;content&#039;&#039; tab. Here are the workarounds:&lt;br /&gt;
* Register only a minimalist context, that will load additional contexts (through the UI LuaContext markup). Do not initiate any action from the root context, let the children context handle everything.&lt;br /&gt;
* Provide a custom stack trace, as explained in a further section.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Print, assert and error ===&lt;br /&gt;
&amp;lt;code&amp;gt;print(&#039;&#039;&#039;...&#039;&#039;&#039;)&amp;lt;/code&amp;gt; can be used to print anything to the Firetuner output. This allows you to check the flow of a program, or the values of variables. Print calls &#039;&#039;&#039;tostring&#039;&#039;&#039; on every argument and displays them all on a single line with tabulations as separators between them. Nil values are not displayed, so it is advised you provide expressions such as: &amp;lt;code&amp;gt;(expr or &#039;nil&#039;)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;error(&#039;&#039;&#039;string&#039;&#039;&#039; message, &#039;&#039;&#039;int&#039;&#039;&#039; level = 1)&amp;lt;/code&amp;gt; throws an error with the specified message. The execution is then halted and the hand returned to the game engine (or the current protected call if you did use &#039;&#039;&#039;pcall&#039;&#039;&#039; or &#039;&#039;&#039;xpcall&#039;&#039;&#039;). The level parameter controls the error position that will be reported. 1 for the line where error is located, 2 for the function call that contained an error, etc. 0 for no position.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;assert(&#039;&#039;&#039;variant&#039;&#039;&#039; condition, &#039;&#039;&#039;string&#039;&#039;&#039; message = &amp;quot;assertion failed&amp;quot;)&amp;lt;/code&amp;gt; can be used to assert the provided condition is neither nil nor false (everything else is evaluated to true in Lua). Otherwise, an error with the specified message is thrown. You can use them punctually, as a debugging technique. But they may also be used as a defensive programming technique such as [http://en.wikipedia.org/wiki/Design_by_contract design-by-contract]: the idea is that whenever your program&#039;s correctness relies on an assumption, you should explicitly check it. For example, if a function takes an array as an argument and assumes that it is not empty, you should add two conditions at the beginning: &amp;lt;code&amp;gt;assert(type(t) == &amp;quot;table&amp;quot;)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;assert(#t &amp;gt; 0)&amp;lt;/code&amp;gt;. This makes the code more self-explanatory (implicit assumptions are now explicitly stated) and it allows you to catch bugs as soon as possible, which typically makes them easier to understand and fix.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Handling errors for the end user ===&lt;br /&gt;
Most of the time, when one of your user encounters an error with your mod, he just stops using it. A fraction of them will do the effort of reporting bugs but too often the informations they provide is unusable (from &amp;quot;it doesn&#039;t work&amp;quot; to wrong reproduction steps &amp;quot;play until turn 173 and wait for Mars being aligned with Venus&amp;quot;). The best way to increase the number of reports and their usefulness is to let your mod tell them the info it needs, as illustrated below.&lt;br /&gt;
&lt;br /&gt;
[[File:IGE-Error.png|none|frame|[http://forums.civfanatics.com/showthread.php?t=436912 In-game editor] tells its users what they must report, even including a calls stack trace when available. The user only needs to make a screenshot that will then land on his Steam profile (provided he didn&#039;t change the Steam settings). Reporting made easy!]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The [[Lua introduction for confirmed developers]] describes a number of techniques you can use to achieve similar results. Here we present an implementation you can use to handle errors in the most dangerous parts of your code in order to present them to the user with a full stack trace when available.&lt;br /&gt;
&amp;lt;div class=&amp;quot;civ5-example&amp;quot;&amp;gt;&amp;lt;syntaxhighlight lang=&amp;quot;lua&amp;quot;&amp;gt;&lt;br /&gt;
-- Returns an array of strings, one for each call level.&lt;br /&gt;
function getStackTrace()&lt;br /&gt;
    -- Level 1 is getStackTrace, 2 is its caller&lt;br /&gt;
    local level = 2 &lt;br /&gt;
    local trace = {}&lt;br /&gt;
    while true do&lt;br /&gt;
        -- Gets that level&#039;s informations: function name, source file and line.&lt;br /&gt;
        local info = debug.getinfo(level, &amp;quot;nSl&amp;quot;) &lt;br /&gt;
        if not info then break end&lt;br /&gt;
&lt;br /&gt;
        -- C code or Lua code?&lt;br /&gt;
        if info.what == &amp;quot;C&amp;quot; then&lt;br /&gt;
            table.insert(trace, &amp;quot;C function&amp;quot;);&lt;br /&gt;
        else   &lt;br /&gt;
            local userStr = Path.GetFileName(info.source)..&amp;quot;: &amp;quot;..info.currentline;&lt;br /&gt;
            if info.name and string.len(info.name) then&lt;br /&gt;
                userStr = userStr..&amp;quot; (&amp;quot;..info.name..&amp;quot;)&amp;quot;;&lt;br /&gt;
            end&lt;br /&gt;
            table.insert(trace, userStr);&lt;br /&gt;
        end&lt;br /&gt;
        level = level + 1&lt;br /&gt;
    end&lt;br /&gt;
    return trace;&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Gets a nicely formatted string of the error. &lt;br /&gt;
-- The second parameter is the number of levels to ignore in the calls stack (formatError excluded). Defaults to 0.&lt;br /&gt;
function formatError(err, levelsToIgnoreBelow)&lt;br /&gt;
    print(err);&lt;br /&gt;
&lt;br /&gt;
    -- We do not want to include formatError in the stack trace, hence the +1&lt;br /&gt;
    levelsToIgnoreBelow = (levelsToIgnoreBelow or 0) + 1;&lt;br /&gt;
&lt;br /&gt;
    -- &#039;err&#039; is like: [string &amp;quot;C:\Users\Boss\Documents\My Games\Sid Meier&#039;...&amp;quot;]:41: attempt to concatenate local &#039;name&#039; (a nil value)&lt;br /&gt;
    -- We retrieve important positions in this string. Remember: not all paths are truncated.&lt;br /&gt;
    local elipsisIndex = string.find(err, &amp;quot;...&amp;quot;, 1, true) or -5;&lt;br /&gt;
    local lineIndex = elipsisIndex + 6	&lt;br /&gt;
    local msgIndex = string.find(err, &amp;quot;:&amp;quot;, lineIndex, true) + 1&lt;br /&gt;
&lt;br /&gt;
    -- Can we append the stack trace?&lt;br /&gt;
    local result = &amp;quot;&amp;quot;&lt;br /&gt;
    if debug and debug.getinfo then&lt;br /&gt;
        result = string.sub(err, msgIndex)&lt;br /&gt;
&lt;br /&gt;
        local trace = getStackTrace()&lt;br /&gt;
        for i, v in ipairs(trace) do&lt;br /&gt;
            print(v)&lt;br /&gt;
            if (i &amp;gt; levelsToIgnoreBelow) then&lt;br /&gt;
                result = result..&amp;quot;[NEWLINE]&amp;quot;..v;&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    -- Otherwise just report the line and message, and the source file when not truncated.&lt;br /&gt;
    else&lt;br /&gt;
        result = &amp;quot;line &amp;quot;..string.sub(err, elipsisIndex)&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return result&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- The error handler to provide to xpcall&lt;br /&gt;
local function errorHandler(err)&lt;br /&gt;
    -- The stack trace at this point is:&lt;br /&gt;
    -- 1: this error handler (must not be reported), &lt;br /&gt;
    -- 2: C function calling the handler (kept for security)&lt;br /&gt;
    -- 3: the error source&lt;br /&gt;
    err = formatError(err, 1);&lt;br /&gt;
&lt;br /&gt;
    -- Show a popup to the user&lt;br /&gt;
    local str = L(&amp;quot;Oops, an error occured:&amp;quot;)..&amp;quot;[NEWLINE][ICON_PIRATE] &amp;quot;..err;&lt;br /&gt;
    Events.SerialEventGameMessagePopup( { Type = ButtonPopupTypes.BUTTONPOPUP_TEXT, Data1 = 800, Option1 = true, Text = str } );&lt;br /&gt;
&lt;br /&gt;
    -- Restore things up here when needed. Beware to not cause any error as it would cause an infinite recursive call up to the stack overflow!&lt;br /&gt;
    return false&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
-- Calls someDangerousFunction with the given error handler&lt;br /&gt;
xpcall(someDangerousFunction, errorHandler)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Troubleshooting ==&lt;br /&gt;
The [[Civ5 Useful Programs]] page presents you a number of tools you can use to inspect or modify the game. This is especially useful if you want to quickly reproduce a bug or test something, or to understand what is happening.&lt;br /&gt;
* Let&#039;s say your mod adds a tech but you do not see in the techs panel. There is a FireTuner panel you can use to see a flat list of all the techs in-game.&lt;br /&gt;
* Let&#039;s say your mod adds a unit or a wonder, the IGE mod allows you to quickly create an unit or build that wonder (including the splash screen).&lt;br /&gt;
* Let&#039;s say your mod modifies the yields when the player acquire a specific tech. Once again IGE allows you to grant you that tech and see how the yields are modified.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Configuration ==&lt;br /&gt;
Look for the following files under &amp;lt;code&amp;gt;My Documents/My Games/Sid Meiers&#039; Civilization V&amp;lt;/code&amp;gt; and open them in a text editor like the notepad (not in a word processor).&lt;br /&gt;
* &#039;&#039;&#039;config.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;LoggingEnabled&amp;lt;/code&amp;gt; to 1. Civ5 will write log files under the &amp;lt;code&amp;gt;Logs&amp;lt;/code&amp;gt; folder.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;EnableLuaDebugLibrary&amp;lt;/code&amp;gt; to 1. Civ5 will display stack traces on Lua errors and you will be able to use the [http://www.lua.org/manual/5.1/manual.html#pdf-debug.debug debug] object.&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugPanel&amp;lt;/code&amp;gt; to 1. By pressing the &#039;&#039;&#039;²&#039;&#039;&#039; key (may be &#039;&#039;&#039;ù&#039;&#039;&#039; or something else depending on your computer&#039;s language) during a game, Civ5 will display a debug panel.&lt;br /&gt;
* &#039;&#039;&#039;usersettings.ini&#039;&#039;&#039;&lt;br /&gt;
** Set &amp;lt;code&amp;gt;DebugMode&amp;lt;/code&amp;gt; to 1. Needed to enable other features previously mentioned.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Civ5 Tutorials]]&lt;/div&gt;</summary>
		<author><name>DonQuich</name></author>
	</entry>
</feed>