Difference between revisions of "MG/Lua"

From MegaGlest
Jump to navigation Jump to search
(10 intermediate revisions by the same user not shown)
Line 1: Line 1:
'''Glest versions 3.2.0 and newer includes lua scripting functionality for scripted scenarios.'''
+
[[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]].
  
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==
 +
=== showMessage(text, header) ===
 +
Displays a message box on the screen, that will have to be dismissed by the player.
  
== Useful Links ==
+
Parameters:<br />
*Omega's tutorial: [http://glest.org/glest_board/index.php?topic=3841.0 tutorial].
+
'''text''' - a string identifying the'' text'' from a language file.<br />
*[http://www.lua.org/pil/ Programming in Lua]
+
'''header''' - a string identifying the'' title bar text ''from a language file.
*[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.
 
  
A solution is to either swap the logic:
+
=== addConsoleText(text) ===
 +
Displays a message in the game console messages area. Will remain until the user-specified message timeout has elapsed.
  
ie. if you wanted,<br />a &lt;= b<br />you would have to do,<br />b &gt;= a
+
Parameters:<br />
 +
'''text''' - a string identifying the'' text'' from a language file.
  
Or use an external lua file as mentioned in the next section.
+
=== addConsoleLangText(const char *fmt, ...)===
 +
Available in rev 2813. 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.
  
== Loading a Lua File ==
+
Parameters:<br />
To run Lua code in an external file you use the dofile function and provide the file path from the executable.
+
'''text''' - a string identifying the ''text'' from a language file.
  
Example:
+
=== setDisplayText(text) ===
 +
Displays a message at the top of the screen. Will remain until dismissed with <tt>clearDisplayText()</tt> or <tt>setDisplayText()</tt> is called again.
  
dofile("gae_scenarios/Tutorials/basic_tutorial/startup.lua")
+
Parameters:<br />
 +
'''text''' - a string identifying the ''text'' from a language file.
  
== Language System ==
+
===displayFormattedText (const char *fmt, ...)===
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.
+
Available in rev 2767. Works like <tt>setDisplayText()</tt> but allows formatting of text.
  
=== Example ===
+
Parameters:<br />
In advanced_tutorial.xml is :<br />showMessage('MagicBrief', 'GlestAdvancedTutorial')
+
'''fmt''' - a string identifying the format of text ''(like in printf)''.<br />
 +
'''...''' - variable parameter list to pass values to fmt ''(like in printf)''.
  
In advanced_tutorial_english.lng is :<br />MagicBrief=You are in command of the Magic faction, which uses mages and summoned creatures to fight.
+
===displayFormattedLangText (const char *fmt, ...)===
== Coordinates ==
+
Available in rev 2767. Works like <tt>displayFormattedText()</tt> but uses the language-file for resolving the format of the text.
Coordinates are specified as an array of two elements, the 'x' coordinate in the first element, and the 'y' coordinate in the second.
 
  
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).
+
Parameters:<br />
 +
'''fmt''' - a string identifying the format of text ''(like in printf)''.<br />
 +
'''...''' - variable parameter list to pass values to fmt ''(like in printf)''.
  
eg. A 128 x 128 Map has 254 x 254 Cells. The northwest corner is {0,0} and the southeast corner is {253,253}.
+
=== clearDisplayText () ===
 +
Clears the message from the top of the screen previously set with <tt>setDisplayText()</tt>.
  
When a function returns a 'Vec2i' you can access the individual co-ordinates by sub-scripting the array,
+
==Unit==
myPos = someFunction ()  
+
=== createUnit(unitID, faction, pos) ===
x = myPos[1]
+
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). '''Warning''': If a position can not be found, the game crashes.
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'.
 
  
You can also pass a 'pre created' array to these functions, which may be useful for scripting advanced scenarios.
+
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 ==
+
=== destroyUnit(unitID) ===
You need to specify the players like:
+
Destroys a unit.
&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.
 
  
 +
Parameters:<br />
 +
