The concept is to take something like this:
Code:
If (functionA) then
stuff
else if (functionB) then
stuff
else if (functionC) then
stuff
else if (functionD) then
stuff
...etc...
...and replace the long if-then chains with a table:
Code:
functionTable = {
functionA
functionB
functionC
functionD
...
}
Then you can "jump" to functions by index, and dramatically simplify the code:
Code:
If functionTable[i] then
stuff
This is basically turning an If-Then or Select-Case chain into a function array. The array can be stored in a location outside the code (such as XML), allowing easy changes to how the program operates without code alterations or recompiling.
There's also uses for two-dimensional function tables, especially for programs that have states. A good example is a vending machine.
The program stores the state and input as integers, then simply executes function[state][input] from the table to figure out what to do next.
I used this concept to greatly simplify the checks for the Emigration mod. Basically it looks like this when put in table form:
I simply loop through all the conditions, which are Lua functions, and if (condition) then (multiply by weight value). IsCityStatus indicates the row is a city status to check (to distinguish those from things like the weight for EmigratedOnceAlready).
PHP:
for row in GameInfo.EmigrationWeights() do
if row.IsCityStatus and city[row.Type](city) then
cityWeight[cityID] = cityWeight[cityID] * row.Value;
end;
end
On a side note, the other part of the XML file is configuration settings. In real world programming, it's good practice to separate some types of information away from the core code, at least by putting all constants at the top of the program. Exporting these constants to a file allows you to manipulate the code without recompiling or retesting, and reduces the chance of introducing coding errors when changing data values. This is why Civilization has lots of data stored in XML, and why I exported the constants used in Emigration.lua out to Emigration.xml. These are seen at the top of the file:
Code:
<Emigration>
<Row>
<Type>Debug</Type>
<Value>false</Value>
</Row>
<Row>
<Type>HappinessAverageTurns</Type>
<Value>10</Value>
</Row>
<Row>
<Type>MaxPasses</Type>
<Value>3</Value>
</Row>
<Row>
<Type>NumEmigrantsDenominator</Type>
<Value>10</Value>
</Row>
</Emigration>
In Windows this type of file is often called an ini file, and in Java it's called a property file.