Editing MG/Lua

Jump to navigation Jump to search

Warning: You are not logged in. Your IP address will be publicly visible if you make any edits. If you log in or create an account, your edits will be attributed to your username, along with other benefits.

The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then save the changes below to finish undoing the edit.

Latest revision Your text
Line 1: Line 1:
[[Lua]] is the scripting language used in [[MegaGlest]]'s [[scenarios]]. It allows scenarios to expand and do things not normally possible in regular games of Glest. This page lists all the Lua commands available in MegaGlest. For information on how to create scenarios and working with Lua in general, see [[Lua]].
+
'''Glest versions 3.2.0 and newer includes lua scripting functionality for scripted scenarios.'''
  
Notice: You can’t use the <-operator in within the XML-events. You can use an external script instead or invert the logic.
+
The game includes 2 tutorial scenarios and one scripted normal scenario(storming) now. These demo scenarios show a bit what's possible now. Have a look at them if you want to learn it.
  
==Text==
+
== Useful Links ==
=== showMessage(text, header) ===
+
*Omega's tutorial: [http://glest.org/glest_board/index.php?topic=3841.0 tutorial].
Displays a message box on the screen, that will have to be dismissed by the player.
+
*[http://www.lua.org/pil/ Programming in Lua]
 +
*[http://lua-users.org/wiki/TutorialDirectory lua tutorials]
 +
*[http://lua-users.org/wiki Lua-Users.org Wiki]
 +
== Lua/XML Intermixture Problem ==
 +
Due to XML's nature of using angle brackets for elements the parser will get confused and give an error if you try to use the left angle bracket in the scenario's XML file.
  
Parameters:<br />
+
A solution is to either swap the logic:
'''text''' - a string identifying the'' text'' from a language file.<br />
 
'''header''' - a string identifying the'' title bar text ''from a language file.
 
  
=== addConsoleText(text) ===
+
ie. if you wanted,<br />a &lt;= b<br />you would have to do,<br />b &gt;= a
Displays a message in the game console messages area. Will remain until the user-specified message timeout has elapsed.
 
  
Parameters:<br />
+
Or use an external lua file as mentioned in the next section.
'''text''' - a string identifying the'' text'' from a language file.
 
  
=== addConsoleLangText(text)===
+
== Loading a Lua File ==
Displays a message in the game console messages area. Will remain until the message timeout has elapsed. Works like <tt>displayFormattedText()</tt> besides the fact that <tt>addConsoleLangText()</tt> uses the language-file for resolving the format of the text.
+
To run Lua code in an external file you use the dofile function and provide the file path from the executable.
  
Parameters:<br />
+
Example:
'''text''' - a string identifying the ''text'' from a language file.
 
  
=== setDisplayText(text) ===
+
dofile("gae_scenarios/Tutorials/basic_tutorial/startup.lua")
Displays a message at the top of the screen. Will remain until dismissed with <tt>clearDisplayText()</tt> or <tt>setDisplayText()</tt> is called again.
 
  
Parameters:<br />
+
== Language System ==
'''text''' - a string identifying the ''text'' from a language file.
+
Each scenario is stored in its own folder. In this folder should be an xml file of the same name as the folder with xml as the extension. Glest also looks for a lng file (scenario_name_english.lng as default) to allow for translations of text.
  
===displayFormattedText (fmt, ...)===
+
=== Example ===
Works like <tt>setDisplayText()</tt> but allows formatting of text.
+
In advanced_tutorial.xml is :<br />showMessage('MagicBrief', 'GlestAdvancedTutorial')
  
Parameters:<br />
+
In advanced_tutorial_english.lng is :<br />MagicBrief=You are in command of the Magic faction, which uses mages and summoned creatures to fight.
'''fmt''' - a string identifying the format of text ''(like in printf)''.<br />
+
== Coordinates ==
'''...''' - variable parameter list to pass values to fmt ''(like in printf)''.
+
Coordinates are specified as an array of two elements, the 'x' coordinate in the first element, and the 'y' coordinate in the second.
  
===displayFormattedLangText (fmt, ...)===
+
The origin {0,0} is at the 'top left' (or north-west if you like) of the screen. A map's size is defined in 'Tiles', each of which is a block of 2x2 Cells. For technical reasons the last row &amp; column of Tiles are not valid. So a 64 * 64 map is (64-1)*2 = 126 Cells wide and high. The co-ordinates you supply in LUA are Cell coordinates, not Tile coordinates, and are 'zero indexed' (the first one is 0, the last is NumCells - 1).
Works like <tt>displayFormattedText()</tt> but uses the language-file for resolving the format of the text.
 
  
Parameters:<br />
+
eg. A 128 x 128 Map has 254 x 254 Cells. The northwest corner is {0,0} and the southeast corner is {253,253}.
'''fmt''' - a string identifying the format of text ''(like in printf)''.<br />
 
'''...''' - variable parameter list to pass values to fmt ''(like in printf)''.
 
  
=== clearDisplayText() ===
+
When a function returns a 'Vec2i' you can access the individual co-ordinates by sub-scripting the array,
Clears the message from the top of the screen previously set with <tt>setDisplayText()</tt>.
+
myPos = someFunction ()  
 +
x = myPos[1]
 +
y = myPos[2]
 +
When ever there is a parameter requiring positions of type Vec2i you can use the format '''{x,y}''' (where x and y are number values within the required range, as defined above) to select a position on the map.
 +
someFunction ( {x,y} )
 +
Here 'x' and 'y' could be numbers, variables, or 'expressions'.
  
==Unit==
+
You can also pass a 'pre created' array to these functions, which may be useful for scripting advanced scenarios.
=== createUnit(unitID, faction, pos) ===
 
Creates a unit. If ''pos'' is occupied, a nearby cell will be chosen. The game attempts to keep a 2 cell 'border' between the new unit and other units or objects (eg, trees). If a position can not be found, the game crashes.
 
  
Parameters:<br />'''unit''' - name of a unit in the loaded factions.<br />'''faction''' - the index of the faction this unit will belong to.<br />'''pos''' - an array of two elements, specifying the co-ordinates {x,y}.
+
== Faction Index and Players ==
=== createUnitNoSpacing(unitID, faction, pos) ===
+
You need to specify the players like:
Same as above, but position is exact.
+
&lt;players&gt;
 +
&lt;player control="human" faction="tech" team="1"/&gt;
 +
&lt;player control="cpu" faction="magic" team="2"/&gt;
 +
&lt;player control="closed"/&gt;
 +
&lt;player control="closed"/&gt;
 +
&lt;/players&gt;
 +
The first player's factionIndex is 0. The second player's factionIndex is 1 and so on. There must be exactly 4 player tags.
  
  
===destroyUnit(unitID)===
 
Destroys a unit.
 
  
Parameters:<br />
+
== Commands ==
'''unitID''' - the ID of the unit to destroy.
 
  
=== morphToUnit(unitID, morphName, ignoreRequirements) ===
 
Morphs a unit into another unit of type morphName. If ignoreRequirements is set to 1 then the morph is executed even if the unit does not satisfy the morph requirements.
 
  
Parameters:<br />
+
WARNING: All of these functions return type void and''' '''should''' not''' be used as arguments for other functions.
'''unitID''' - the ID of a unit.<br />
+
=== showMessage ( text, header ) ===
'''morphName''' - the name of the morph to execute.<br />
+
Displays a message box on the screen, that will have to be dismissed by the player.
'''ignoreRequirements''' - a 0 or 1 value indicating whether to respect morph requirements (0) or not (1)
 
 
 
===setUnitPosition(unitId, pos)===
 
"Teleports" unit to the given position (places the unit there instantly, no move animation).
 
 
 
Parameters:<br />
 
'''unitID''' - the ID of the unit to move.<br />
 
'''pos''' - the x and y coordinates of the location you wish to move the unit to (note the exact position may not be the supplied position, as the unit may be slightly staggered, particularly if a unit already exists in the given location).
 
 
 
=== moveToUnit(unitID, destUnitID) ===
 
Move unitID to the location of destUnitID.
 
 
 
Parameters:<br />
 
'''unitID''' - the ID of the unit to move (starting location).<br />
 
'''destUnitID''' - the ID of the unit to move to (ending location of unitID). This would essentially make unitID 'follow' destUnitID until it arrives at the location of destUnitID.
 
 
 
===giveStopCommand(unitID)===
 
Gives a stop command to a specific unit.
 
 
 
Parameters:<br />
 
'''unitID''' - the ID of a unit that has a stop command.
 
 
 
===giveAttackCommand(unitID, unitToAttackID)===
 
Instruct a unit to carry out a command of type 'attack' on a specific unit.
 
 
 
Parameters:<br />
 
'''unitID''' - the ID of a unit that has an attack command.
 
'''unitToAttackID''' - the ID of a unit that should be attacked.
 
 
 
=== giveAttackStoppedCommand(unitID, valueName, ignoreRequirements) ===
 
Executes the attack stopped command for a unit specified by 'valueName'. If ignoreRequirements is set to 1 then the command is executed even if the unit does not satisfy the command requirements.
 
 
 
Parameters:<br />
 
'''unitID''' - the ID of a unit.<br />
 
'''valueName''' - the name of the attack stopped command to execute.<br />
 
'''ignoreRequirements''' - a 0 or 1 value indicating whether to respect command requirements (0) or not (1).
 
 
 
=== giveResource(resource, faction, amount) ===
 
Give an amount of a specified resource to a player, negative values are valid and have the obvious effect.
 
 
 
Parameters:<br />
 
'''resource''' - a corresponding resource in the techtree.<br />
 
'''faction''' - the index of the faction to give the resource.<br />
 
'''amount''' - the amount of resource the faction will receive.
 
 
 
=== givePositionCommand(unitID, command, pos) ===
 
Instruct a unit to carry out a command of type 'attack' or 'move'. The unit being given the command must have such a command available.
 
 
 
Parameters:<br />
 
'''unitID''' - the ID of a unit that has an attack and/or move command.<br />
 
'''command''' - the type of command to carry out ('attack' or 'move')<br />
 
'''pos''' - an array of two elements, specifying the co-ordinates {x,y}.
 
 
 
=== giveProductionCommand(unitID, produced) ===
 
Instruct a unit to carry out a command of type 'produce'. The unit being given the command must have such a command available.
 
 
 
Parameters:<br />
 
'''unitID''' - the ID of a unit that is to produce the new unit.<br />
 
'''produced''' - the name of the unit to produce.
 
 
 
=== giveUpgradeCommand(unitID, upgrade) ===
 
Instruct a unit to carry out a command of type 'upgrade'. The unit being given the command must have such a command available.
 
 
 
Parameters:<br />
 
'''unitID''' - the ID of the unit to perform the upgrade.<br />
 
'''upgrade '''- the name of the upgrade to perform.
 
 
 
===giveKills(unitID, amount)===
 
Gives a specified unit a certain number of kills (which can be used to level them up).
 
 
 
Parameters:<br />
 
'''unitID''' - The ID of the unit to give the kills to.<br />
 
'''amount''' - The number of kills given.
 
 
 
===getUnitProperty(unitId,typeId)===
 
Returns the value of the type of the unit.
 
The type can be a number between 1 and 5.
 
1=hp
 
2=ep
 
3=level
 
4=field
 
5=skill
 
 
 
getUnitProperty is dedicated for hp,ep and field. For skill and level see getUnitPropertyName(unitId,typeId).
 
 
 
===getUnitPropertyName(unitId,typeId)===
 
Returns the name of the type of the unit.
 
The type can be a number between 1 and 5.
 
1=hp
 
2=ep
 
3=level
 
4=field
 
5=skill
 
 
 
getUnitPropertyName is dedicated for skill and level. For hp,ep and field see getUnitProperty(unitId,typeId).
 
 
 
===selectUnit(unitID)===
 
Selects the specified unit.
 
 
 
Parameters:<br />
 
'''unitID''' - The ID of the unit to select.
 
 
 
===unselectUnit(unitID)===
 
Unselects the specified unit (provided it's already selected).
 
 
 
Parameters:<br />
 
'''unitID''' - The ID of the unit to unselect.
 
 
 
===addUnitToGroupSelection(unitID, groupIndex)===
 
Adds the unit to a group, assigned a user defined group index.
 
 
 
Parameters:<br />
 
'''unitID''' - The ID of the unit to select.<br />
 
'''groupIndex''' - A number to identify the group.
 
 
 
===removeUnitFromGroupSelection(unitID, groupIndex)===
 
Removes the unit from a group of the defined group index.
 
  
Parameters:<br />
+
Parameters:<br />'''text''' - a string identifying the'' text'' from a language file<br />'''header''' - a string identifying the'' title bar text ''from a language file
'''unitID''' - The ID of the unit to select.<br />
 
'''groupIndex''' - The previously assigned index of the group.
 
  
===recallGroupSelection(groupIndex)===
+
=== setDisplayText ( text ) ===
Reselects a previously defined group by its group index.
 
  
Parameters:<br />
 
'''groupIndex''' - The previously assigned index of the group.
 
  
===highlightUnit(unitID, radius, thickness, colour)===
+
Displays a message at the top of the 'playing area'. Will remain until dismissed with clearDisplayText() or setDisplayText() is called again.
Places a coloured circle around a unit.
 
  
Parameters:<br />
+
Parameters:<br />'''text''' - a string identifying the'' text'' from a language file
'''unitID''' - unit ID of the target unit.<br />
 
'''radius''' - the radius, in Glest tiles, of the circle.<br />
 
'''thickness''' - thickness of the circle.<br />
 
'''colour''' - the colour of the circle.
 
  
===unhighlightUnit(unitID)===
+
=== clearDisplayText () ===
Removes a previously placed highlight from a unit.
+
Clears the message from the top of the playing area, previously set with setDisplayText().
 
+
=== setCameraPosition ( pos ) ===
Parameters:<br />
 
'''unitID''' - unit ID of the target unit.
 
 
 
==Game==
 
=== setCameraPosition(pos) ===
 
 
Move the camera to the coordinates of pos.
 
Move the camera to the coordinates of pos.
  
Parameters:<br />
+
Parameters:<br />'''pos''' - an array of two elements, specifying the co-ordinates {x,y}
'''pos''' - an array of two elements, specifying the co-ordinates {x,y}.
 
 
 
=== shakeCamera(intensity, duration) ===
 
Causes the camera to shake.
 
 
 
Parameters:<br />
 
'''intensity''' - Intensity of the shaking effect<br />
 
'''duration''' - Duration of the shaking effect in update frames (40 equals one second)
 
 
 
=== shakeCameraOnUnit(intensity, duration, unitId) ===
 
Same as above, but the shake intensity is affected by the distance between camera and unit.
 
Useful if the camera should only shake, when the unit is in sight.
 
 
 
Parameters:<br />
 
'''intensity''' - Intensity of the shaking effect<br />
 
'''duration''' - Duration of the shaking effect in update frames (40 equals one second)<br />
 
'''unitId''' - Unit ID of the unit, which should influence the shake intensity
 
 
 
===togglePauseGame(pauseStatus)===
 
Toggle the pause state of the existing game.
 
 
 
Parameters:<br />
 
'''pauseStatus''' - 0 indicates normal game play, 1 indicates a paused game
 
 
 
=== setPlayerAsWinner(factionID) ===
 
Sets the player with index faction ID as the winner. Would typically be followed by <tt>endGame()</tt>.
 
  
Parameters:<br />
+
=== createUnit ( unit, faction, pos ) ===
'''faction '''- the index of the faction.
+
Spawns a unit. If pos is occupied a nearby cell will be chosen. The game attempts to keep a 2 cell 'border' between the new unit and other units or objects (ie. trees). '''Warning''': If a position can not be found, the game crashes.
  
=== endGame() ===
+
Parameters:<br />'''unit''' - name of a unit in the loaded factions.<br />'''faction''' - the index of the faction this unit will belong to.<br />'''pos''' - an array of two elements, specifying the co-ordinates {x,y}
Ends the scenario, bringing up the "you win" screen and asking the player if they want to leave the game. Usually would be called after <tt>setPlayerAsWinner()</tt> when victory conditions have been met.
 
  
=== loadScenario(scenario, keepFactions) ===
+
=== giveResource ( resource, faction, amount ) ===
Loads another scenario from inside an existing scenario. The new scenario must have the same techtree and factions, but map, tileset can change.
+
Give an amount of a specified resource to a player, negative values are valid and have the obvious effect.<br />Parameters:<br />'''resource''' - a corresponding resource in the tech tree<br />'''faction''' - the index of the faction to give the resource<br />'''amount''' - the amount of resource the faction will receive
  
Parameters:<br />
+
=== givePositionCommand ( unitId, command, pos ) ===
'''scenario''' - the name of the scenario to be loaded.<br />
+
Instruct a unit to carry out a command of type 'attack' or 'move'.
'''keepFactions''' - True to call the next scenario with existing factions or false to call the next scenario with only newly defined factions in the new scenario
 
  
===setAttackWarningsEnabled(enabled)===
+
Parameters:<br />'''unitId''' - the id of a unit that has an attack and/or move command.<br />'''command''' - the type of command to carry out ('attack' or 'move')<br />'''pos''' - an array of two elements, specifying the co-ordinates {x,y}
Enables or disables the attack warning system for the player.
 
  
Parameters:<br />
+
=== giveProductionCommand ( unitId, produced ) ===
'''enabled''' - A boolean true or false value, with true enabling the attack warning system and false disabling it.
 
  
===getAttackWarningsEnabled()===
+
Instruct a unit to carry out a command of type 'produce'.
Returns the current status of the attack warnings system (true if enabled, false if disabled).
 
  
===getIsDayTime()===
+
Parameters:<br />'''unitId''' - the id of a unit that is to produce the new unit.<br />'''produced''' - the type of unit to create. (ie. "worker")
Returns if it is day ingame. ( 1 is day and 0 is night )
+
=== giveUpgradeCommand ( unitId, upgrade ) ===
  
===getIsNightTime()===
+
Instruct a unit to carry out a command of type 'upgrade'.
Returns if it is night ingame. ( 1 is night and 0 is day )
 
  
===getTimeOfDay()===
+
Parameters:<br />'''unitId''' - the id of the unit to perform the upgrade.<br />'''upgrade '''- the type of upgrade to perform. (ie. "hell_gate")
Returns the ingame time of the day.
 
  
=== storeSaveGameDate(key, value) ===
+
=== setPlayerAsWinner ( faction ) ===
Stores ''value'' at ''key'' in the savegame.<br />
 
'''''Only available in the onSave-tag!'''''
 
  
Parameters:<br />
+
Sets the player with index 'faction' as the winner, would typically be followed by endGame().
'''key''' - a key string<br />
 
'''value''' - a string that is stored
 
  
=== loadSaveGameDate(key) ===
+
Parameters:<br />'''faction '''- the index of the faction [0-3, Player1=0]
Returns the ''value'' stored at ''key'' in the savegame.<br />
+
=== endGame () ===
'''''Only available in the onLoad-tag!'''''
 
  
Parameters:<br />
+
End the scenario, usually would be called after setPlayerAsWinner() when victory conditions have been met.
'''key''' - a key string
+
===DisplayFormattedText (const char *fmt,...)===
[[Category:MG]]
+
Displays a message at the top of the 'playing area'. Will remain until dismissed with clearDisplayText() or setDisplayText() is called again.
[[Category:Scenarios]]
 
[[Category:Lua]]
 
  
==AI==
+
Parameters:
===enableAi(faction)===
+
'''fmt''' - a string identifying the'' format of text (like in printf)''
 +
'''...''' - variable parameter list to pass values to fmt ''(like in printf)''
 +
===enableAi ( int faction )===
 
Enables a factions AI. All of the faction's units will move with this command.
 
Enables a factions AI. All of the faction's units will move with this command.
  
Parameters:<br />
+
Parameters:
'''faction '''- the index of the faction.
+
'''faction '''- the index of the faction [0-7, Player1=0]
 
+
===disableAi ( int faction )===
===disableAi(faction)===
 
 
Disables a factions AI. None of the faction's units will move with this command.
 
Disables a factions AI. None of the faction's units will move with this command.
  
Parameters:<br />
+
Parameters:
'''faction '''- the index of the faction.
+
'''faction '''- the index of the faction [0-7, Player1=0]
 
+
===bool getAiEnabled ( int faction )===
===getAiEnabled(faction)===
+
Checks the enabled status of a factions AI.
Checks the enabled status of a factions AI. Returns 0 if the AI is disabled, and 1 if enabled.
 
 
 
Parameters:<br />
 
'''faction '''- the index of the faction.
 
  
===enableConsume(faction)===
+
Parameters:
 +
'''faction '''- the index of the faction [0-7, Player1=0]
 +
===enableConsume ( int faction )===
 
Enables a factions requirement to consume resources like food. All of the faction's units will consume food type resources with this command.
 
Enables a factions requirement to consume resources like food. All of the faction's units will consume food type resources with this command.
  
Parameters:<br />
+
Parameters:
'''faction '''- the index of the faction.
+
'''faction '''- the index of the faction [0-7, Player1=0]
 
+
===disableConsume ( int faction )===
===disableConsume(faction)===
 
 
Disbles a factions requirement to consume resources like food. All of the faction's units will not consume food type resources with this command.
 
Disbles a factions requirement to consume resources like food. All of the faction's units will not consume food type resources with this command.
  
Parameters:<br />
+
Parameters:
'''faction '''- the index of the faction.
+
'''faction '''- the index of the faction [0-7, Player1=0]
 +
===bool getConsumeEnabled ( int faction )===
 +
Checks the consume status of a factions AI.
  
===getConsumeEnabled(faction)===
+
Parameters:
Checks the consume status of a factions AI. Returns 0 if disabled, and 1 if enabled.
+
'''faction '''- the index of the faction [0-7, Player1=0]
 +
===giveAttackCommand ( unitId, unitToAttackId )===
 +
Instruct a unit to carry out a command of type 'attack' on a specific unit.
  
Parameters:<br />
+
Parameters:
'''faction '''- the index of the faction.
+
'''unitId''' - the id of a unit that has an attack and/or move command.
 +
'''unitId''' - the id of a unit that should be attacked.
 +
===int registerCellTriggerEventForUnitToUnit ( sourceUnitId, destUnitId )===
 +
Register a cell 'trigger' event. Any time sourceUnit comes next to destUnit the eventID returned by this function will be triggered
  
==Sound==
+
inside an event called '<cellTriggerEvent>'
===playStaticSound(soundFile)===
 
Play a static sound file specified by 'soundFile'.
 
  
Parameters:<br />
+
Parameters:
'''soundFile''' - the filename of the sound file to play.
+
'''sourceUnitId''' - the id of a unit moves next to destUnit.
 +
'''destUnitId''' - the id of a unit that source moves next to.
  
===playStreamingSound(soundFile)===
+
example:
Play a streaming sound file (background music) specified by 'soundFile'.
+
 +
<startup>
 +
 +
        unitA = 'guard'
 +
        unitB = 'castle'
 +
 +
 +
        createUnit(unitB, 1, startLocation(2)) 
 +
        castleUnit= lastCreatedUnit()
 +
        createUnit(unitA, 0, startLocation(2))
 +
        guard= lastCreatedUnit()
 +
 +
        cell_event1 = registerCellTriggerEventForUnitToUnit(guard,castleUnit)
 +
 +
</startup>
 +
<cellTriggerEvent> 
 +
        if triggeredCellEventId() == cell_event1 then
 +
          clearDisplayText()  
 +
          DisplayFormattedText('You captured the FLAG!')
 +
          unregisterCellTriggerEvent(cell_event1)
 +
        end
 +
</cellTriggerEvent>
  
Parameters:<br />
+
===int registerCellTriggerEventForUnitToLocation ( sourceUnitId, Vec2i pos )===
'''soundFile''' - the filename of the sound file to play.
+
Register a cell 'trigger' event. Any time sourceUnit comes into the cell co-ordinates specified by pos, the
  
===stopStreamingSound(soundFile)===
+
event called '<cellTriggerEvent>' is triggered using the eventid returned by this function
Stop playing a streaming sound file (background music) specified by 'soundFile'.
 
  
Parameters:<br />
+
Parameters:
'''soundFile''' - the filename of the sound file to play.
+
'''sourceUnitId''' - the id of a unit moves next to destUnit.
 +
'''Vec2i pos''' - the x and y cell co-ordinates that will trigger the event when sourceUnitID enters the cell
 +
===int registerCellTriggerEventForFactionToUnit ( sourceFactionId, destUnitId )===
 +
Register a cell 'trigger' event. Any time a unit from sourceFaction comes next to destUnit the eventID returned by this function will be triggered
  
===stopAllSound()===
+
inside an event called '<cellTriggerEvent>'
Stop playing all sounds
 
  
==Events==
+
Parameters:
===registerCellTriggerEventForUnitToUnit(sourceUnitID, destUnitID)===
+
'''sourceFactionId''' - the id of a faction who has at least one unit that moves next to destUnit.
Register a cell 'trigger' event. Any time sourceUnit comes next to destUnit the eventID returned by this function will be triggered inside an event called '<cellTriggerEvent>'.
+
'''destUnitId''' - the id of a unit that source moves next to.
  
Parameters:<br />
+
===int registerCellTriggerEventForFactionToLocation ( sourceFactionId,Vec2i pos)===
'''sourceUnitID''' - the ID of a unit moves next to destUnit.<br />
+
Register a cell 'trigger' event. Any time a unit from sourceFaction comes into the cell co-ordinates specified by pos, the
'''destUnitID''' - the ID of a unit that source moves next to.
 
  
Example:
+
event called '<cellTriggerEvent>' is triggered using the eventid returned by this function
<syntaxhighlight lang="lua">
 
<startup>
 
unitA = 'guard';
 
unitB = 'castle';
 
 
 
createUnit(unitB, 1, startLocation(2));
 
castleUnit= lastCreatedUnit();
 
createUnit(unitA, 0, startLocation(2));
 
guard= lastCreatedUnit();
 
 
 
cell_event1 = registerCellTriggerEventForUnitToUnit(guard, castleUnit);
 
</startup>
 
<cellTriggerEvent>  
 
if triggeredCellEventId() == cell_event1 then
 
clearDisplayText();
 
displayFormattedText('You captured the flag!');
 
unregisterCellTriggerEvent(cell_event1);
 
end
 
</cellTriggerEvent>
 
</syntaxhighlight>
 
  
===registerCellTriggerEventForUnitToLocation(sourceUnitID, pos)===
+
Parameters:
Register a cell 'trigger' event. Any time sourceUnit comes into the cell co-ordinates specified by pos, the event called '<cellTriggerEvent>' is triggered using the eventID returned by this function.
+
'''sourceFactionId''' - the id of a faction who has at least one unit that moves next to destUnit.
 +
'''Vec2i pos''' - the x and y cell co-ordinates that will trigger the event when a unit from sourceFactionID enters the cell
  
Parameters:<br />
+
===int getCellTriggerEventCount ( eventId)===
'''sourceUnitID''' - the ID of a unit moves next to destUnit.<br />
+
Returns the number of times the event specified by eventId has been triggered.
'''pos''' - the x and y cell coordinates that will trigger the event when sourceUnitID enters the cell
 
  
===registerCellTriggerEventForFactionToUnit(sourceFactionID, destUnitID)===
+
Parameters:
Register a cell 'trigger' event. Any time a unit from sourceFaction comes next to destUnit the eventID returned by this function will be triggered inside an event called '&lt;cellTriggerEvent>'.
 
  
Parameters:<br />
+
'''eventId''' - the id of a previously registered event
'''sourceFactionID''' - the ID of a faction who has at least one unit that moves next to destUnit.<br />
 
'''destUnitID''' - the ID of a unit that source moves next to.
 
  
===registerCellTriggerEventForFactionToLocation(sourceFactionID, pos)===
 
Register a cell 'trigger' event. Any time a unit from sourceFaction comes into the cell co-ordinates specified by pos, the event called '<cellTriggerEvent>' is triggered using the eventID returned by this function.
 
  
Parameters:<br />
 
'''sourceFactionID''' - the ID of a faction who has at least one unit that moves next to destUnit.<br />
 
'''pos''' - the x and y cell co-ordinates that will trigger the event when a unit from sourceFactionID enters the cell.
 
  
===registerCellAreaTriggerEvent(pos)===
+
===unregisterCellTriggerEvent (eventId)===
Registers a bounding rectangle as a trigger event. This will be triggered by ANY unit moving in or out of the area. To know which unit, use <tt>triggeredEventAreaEntryUnitId()</tt>.
+
Unregister the event specified by eventId.
  
Parameters:<br />
+
Parameters:
'''pos''' - the x and y coordinate of the top left point then the bottom right point (eg, {10,10,5,5} would create a box from points (10,10) to (5,5)).
 
  
 +
'''eventId''' - the id of a previously registered event
  
===registerDayNightEvent()===
+
===int startTimerEvent ()===
Enables the Day/Night Event which will be triggered when night or day starts.
+
Registers a timer and returns its unqiue Id, which can later be compared within a '<timerTriggerEvent>' event.
  
Example:
+
example:
<syntaxhighlight lang="lua">
+
<timerTriggerEvent>
<startup>
+
registerDayNightEvent()
+
    if triggeredTimerEventId() == timer_event1 then
</startup>
+
      if timerEventSecondsElapsed(triggeredTimerEventId()) >= captureTheFlagSeconds then
<dayNightTriggerEvent> 
+
          clearDisplayText()
if getIsDayTime() == 1 then
+
          DisplayFormattedText('Your time ran out of time to capture the FLAG!')
setDisplayText('It is day time, a safer time to roam!')
+
          stopTimerEvent(timer_event1)
    else
+
          unregisterCellTriggerEvent(cell_event1)
setDisplayText('**It is night time, WATCH OUT!**')
+
      end
 
     end
 
     end
</dayNightTriggerEvent>
+
</syntaxhighlight>
+
</timerTriggerEvent>
  
===unregisterDayNightEvent()===
+
===int resetTimerEvent ( eventId)===
Disables the Day/Night Event.
+
Reset the timer specified by eventId. This function also returns the number of seconds elapsed since the timer started.
  
===triggeredEventAreaEntryUnitId()===
+
Parameters:
Returns the unit ID of the unit who entered a registered cell area trigger event.
 
  
===triggeredEventAreaExitUnitId()===
+
'''eventId''' - the id of a previously registered timer
Returns the unit ID of the unit who exited a registered cell area trigger event.
 
  
===lastUnitTriggerEventUnit()===
+
===int stopTimerEvent ( eventId)===
Returns the ID of the Unit which triggered the UnitTriggerEvent.
+
Stop the timer specified by eventId. This function also returns the number of seconds elapsed since the timer started.<br />
  
===lastUnitTriggerEventType()===
+
Parameters:
Returns the ID of property which changed.
 
1=hp
 
2=ep
 
3=level
 
4=field
 
5=skill
 
  
===getCellTriggerEventCount(eventID)===
+
'''eventId''' - the id of a previously registered timer
Returns the number of times the event specified by eventID has been triggered.
 
  
Parameters:<br />
+
===int timerEventSecondsElapsed ( eventId)===
'''eventID''' - the ID of a previously registered event
+
This function returns the number of seconds elapsed since the timer started.
 
 
===triggeredCellEventUnitId()===
 
Can be called in a '&lt;cellTriggerEvent>' to return the unit ID of the unit whom triggered the event.
 
 
 
===unregisterCellTriggerEvent(eventID)===
 
Unregister the event specified by eventID.
 
  
Parameters:<br />
+
Parameters:
'''eventID''' - the ID of a previously registered event.
 
  
===registerUnitTriggerEvent(unitId)===
+
'''eventId''' - the id of a previously registered timer
Registers a unit trigger event for a unit which will be triggered if one of his properties changes.
+
===int triggeredCellEventId ()===
 +
This function returns the eventId that is currently triggering a '<cellTriggerEvent>'
  
Example:
+
===int triggeredTimerEventId ()===
<syntaxhighlight lang="lua">
+
This function returns the eventId that is currently triggering a '<timerTriggerEvent>'
<startup>
 
    createUnit('battle_machine', 1, startLocation(1))
 
  
    player2_battlemachine= lastCreatedUnit()
+
== Queries ==
    registerUnitTriggerEvent(player2_battlemachine)
+
These function return useful information that can be used in command functions.
</startup>
 
<unitTriggerEvent>
 
    if player2_battlemachine == lastUnitTriggerEventUnit() then
 
                       
 
        if lastUnitTriggerEventType() == 1 then -- hp changed
 
            print('Unit hp is now: ' .. getUnitProperty(lastUnitTriggerEventUnit(),lastUnitTriggerEventType()))
 
        elseif lastUnitTriggerEventType() == 2 then -- ep changed
 
            print('Unit ep is now: ' .. getUnitProperty(lastUnitTriggerEventUnit(),lastUnitTriggerEventType()))
 
        elseif lastUnitTriggerEventType() == 3 then -- level changed
 
            print('Unit level is now: ' .. getUnitPropertyName(lastUnitTriggerEventUnit(),lastUnitTriggerEventType()))
 
        elseif lastUnitTriggerEventType() == 4 then -- field changed
 
            print('Unit field is now: ' .. getUnitProperty(lastUnitTriggerEventUnit(),lastUnitTriggerEventType()))
 
        elseif lastUnitTriggerEventType() == 5 then -- skill changed
 
            print('Unit skill is now: ' .. getUnitPropertyName(lastUnitTriggerEventUnit(),lastUnitTriggerEventType()))
 
        end
 
    end
 
</unitTriggerEvent>
 
</syntaxhighlight>
 
  
===unregisterUnitTriggerEvent(unitId)===
+
=== Vec2i startLocation ( faction ) ===
Unregisters the unit trigger event for a unit.
+
Returns the start location for a given faction.
  
===startTimerEvent()===
+
Parameters:
Registers a timer and returns its unqiue ID, which can later be compared within a '<timerTriggerEvent>' event.
+
'''faction '''- the index of the faction [0-3, Player1=0]
  
 
Example:
 
Example:
<syntaxhighlight lang="lua">
+
createUnit ( "someunit", 0, {startLocation(0)[1] + 5, startLocation(0)[2]} )
<timerTriggerEvent>
+
This would create a unit 5 cells east of startLocation 0.
if triggeredTimerEventId() == timer_event1 then
 
if timerEventSecondsElapsed(triggeredTimerEventId()) >= captureTheFlagSeconds then
 
clearDisplayText();
 
displayFormattedText('Your time ran out of time to capture the flag!');
 
stopTimerEvent(timer_event1);
 
unregisterCellTriggerEvent(cell_event1);
 
end
 
end
 
</timerTriggerEvent>
 
</syntaxhighlight>
 
  
===resetTimerEvent(eventID)===
+
=== Vec2i unitPosition ( unitId ) ===
Reset the timer specified by eventID. This function also returns the number of seconds elapsed since the timer started.
 
  
Parameters:<br />
+
Returns the current location of a given unit.
'''eventID''' - the ID of a previously registered timer.
 
 
 
===stopTimerEvent(eventID)===
 
Stop the timer specified by eventID. This function also returns the number of seconds elapsed since the timer started.
 
 
 
Parameters:<br />
 
'''eventID''' - the ID of a previously registered timer.
 
 
 
===timerEventSecondsElapsed(eventID)===
 
This function returns the number of seconds elapsed since the timer started.
 
 
 
Parameters:<br />
 
'''eventID''' - the ID of a previously registered timer.
 
 
 
===triggeredCellEventId()===
 
This function returns the eventID that is currently triggering a '<cellTriggerEvent>'.
 
 
 
===triggeredTimerEventId()===
 
This function returns the eventID that is currently triggering a '<timerTriggerEvent>'.
 
 
 
===startEfficientTimerEvent(triggerSecondsElapsed)===
 
This function creates a timer that will only trigger the timer event after <tt>triggerSecondsElapsed</tt> seconds, then remove the timer.
 
  
==Queries==
+
Parameters:
=== unitPosition(unitID) ===
 
Returns the current location of a given unit.
 
  
Parameters:<br />
+
'''unitId - '''the unitId of the unit whose position you wish to know.
'''unitID - '''the unitID of the unit whose position you wish to know.
 
  
 
Example:
 
Example:
<syntaxhighlight lang="lua">
+
if ( unitPosition(myUnit)[1] &gt; 47 and 75 &gt; unitPosition(myUnit)[1]
if (unitPosition(myUnit)[1] > 47 and 75 > unitPosition(myUnit)[1] and  unitPostion(myUnit)[2] > 95 ) then
+
-- The unit's x co-ord is between 47 and 75, and its y cord is larger than 95.
+
and  unitPostion(myUnit)[2] &gt; 95 ) then
end
+
</syntaxhighlight>
+
  -- The unit's x co-ord is between 47 and 75, and its y cord is larger than 95.
 +
 +
  -- trigger some action here ?
 +
 +
end
  
=== unitFaction(unitID)===
+
=== int unitFaction ( unitId )===
Returns the faction index of the unit with unitID.
+
Returns the faction '''index''' of the unit with unitId.
  
Parameters:<br />
+
=== int resourceAmount ( resource, faction ) ===
'''unitID''' - The ID of the unit whose faction you wish you check.
 
  
=== resourceAmount(resource, faction) ===
 
 
Returns the amount of a given resource is possessed by a faction.
 
Returns the amount of a given resource is possessed by a faction.
  
Parameters:<br />
+
=== string lastCreatedUnitName () ===
'''resource''' - The name of the resource you wish you check.<br />
 
'''faction''' - The index of the faction to check.
 
 
 
===unitName(unitId)===
 
Returns the name of the unit whose unit ID was passed into the function.
 
 
 
Parameters:<br />
 
'''unitID''' - the ID of the unit whose name you wish to know.
 
  
=== lastCreatedUnitName() ===
+
Returns the unit type of the last created unit.
Returns the unit name of the last created unit.
+
=== int lastCreatedUnit () ===
  
=== lastCreatedUnit() ===
 
 
Returns the unit ID of the last created unit.
 
Returns the unit ID of the last created unit.
 +
=== string lastDeadUnitName () ===
  
=== lastDeadUnitName() ===
+
Returns the type of the last unit to die.
Returns the name of the last unit to die.
+
=== int lastDeadUnit ()===
  
=== lastDeadUnit()===
 
 
Returns the ID of the last unit to die.
 
Returns the ID of the last unit to die.
 +
=== int unitCount ( faction ) ===
  
===lastDeadUnitCauseOfDeath()===
 
Returns the following depending on how the last unit died:
 
:None = 0
 
:Attacked = 1
 
:Attack boost = 2
 
:Starved resource = 3
 
:Negative regeneration = 4
 
 
=== lastDeadUnitKillerName() ===
 
Returns the name of the killer of the last dead unit. Returns empty if the cause of death was not from an attacker (attacked).
 
 
=== lastDeadUnitKiller()===
 
Returns the ID of the killer of the last dead unit. Returns -1 if the cause of death was not from an attacker (attacked).
 
 
===lastAttackedUnit()===
 
Returns the ID of the last unit which was attacked.
 
 
===lastAttackedUnitName()===
 
Returns the name of the last unit which was attacked.
 
 
===lastAttackingUnit()===
 
Returns the ID of the last unit to attack.
 
 
===lastAttackingUnitName()===
 
Returns the name of the last unit to attack.
 
 
===getSystemMacroValue(key) ===
 
Returns the value of the SystemMacro in C++ (e.g. $SCENARIO_PATH, $APPLICATIONPATH, $GAMEVERSION). At the moment it is primary used to get the path to the loaded scenario.
 
 
Parameters:<br />
 
'''key - ''' The name of the SystemMacro you want to get. Usually starts with "$". (e.g. $SCENARIO_PATH, $APPLICATIONPATH, $GAMEVERSION)
 
 
Example (will load the file filename.lua in the folder of your scenario):
 
<syntaxhighlight lang="lua">
 
dofile(getSystemMacroValue("$SCENARIO_PATH") .. "filename.lua")
 
</syntaxhighlight>
 
 
=== scenarioDir() ===
 
Does the same as '''getSystemMacroValue("$SCENARIO_PATH")'''. Exist for GAE compatibility.
 
 
 
=== getPlayerName(faction) ===
 
Returns the name of the player of a given faction.
 
 
=== playerName(faction) ===
 
Does the same as '''getPlayerName(faction)'''. Exist for GAE compatibility.
 
 
Parameters:<br />
 
'''faction''' - The index of the faction you wish to check.
 
 
=== unitCount(faction) ===
 
 
Returns the number of units a given faction has.
 
Returns the number of units a given faction has.
 +
=== int unitCountOfType ( faction, type ) ===
  
Parameters:<br />
+
Returns the number of units of a specific type a given faction has.
'''faction''' - The index of the faction you wish to check.
+
== Events ==
 +
These are xml tags used to execute lua code on its specified event. Variables can be used across different events. (TODO: see if events can be nested [Ed: This wont end well&nbsp;;) -silnarm])
  
=== unitCountOfType(faction, name) ===
+
&lt;startup&gt;<br />[insert code]
Returns the number of units of a specific name a given faction has.
 
  
Parameters:<br />
+
&lt;startup&gt;
'''faction''' - The index of the faction you wish to check.<br />
 
'''name''' - The name of the specific unit you wish to check.
 
  
===gameWon()===
+
&lt;unitCreatedOfType type="unitname"&gt;<br />[insert code]<br />&lt;/unitCreatedOfType&gt;
Returns true if the human player won the game, and false if they did not.
 
  
===isGameOver()===
+
&lt;unitDied&gt;<br />[insert code]<br />&lt;/unitDied&gt;
Returns true if the game is over (either by the default game over criteria being met or by calling <tt>endGame()</tt>). Returns false otherwise.
 
  
===startLocation(faction) ===
+
&lt;resourceHarvested&gt;<br />[insert code]<br />&lt;/resourceHarvested&gt;
Returns the start location for a given faction as a set of coordinates.
 
  
Parameters:<br />
+
<gameOver>
'''faction '''- the index of the faction.
+
[insert code]
 +
</gameOver>
  
Example:
+
<cellTriggerEvent>
<syntaxhighlight lang="lua">
 
createUnit ( "someunit", 0, {startLocation(0)[1] + 5, startLocation(0)[2]} )
 
</syntaxhighlight>
 
This would create a unit 5 cells east of startLocation 0.
 
  
===setRandomGenInit(seed)===
+
[insert code]
Generates a random number based on the supplied seed.
 
  
===getRandomGen(minVal, maxVal)===
+
</cellTriggerEvent>
Used with <tt>setRandomGenInit</tt> to get a random number inbetween <tt>minVal</tt> and <tt>maxVal</tt>.
 
  
===getWorldFrameCount()===
+
<timerTriggerEvent>
Retrieves the world frame count, which can be used in seeding random numbers.
 
 
 
===getUnitsForFaction(factionIndex, commandTypeName, field)===
 
Returns an array (table) of units in the specified faction which lists all units which have the specified command and can use it on the specified field (such as being able to attack air units).<br />
 
<tt>0</tt> for land and <tt>1</tt> for air field.
 
[[Category:MG]]
 
[[Category:Scenarios]]
 
[[Category:Lua]]
 
 
 
===getUnitCurrentField(unitId)===
 
For the specified unit, returns <tt>0</tt> if they are land and <tt>1</tt> if they are in the air field.
 
 
 
==Network==
 
===networkShowMessageForFaction(text, header, factionIndex)===
 
Works the same was as <tt>showMessage()</tt>, but only displays the message to the specific faction. Good for network scenarios where it may be beneficial to display different messages to each player.
 
 
 
===networkShowMessageForTeam(text, header, teamIndex)===
 
Works the same was as <tt>networkShowMessageForFaction()</tt> above, but displays to all players in the specified team.
 
 
 
===showMarker(flashCount, factionIndex, note, textureFile, pos)===
 
Places a marker on the map at a given location.
 
 
 
Parameters:<br />
 
'''flashCount''' -<br />
 
'''factionIndex''' - index of the faction who "placed" the marker.<br />
 
'''note''' - note on the marker.<br />
 
'''textureFile''' - path of texture file to use for marker.<br />
 
'''pos''' - the x and y cell coordinates of the marker.
 
 
 
===networkSetCameraPositionForFaction(factionIndex, pos)===
 
Set the camera position for a specific faction.
 
 
 
Parameters:<br />
 
'''factionIndex''' - index of the faction whose camera you wish to move.<br />
 
'''pos''' - x and y coordinates for the camera's position.
 
 
 
===networkSetCameraPositionForTeam(teamNumber, pos)===
 
Set the camera position for all factions on a team.
 
  
Parameters:<br />
 
'''teamNumber''' - team number whose camera you wish to move.<br />
 
'''pos''' - x and y coordinates for the camera's position.
 
  
== XML events ==
+
[insert code]
These are XML tags used to execute Lua code on its specified event. Variables can be used across different events.
 
  
<syntaxhighlight lang="xml"><global>
 
<!--
 
Code here will be executed whenever the scenario is started.
 
-->
 
</global>
 
<onSave>
 
<!--
 
Code here will be executed when the game is about to save.
 
-->
 
</onSave>
 
<onLoad>
 
<!--
 
Code here will be executed when the savegame got loaded.
 
-->
 
</onLoad>
 
<startup>
 
<!--
 
Code here will be executed once on startup.
 
-->
 
</startup>
 
<unitCreatedOfType type="unitname">
 
<!--
 
Code here will be executed every time a unit of the specified
 
type is created.
 
-->
 
</unitCreatedOfType>
 
<unitDied>
 
<!--
 
Code here will be executed every time a unit dies.
 
-->
 
</unitDied>
 
<unitAttacked>
 
<!--
 
Code here will be executed every time a unit gets attacked.
 
-->
 
</unitAttacked>
 
<unitAttacking>
 
<!--
 
Code here will be executed every time a unit is attacking.
 
-->
 
</unitAttacking>
 
<resourceHarvested>
 
<!--
 
Code here will be executed every time a resource is harvested.
 
-->
 
</resourceHarvested>
 
<gameOver>
 
<!--
 
Code here will be executed when the game ends.
 
-->
 
</gameOver>
 
<cellTriggerEvent>
 
<!--
 
Code here will be executed when cell events activate.
 
-->
 
</cellTriggerEvent>
 
<timerTriggerEvent>
 
<!--
 
Code here will be executed when timer events acivate.
 
-->
 
 
</timerTriggerEvent>
 
</timerTriggerEvent>
</syntaxhighlight>
 
 
==See Also==
 
*[[Engines#Lua_scripting|Comparison of Lua functions in the engines]]
 
*[[Lua]]
 
*[[Scenarios]]
 
 
==External Links==
 
*[http://www.lua.org/pil/ Programming in Lua]
 
*[http://lua-users.org/wiki/TutorialDirectory Lua tutorials]
 
*[http://lua-users.org/wiki Lua-Users.org Wiki]
 
 
[[Category:MG]]
 
[[Category:MG]]
[[Category:Scenarios]]
 
[[Category:Lua]]
 
[[Category:XMLs]]
 

Please note that all contributions to MegaGlest are considered to be released under the Creative Commons Attribution Share Alike (see MegaGlest:Copyrights for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource. Do not submit copyrighted work without permission!

To edit this page, please answer the question that appears below (more info):

Cancel Editing help (opens in new window)