'''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.
  
== Commands ==
+
Parameters:<br />
 +
'''unitID''' - the ID of a unit.<br />
 +
'''morphName''' - the name of the morph to execute.<br />
 +
'''ignoreRequirements''' - a 0 or 1 value indicating whether to respect morph requirements (0) or not (1)
  
 +
=== moveToUnit ( unitID, destUnitID ) ===
 +
Move unitID to the location of destUnitID.
  
WARNING: All of these functions return type void and''' '''should''' not''' be used as arguments for other functions.
+
Parameters:<br />
=== showMessage ( text, header ) ===
+
'''unitID''' - the ID of the unit to move (starting location).<br />
Displays a message box on the screen, that will have to be dismissed by the player.
+
'''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.
  
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
+
===giveAttackCommand(unitID, unitToAttackID)===
 +
Instruct a unit to carry out a command of type 'attack' on a specific unit.
  
=== setDisplayText ( text ) ===
+
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.
  
Displays a message at the top of the 'playing area'. Will remain until dismissed with clearDisplayText() or setDisplayText() is called again.
+
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).
  
Parameters:<br />'''text''' - a string identifying the'' text'' from a language file
+
=== giveResource(resource, faction, amount) ===
 +
Give an amount of a specified resource to a player, negative values are valid and have the obvious effect.
  
=== clearDisplayText () ===
+
Parameters:<br />
Clears the message from the top of the playing area, previously set with setDisplayText().
+
'''resource''' - a corresponding resource in the techtree.<br />
=== setCameraPosition ( pos ) ===
+
'''faction''' - the index of the faction to give the resource.<br />
Move the camera to the coordinates of pos.
+
'''amount''' - the amount of resource the faction will receive.
  
Parameters:<br />'''pos''' - an array of two elements, specifying the co-ordinates {x,y}
+
=== 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.
  
=== createUnit ( unit, faction, pos ) ===
+
Parameters:<br />
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.
+
'''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}.
  
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}
+
=== 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.
  
=== giveResource ( resource, faction, amount ) ===
+
Parameters:<br />
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
+
'''unitID''' - the ID of a unit that is to produce the new unit.<br />
 +
'''produced''' - the name of the unit to produce.
  
=== givePositionCommand ( unitId, command, pos ) ===
+
=== giveUpgradeCommand(unitID, upgrade) ===
Instruct a unit to carry out a command of type 'attack' or 'move'.
+
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 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}
+
Parameters:<br />
 +
'''unitID''' - the ID of the unit to perform the upgrade.<br />
 +
'''upgrade '''- the name of the upgrade to perform.
  
=== giveProductionCommand ( unitId, produced ) ===
+
===giveKills(unit, amount)===
 +
Available in rev 2823. Gives a specified unit a certain number of kills (which can be used to level them up).
  
Instruct a unit to carry out a command of type 'produce'.
+
Parameters:<br />
 +
'''unit''' - The ID of the unit to give the kills to.<br />
 +
'''amount''' - The number of kills given.
  
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")
+
==Game==
=== giveUpgradeCommand ( unitId, upgrade ) ===
+
=== setCameraPosition(pos) ===
 +
Move the camera to the coordinates of pos.
  
Instruct a unit to carry out a command of type 'upgrade'.
+
Parameters:<br />
 +
'''pos''' - an array of two elements, specifying the co-ordinates {x,y}.
  
Parameters:<br />'''unitId''' - the id of the unit to perform the upgrade.<br />'''upgrade '''- the type of upgrade to perform. (ie. "hell_gate")
+
===togglePauseGame(pauseStatus)===
 +
Toggle the pause state of the existing game.
  
=== setPlayerAsWinner ( faction ) ===
+
Parameters:<br />
 +
'''pauseStatus''' - 0 indicates normal game play, 1 indicates a paused game
  
Sets the player with index 'faction' as the winner, would typically be followed by endGame().
+
=== setPlayerAsWinner(factionID) ===
 +
Sets the player with index faction ID as the winner. Would typically be followed by <tt>endGame()</tt>.
  
Parameters:<br />'''faction '''- the index of the faction [0-3, Player1=0]
+
Parameters:<br />
=== endGame () ===
+
'''faction '''- the index of the faction.
  
End the scenario, usually would be called after setPlayerAsWinner() when victory conditions have been met.
+
=== endGame() ===
===DisplayFormattedText (const char *fmt,...)===
+
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.
Displays a message at the top of the 'playing area'. Will remain until dismissed with clearDisplayText() or setDisplayText() is called again.
 
  
Parameters:
+
==AI==
'''fmt''' - a string identifying the'' format of text (like in printf)''
+
===enableAi(faction)===
'''...''' - 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:
+
Parameters:<br />
'''faction '''- the index of the faction [0-7, Player1=0]
+
'''faction '''- the index of the faction.
===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:
+
Parameters:<br />
'''faction '''- the index of the faction [0-7, Player1=0]
+
'''faction '''- the index of the faction.
===bool getAiEnabled ( int faction )===
 
Checks the enabled status of a factions AI.
 
  
Parameters:
+
===getAiEnabled(faction)===
'''faction '''- the index of the faction [0-7, Player1=0]
+
Checks the enabled status of a factions AI. Returns 0 if the AI is disabled, and 1 if enabled.
===enableConsume ( int faction )===
+
 
 +
Parameters:<br />
 +
'''faction '''- the index of the faction.
 +
 
 +
===enableConsume(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:
+
Parameters:<br />
'''faction '''- the index of the faction [0-7, Player1=0]
+
'''faction '''- the index of the faction.
===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:
+
Parameters:<br />
'''faction '''- the index of the faction [0-7, Player1=0]
+
'''faction '''- the index of the faction.
===bool getConsumeEnabled ( int faction )===
 
Checks the consume status of a factions AI.
 
  
Parameters:
+
===getConsumeEnabled(faction)===
'''faction '''- the index of the faction [0-7, Player1=0]
+
Checks the consume status of a factions AI. Returns 0 if disabled, and 1 if enabled.
===giveAttackCommand ( unitId, unitToAttackId )===
+
 
Instruct a unit to carry out a command of type 'attack' on a specific unit.
+
Parameters:<br />
 +
'''faction '''- the index of the faction.
  
Parameters:
+
==Sound==
'''unitId''' - the id of a unit that has an attack and/or move command.
+
===playStaticSound(soundFile)===
'''unitId''' - the id of a unit that should be attacked.
+
Play a static sound file specified by 'soundFile'.
===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
 
  
inside an event called '<cellTriggerEvent>'
+
Parameters:<br />
 +
'''soundFile''' - the filename of the sound file to play.
  
Parameters:
+
===playStreamingSound(soundFile)===
'''sourceUnitId''' - the id of a unit moves next to destUnit.
+
Play a streaming sound file (background music) specified by 'soundFile'.
'''destUnitId''' - the id of a unit that source moves next to.
 
  
example:
+
Parameters:<br />
+
'''soundFile''' - the filename of the sound file to play.
<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>
 
  
===int registerCellTriggerEventForUnitToLocation ( sourceUnitId, Vec2i pos )===
+
===stopStreamingSound(soundFile)===
Register a cell 'trigger' event. Any time sourceUnit comes into the cell co-ordinates specified by pos, the
+
Stop playing a streaming sound file (background music) specified by 'soundFile'.
  
event called '<cellTriggerEvent>' is triggered using the eventid returned by this function
+
Parameters:<br />
 +
'''soundFile''' - the filename of the sound file to play.
  
Parameters:
+
===stopAllSound()===
'''sourceUnitId''' - the id of a unit moves next to destUnit.
+
Stop playing all sounds
'''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
 
  
inside an event called '<cellTriggerEvent>'
+
==Events==
 +
===registerCellTriggerEventForUnitToUnit(sourceUnitID, destUnitID)===
 +
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>'.
  
Parameters:
+
Parameters:<br />
'''sourceFactionId''' - the id of a faction who has at least one unit that moves next to destUnit.
+
'''sourceUnitID''' - the ID of a unit moves next to destUnit.<br />
'''destUnitId''' - the id of a unit that source moves next to.
+
'''destUnitID''' - the ID of a unit that source moves next to.
  
===int registerCellTriggerEventForFactionToLocation ( sourceFactionId,Vec2i pos)===
+
Example:
Register a cell 'trigger' event. Any time a unit from sourceFaction comes into the cell co-ordinates specified by pos, the
+
<syntaxhighlight lang="lua">
 +
<startup>
 +
unitA = 'guard';
 +
unitB = 'castle';
  
event called '<cellTriggerEvent>' is triggered using the eventid returned by this function
+
createUnit(unitB, 1, startLocation(2));
 +
castleUnit= lastCreatedUnit();
 +
createUnit(unitA, 0, startLocation(2));
 +
guard= lastCreatedUnit();
  
Parameters:
+
cell_event1 = registerCellTriggerEventForUnitToUnit(guard, castleUnit);
'''sourceFactionId''' - the id of a faction who has at least one unit that moves next to destUnit.
+
</startup>
'''Vec2i pos''' - the x and y cell co-ordinates that will trigger the event when a unit from sourceFactionID enters the cell
+
<cellTriggerEvent> 
 +
if triggeredCellEventId() == cell_event1 then
 +
clearDisplayText();
 +
displayFormattedText('You captured the flag!');
 +
unregisterCellTriggerEvent(cell_event1);
 +
end
 +
</cellTriggerEvent>
 +
</syntaxhighlight>
  
===int getCellTriggerEventCount ( eventId)===
+
===registerCellTriggerEventForUnitToLocation(sourceUnitID, pos)===
Returns the number of times the event specified by eventId has been triggered.
+
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.
  
Parameters:
+
Parameters:<br />
 +
'''sourceUnitID''' - the ID of a unit moves next to destUnit.<br />
 +
'''pos''' - the x and y cell coordinates that will trigger the event when sourceUnitID enters the cell
  
'''eventId''' - the id of a previously registered event
+
===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 inside an event called '<cellTriggerEvent>'.
  
 +
Parameters:<br />
 +
'''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.
  
===unregisterCellTriggerEvent (eventId)===
+
Parameters:<br />
Unregister the event specified by eventId.
+
'''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.
  
Parameters:
+
===getCellTriggerEventCount(eventID)===
 +
Returns the number of times the event specified by eventID has been triggered.
  
'''eventId''' - the id of a previously registered event
+
Parameters:<br />
 +
'''eventID''' - the ID of a previously registered event
  
===int startTimerEvent ()===
+
===unregisterCellTriggerEvent(eventID)===
Registers a timer and returns its unqiue Id, which can later be compared within a '<timerTriggerEvent>' event.
+
Unregister the event specified by eventID.
  
example:
+
Parameters:<br />
<timerTriggerEvent>
+
'''eventID''' - the ID of a previously registered event.
 
    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>
 
  
===int resetTimerEvent ( eventId)===
+
===startTimerEvent()===
Reset the timer specified by eventId. This function also returns the number of seconds elapsed since the timer started.
+
Registers a timer and returns its unqiue ID, which can later be compared within a '<timerTriggerEvent>' event.
  
Parameters:
+
Example:
 +
<syntaxhighlight lang="lua">
 +
<timerTriggerEvent>
 +
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>
  
'''eventId''' - the id of a previously registered timer
+
===resetTimerEvent(eventID)===
 +
Reset the timer specified by eventID. This function also returns the number of seconds elapsed since the timer started.
  
===int stopTimerEvent ( eventId)===
+
Parameters:<br />
Stop the timer specified by eventId. This function also returns the number of seconds elapsed since the timer started.<br />
+
'''eventID''' - the ID of a previously registered timer.
  
Parameters:
+
===int stopTimerEvent(eventID)===
 +
Stop the timer specified by eventID. This function also returns the number of seconds elapsed since the timer started.
  
'''eventId''' - the id of a previously registered timer
+
Parameters:<br />
 +
'''eventID''' - the ID of a previously registered timer.
  
===int timerEventSecondsElapsed ( eventId)===
+
===timerEventSecondsElapsed(eventID)===
 
This function returns the number of seconds elapsed since the timer started.
 
This function returns the number of seconds elapsed since the timer started.
  
Parameters:
+
Parameters:<br />
 +
'''eventID''' - the ID of a previously registered timer.
  
'''eventId''' - the id of a previously registered timer
+
===triggeredCellEventId()===
===int triggeredCellEventId ()===
+
This function returns the eventID that is currently triggering a '<cellTriggerEvent>'.
This function returns the eventId that is currently triggering a '<cellTriggerEvent>'
 
  
===int triggeredTimerEventId ()===
+
===triggeredTimerEventId()===
This function returns the eventId that is currently triggering a '<timerTriggerEvent>'
+
This function returns the eventID that is currently triggering a '<timerTriggerEvent>'.
  
== Queries ==
+
==Queries==
These function return useful information that can be used in command functions.
+
===startLocation(faction) ===
 +
Returns the start location for a given faction as a set of coordinates.
  
=== Vec2i startLocation ( faction ) ===
+
Parameters:<br />
Returns the start location for a given faction.
+
'''faction '''- the index of the faction.
 
 
Parameters:
 
'''faction '''- the index of the faction [0-3, Player1=0]
 
  
 
Example:
 
Example:
createUnit ( "someunit", 0, {startLocation(0)[1] + 5, startLocation(0)[2]} )
+
<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.
 
This would create a unit 5 cells east of startLocation 0.
  
=== Vec2i unitPosition ( unitId ) ===
+
=== unitPosition(unitID) ===
 
 
 
Returns the current location of a given unit.
 
Returns the current location of a given unit.
  
Parameters:
+
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:
if ( unitPosition(myUnit)[1] &gt; 47 and 75 &gt; unitPosition(myUnit)[1]
+
<syntaxhighlight lang="lua">
+
if (unitPosition(myUnit)[1] > 47 and 75 > unitPosition(myUnit)[1] and  unitPostion(myUnit)[2] > 95 ) then
and  unitPostion(myUnit)[2] &gt; 95 ) then
+
-- The unit's x co-ord is between 47 and 75, and its y cord is larger than 95.
+
end
  -- The unit's x co-ord is between 47 and 75, and its y cord is larger than 95.
+
</syntaxhighlight>
 
  -- trigger some action here ?
 
 
end
 
  
=== int unitFaction ( unitId )===
+
=== unitFaction(unitID)===
Returns the faction '''index''' of the unit with unitId.
+
Returns the faction index of the unit with unitID.
  
=== int resourceAmount ( resource, faction ) ===
+
Parameters:<br />
 +
'''unitID''' - The ID of the unit who's 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.
  
=== string lastCreatedUnitName () ===
+
Parameters:<br />
 +
'''resource''' - The name of the resource you wish you check.<br />
 +
'''faction''' - The index of the faction to check.
  
Returns the unit type of the last created unit.
+
=== lastCreatedUnitName() ===
=== int lastCreatedUnit () ===
+
Returns the unit name of the last created unit.
  
 +
=== lastCreatedUnit() ===
 
Returns the unit ID of the last created unit.
 
Returns the unit ID of the last created unit.
=== string lastDeadUnitName () ===
 
  
Returns the type of the last unit to die.
+
=== lastDeadUnitName () ===
=== int lastDeadUnit ()===
+
Returns the name of the last unit to die.
  
 +
=== lastDeadUnit ()===
 
Returns the ID of the last unit to die.
 
Returns the ID of the last unit to die.
=== int unitCount ( faction ) ===
 
  
Returns the number of units a given faction has.
+
===lastDeadUnitCauseOfDeath()===
=== int unitCountOfType ( faction, type ) ===
+
Available in rev 2824. Returns the following depending on how the last unit died:
 +
:None = 0
 +
:Attacked = 1
 +
:Attack boost = 2
 +
:Starved resource = 3
 +
:Negative regeneration = 4
 +
 
 +
===lastAttackedUnit()===
 +
Available in rev 2823. Returns the ID of the last unit which was attacked.
 +
 
 +
===lastAttackedUnitName()===
 +
Available in rev 2823. Returns the name of the last unit which was attacked.
 +
 
 +
===lastAttackingUnit()===
 +
Available in rev 2823. Returns the ID of the last unit to attack.
  
Returns the number of units of a specific type a given faction has.
+
===lastAttackingUnit()===
===bool gameWon ()===
+
Available in rev 2823. Returns the name of the last unit to attack.
Returns true if the human player won the game
 
  
== Events ==
+
=== unitCount(faction) ===
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])
+
Returns the number of units a given faction has.
  
&lt;startup&gt;<br />[insert code]
+
Parameters:<br />
 +
'''faction''' - The index of the faction you wish to check.
  
&lt;startup&gt;
+
=== unitCountOfType(faction, name) ===
 +
Returns the number of units of a specific name a given faction has.
  
&lt;unitCreatedOfType type="unitname"&gt;<br />[insert code]<br />&lt;/unitCreatedOfType&gt;
+
Parameters:<br />
 +
'''faction''' - The index of the faction you wish to check.
 +
'''name''' - The name of the specific unit you wish to check.
  
&lt;unitDied&gt;<br />[insert code]<br />&lt;/unitDied&gt;
+
===gameWon()===
 +
Returns true if the human player won the game, and false if they did not.
  
&lt;resourceHarvested&gt;<br />[insert code]<br />&lt;/resourceHarvested&gt;
+
== XML events ==
 +
These are XML tags used to execute Lua code on its specified event. Variables can be used across different events.
  
 +
<syntaxhighlight lang="xml"><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.
 +
Works with SVN rev 2823.
 +
-->
 +
</unitAttacked>
 +
<unitAttacking>
 +
<!--
 +
Code here will be executed every time a unit is attacking.
 +
Works with SVN rev 2823.
 +
-->
 +
</unitAttacking>
 +
<resourceHarvested>
 +
<!--
 +
Code here will be executed every time a resource is harvested.
 +
-->
 +
</resourceHarvested>
 
<gameOver>
 
<gameOver>
[insert code]
+
<!--
 +
Code here will be executed when the game ends.
 +
-->
 
</gameOver>
 
</gameOver>
 
 
<cellTriggerEvent>
 
<cellTriggerEvent>
 
+
<!--
[insert code]
+
Code here will be executed when cell events activate.
 
+
-->
 
</cellTriggerEvent>
 
</cellTriggerEvent>
 
 
<timerTriggerEvent>
 
<timerTriggerEvent>
 +
<!--
 +
Code here will be executed when timer events acivate.
 +
-->
 +
</timerTriggerEvent>
 +
</syntaxhighlight>
  
 +
==See Also==
 +
*[[Lua]]
 +
*[[Scenarios]]
  
[insert code]
+
==External Links==
 
+
*[http://www.lua.org/pil/ Programming in Lua]
</timerTriggerEvent>
+
*[http://lua-users.org/wiki/TutorialDirectory Lua tutorials]
 +
*[http://lua-users.org/wiki Lua-Users.org Wiki]
 
[[Category:MG]]
 
[[Category:MG]]
 +
[[Category:Scenarios]]

Revision as of 16:39, 19 November 2011

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.

Text

showMessage(text, header)

Displays a message box on the screen, that will have to be dismissed by the player.

Parameters:
text - a string identifying the text from a language file.
header - a string identifying the title bar text from a language file.

addConsoleText(text)

Displays a message in the game console messages area. Will remain until the user-specified message timeout has elapsed.

Parameters:
text - a string identifying the text from a language file.

addConsoleLangText(const char *fmt, ...)

Available in rev 2813. Displays a message in the game console messages area. Will remain until the message timeout has elapsed. Works like displayFormattedText() besides the fact that addConsoleLangText() uses the language-file for resolving the format of the text.

Parameters:
text - a string identifying the text from a language file.

setDisplayText(text)

Displays a message at the top of the screen. Will remain until dismissed with clearDisplayText() or setDisplayText() is called again.

Parameters:
text - a string identifying the text from a language file.

displayFormattedText (const char *fmt, ...)

Available in rev 2767. Works like setDisplayText() but allows formatting of text.

Parameters:
fmt - a string identifying the format of text (like in printf).
... - variable parameter list to pass values to fmt (like in printf).

displayFormattedLangText (const char *fmt, ...)

Available in rev 2767. Works like displayFormattedText() but uses the language-file for resolving the format of the text.

Parameters:
fmt - a string identifying the format of text (like in printf).
... - variable parameter list to pass values to fmt (like in printf).

clearDisplayText ()

Clears the message from the top of the screen previously set with setDisplayText().

Unit

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). Warning: If a position can not be found, the game crashes.

Parameters:
unit - name of a unit in the loaded factions.
faction - the index of the faction this unit will belong to.
pos - an array of two elements, specifying the co-ordinates {x,y}.

destroyUnit(unitID)

Destroys a unit.

Parameters:
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:
unitID - the ID of a unit.
morphName - the name of the morph to execute.
ignoreRequirements - a 0 or 1 value indicating whether to respect morph requirements (0) or not (1)

moveToUnit ( unitID, destUnitID )

Move unitID to the location of destUnitID.

Parameters:
unitID - the ID of the unit to move (starting location).
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.

giveAttackCommand(unitID, unitToAttackID)

Instruct a unit to carry out a command of type 'attack' on a specific unit.

Parameters:
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:
unitID - the ID of a unit.
valueName - the name of the attack stopped command to execute.
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:
resource - a corresponding resource in the techtree.
faction - the index of the faction to give the resource.
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:
unitID - the ID of a unit that has an attack and/or move command.
command - the type of command to carry out ('attack' or 'move')
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:
unitID - the ID of a unit that is to produce the new unit.
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:
unitID - the ID of the unit to perform the upgrade.
upgrade - the name of the upgrade to perform.

giveKills(unit, amount)

Available in rev 2823. Gives a specified unit a certain number of kills (which can be used to level them up).

Parameters:
unit - The ID of the unit to give the kills to.
amount - The number of kills given.

Game

setCameraPosition(pos)

Move the camera to the coordinates of pos.

Parameters:
pos - an array of two elements, specifying the co-ordinates {x,y}.

togglePauseGame(pauseStatus)

Toggle the pause state of the existing game.

Parameters:
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 endGame().

Parameters:
faction - the index of the faction.

endGame()

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 setPlayerAsWinner() when victory conditions have been met.

AI

enableAi(faction)

Enables a factions AI. All of the faction's units will move with this command.

Parameters:
faction - the index of the faction.

disableAi(faction)

Disables a factions AI. None of the faction's units will move with this command.

Parameters:
faction - the index of the faction.

getAiEnabled(faction)

Checks the enabled status of a factions AI. Returns 0 if the AI is disabled, and 1 if enabled.

Parameters:
faction - the index of the faction.

enableConsume(faction)

Enables a factions requirement to consume resources like food. All of the faction's units will consume food type resources with this command.

Parameters:
faction - the index of the 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.

Parameters:
faction - the index of the faction.

getConsumeEnabled(faction)

Checks the consume status of a factions AI. Returns 0 if disabled, and 1 if enabled.

Parameters:
faction - the index of the faction.

Sound

playStaticSound(soundFile)

Play a static sound file specified by 'soundFile'.

Parameters:
soundFile - the filename of the sound file to play.

playStreamingSound(soundFile)

Play a streaming sound file (background music) specified by 'soundFile'.

Parameters:
soundFile - the filename of the sound file to play.

stopStreamingSound(soundFile)

Stop playing a streaming sound file (background music) specified by 'soundFile'.

Parameters:
soundFile - the filename of the sound file to play.

stopAllSound()

Stop playing all sounds

Events

registerCellTriggerEventForUnitToUnit(sourceUnitID, destUnitID)

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

Parameters:
sourceUnitID - the ID of a unit moves next to destUnit.
destUnitID - the ID of a unit that source moves next to.

Example:

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

registerCellTriggerEventForUnitToLocation(sourceUnitID, pos)

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.

Parameters:
sourceUnitID - the ID of a unit moves next to destUnit.
pos - the x and y cell coordinates that will trigger the event when sourceUnitID enters the cell

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 inside an event called '<cellTriggerEvent>'.

Parameters:
sourceFactionID - the ID of a faction who has at least one unit that moves next to destUnit.
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:
sourceFactionID - the ID of a faction who has at least one unit that moves next to destUnit.
pos - the x and y cell co-ordinates that will trigger the event when a unit from sourceFactionID enters the cell.

getCellTriggerEventCount(eventID)

Returns the number of times the event specified by eventID has been triggered.

Parameters:
eventID - the ID of a previously registered event

unregisterCellTriggerEvent(eventID)

Unregister the event specified by eventID.

Parameters:
eventID - the ID of a previously registered event.

startTimerEvent()

Registers a timer and returns its unqiue ID, which can later be compared within a '<timerTriggerEvent>' event.

Example:

<timerTriggerEvent>
	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>

resetTimerEvent(eventID)

Reset the timer specified by eventID. This function also returns the number of seconds elapsed since the timer started.

Parameters:
eventID - the ID of a previously registered timer.

int stopTimerEvent(eventID)

Stop the timer specified by eventID. This function also returns the number of seconds elapsed since the timer started.

Parameters:
eventID - the ID of a previously registered timer.

timerEventSecondsElapsed(eventID)

This function returns the number of seconds elapsed since the timer started.

Parameters:
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>'.

Queries

startLocation(faction)

Returns the start location for a given faction as a set of coordinates.

Parameters:
faction - the index of the faction.

Example:

createUnit ( "someunit", 0, {startLocation(0)[1] + 5, startLocation(0)[2]} )

This would create a unit 5 cells east of startLocation 0.

unitPosition(unitID)

Returns the current location of a given unit.

Parameters:
unitID - the unitID of the unit whose position you wish to know.

Example:

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

unitFaction(unitID)

Returns the faction index of the unit with unitID.

Parameters:
unitID - The ID of the unit who's faction you wish you check.

resourceAmount(resource, faction)

Returns the amount of a given resource is possessed by a faction.

Parameters:
resource - The name of the resource you wish you check.
faction - The index of the faction to check.

lastCreatedUnitName()

Returns the unit name of the last created unit.

lastCreatedUnit()

Returns the unit ID of the last created unit.

lastDeadUnitName ()

Returns the name of the last unit to die.

lastDeadUnit ()

Returns the ID of the last unit to die.

lastDeadUnitCauseOfDeath()

Available in rev 2824. Returns the following depending on how the last unit died:

None = 0
Attacked = 1
Attack boost = 2
Starved resource = 3
Negative regeneration = 4

lastAttackedUnit()

Available in rev 2823. Returns the ID of the last unit which was attacked.

lastAttackedUnitName()

Available in rev 2823. Returns the name of the last unit which was attacked.

lastAttackingUnit()

Available in rev 2823. Returns the ID of the last unit to attack.

lastAttackingUnit()

Available in rev 2823. Returns the name of the last unit to attack.

unitCount(faction)

Returns the number of units a given faction has.

Parameters:
faction - The index of the faction you wish to check.

unitCountOfType(faction, name)

Returns the number of units of a specific name a given faction has.

Parameters:
faction - The index of the faction you wish to check. name - The name of the specific unit you wish to check.

gameWon()

Returns true if the human player won the game, and false if they did not.

XML events

These are XML tags used to execute Lua code on its specified event. Variables can be used across different events.

<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. 
Works with SVN rev 2823.
	-->
</unitAttacked>
<unitAttacking>
	<!--
		Code here will be executed every time a unit is attacking. 
Works with SVN rev 2823.
	-->
</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>

See Also

External Links