MG/Lua

From MegaGlest
(Redirected from MG/Scripted Scenarios)
Jump to: navigation, search

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.

Notice: You can’t use the <-operator in within the XML-events. You can use an external script instead or invert the logic.

Contents

Text[edit]

showMessage(text, header)[edit]

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)[edit]

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(text)[edit]

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)[edit]

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 (fmt, ...)[edit]

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 (fmt, ...)[edit]

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()[edit]

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

Unit[edit]

createUnit(unitID, faction, pos)[edit]

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:
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}.

createUnitNoSpacing(unitID, faction, pos)[edit]

Same as above, but position is exact.


destroyUnit(unitID)[edit]

Destroys a unit.

Parameters:
unitID - the ID of the unit to destroy.

morphToUnit(unitID, morphName, ignoreRequirements)[edit]

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)

setUnitPosition(unitId, pos)[edit]

"Teleports" unit to the given position (places the unit there instantly, no move animation).

Parameters:
unitID - the ID of the unit to move.
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)[edit]

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.

giveStopCommand(unitID)[edit]

Gives a stop command to a specific unit.

Parameters:
unitID - the ID of a unit that has a stop command.

giveAttackCommand(unitID, unitToAttackID)[edit]

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)[edit]

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)[edit]

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)[edit]

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)[edit]

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)[edit]

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(unitID, amount)[edit]

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

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

getUnitProperty(unitId,typeId)[edit]

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)[edit]

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)[edit]

Selects the specified unit.

Parameters:
unitID - The ID of the unit to select.

unselectUnit(unitID)[edit]

Unselects the specified unit (provided it's already selected).

Parameters:
unitID - The ID of the unit to unselect.

addUnitToGroupSelection(unitID, groupIndex)[edit]

Adds the unit to a group, assigned a user defined group index.

Parameters:
unitID - The ID of the unit to select.
groupIndex - A number to identify the group.

removeUnitFromGroupSelection(unitID, groupIndex)[edit]

Removes the unit from a group of the defined group index.

Parameters:
unitID - The ID of the unit to select.
groupIndex - The previously assigned index of the group.

recallGroupSelection(groupIndex)[edit]

Reselects a previously defined group by its group index.

Parameters:
groupIndex - The previously assigned index of the group.

highlightUnit(unitID, radius, thickness, colour)[edit]

Places a coloured circle around a unit.

Parameters:
unitID - unit ID of the target unit.
radius - the radius, in Glest tiles, of the circle.
thickness - thickness of the circle.
colour - the colour of the circle.

unhighlightUnit(unitID)[edit]

Removes a previously placed highlight from a unit.

Parameters:
unitID - unit ID of the target unit.

Game[edit]

setCameraPosition(pos)[edit]

Move the camera to the coordinates of pos.

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

togglePauseGame(pauseStatus)[edit]

Toggle the pause state of the existing game.

Parameters:
pauseStatus - 0 indicates normal game play, 1 indicates a paused game

setPlayerAsWinner(factionID)[edit]

Sets the player with index faction ID as the winner. Would typically be followed by endGame().

Parameters:
faction - the index of the faction.

endGame()[edit]

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.

loadScenario(scenario, keepFactions)[edit]

Loads another scenario from inside an existing scenario. The new scenario must have the same techtree and factions, but map, tileset can change.

Parameters:
scenario - the name of the scenario to be loaded.
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)[edit]

Enables or disables the attack warning system for the player.

Parameters:
enabled - A boolean true or false value, with true enabling the attack warning system and false disabling it.

getAttackWarningsEnabled()[edit]

Returns the current status of the attack warnings system (true if enabled, false if disabled).

getIsDayTime()[edit]

Returns if it is day ingame. ( 1 is day and 0 is night )

getIsNightTime()[edit]

Returns if it is night ingame. ( 1 is night and 0 is day )

getTimeOfDay()[edit]

Returns the ingame time of the day.

storeSaveGameDate(key, value)[edit]

Stores value at key in the savegame.
Only available in the onSave-tag!

Parameters:
key - a key string
value - a string that is stored

loadSaveGameDate(key)[edit]

Returns the value stored at key in the savegame.
Only available in the onLoad-tag!

Parameters:
key - a key string

AI[edit]

enableAi(faction)[edit]

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

Parameters:
faction - the index of the faction.

disableAi(faction)[edit]

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

Parameters:
faction - the index of the faction.

getAiEnabled(faction)[edit]

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)[edit]

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)[edit]

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)[edit]

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

Parameters:
faction - the index of the faction.

Sound[edit]

playStaticSound(soundFile)[edit]

Play a static sound file specified by 'soundFile'.

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

playStreamingSound(soundFile)[edit]

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

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

stopStreamingSound(soundFile)[edit]

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

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

stopAllSound()[edit]

Stop playing all sounds

Events[edit]

registerCellTriggerEventForUnitToUnit(sourceUnitID, destUnitID)[edit]

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)[edit]

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)[edit]

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)[edit]

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.

registerCellAreaTriggerEvent(pos)[edit]

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 triggeredEventAreaEntryUnitId().

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


registerDayNightEvent()[edit]

Enables the Day/Night Event which will be triggered when night or day starts.

Example:

<startup>
	registerDayNightEvent()
</startup>
<dayNightTriggerEvent>   
	if getIsDayTime() == 1 then
		setDisplayText('It is day time, a safer time to roam!')
    else
		setDisplayText('**It is night time, WATCH OUT!**')
    end
</dayNightTriggerEvent>

unregisterDayNightEvent()[edit]

Disables the Day/Night Event.

triggeredEventAreaEntryUnitId()[edit]

Returns the unit ID of the unit who entered a registered cell area trigger event.

triggeredEventAreaExitUnitId()[edit]

Returns the unit ID of the unit who exited a registered cell area trigger event.

lastUnitTriggerEventUnit()[edit]

Returns the ID of the Unit which triggered the UnitTriggerEvent.

lastUnitTriggerEventType()[edit]

Returns the ID of property which changed. 1=hp 2=ep 3=level 4=field 5=skill

getCellTriggerEventCount(eventID)[edit]

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

Parameters:
eventID - the ID of a previously registered event

triggeredCellEventUnitId()[edit]

Can be called in a '<cellTriggerEvent>' to return the unit ID of the unit whom triggered the event.

unregisterCellTriggerEvent(eventID)[edit]

Unregister the event specified by eventID.

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

registerUnitTriggerEvent(unitId)[edit]

Registers a unit trigger event for a unit which will be triggered if one of his properties changes.

Example:

<startup>
    createUnit('battle_machine', 1, startLocation(1))
 
    player2_battlemachine= lastCreatedUnit()		
    registerUnitTriggerEvent(player2_battlemachine)
</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>

unregisterUnitTriggerEvent(unitId)[edit]

Unregisters the unit trigger event for a unit.

startTimerEvent()[edit]

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)[edit]

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.

stopTimerEvent(eventID)[edit]

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)[edit]

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

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

triggeredCellEventId()[edit]

This function returns the eventID that is currently triggering a '<cellTriggerEvent>'.

triggeredTimerEventId()[edit]

This function returns the eventID that is currently triggering a '<timerTriggerEvent>'.

startEfficientTimerEvent(triggerSecondsElapsed)[edit]

This function creates a timer that will only trigger the timer event after triggerSecondsElapsed seconds, then remove the timer.

Queries[edit]

unitPosition(unitID)[edit]

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)[edit]

Returns the faction index of the unit with unitID.

Parameters:
unitID - The ID of the unit whose faction you wish you check.

resourceAmount(resource, faction)[edit]

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.

unitName(unitId)[edit]

Returns the name of the unit whose unit ID was passed into the function.

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

lastCreatedUnitName()[edit]

Returns the unit name of the last created unit.

lastCreatedUnit()[edit]

Returns the unit ID of the last created unit.

lastDeadUnitName()[edit]

Returns the name of the last unit to die.

lastDeadUnit()[edit]

Returns the ID of the last unit to die.

lastDeadUnitCauseOfDeath()[edit]

Returns the following depending on how the last unit died:

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

lastDeadUnitKillerName()[edit]

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()[edit]

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()[edit]

Returns the ID of the last unit which was attacked.

lastAttackedUnitName()[edit]

Returns the name of the last unit which was attacked.

lastAttackingUnit()[edit]

Returns the ID of the last unit to attack.

lastAttackingUnitName()[edit]

Returns the name of the last unit to attack.

getSystemMacroValue(key)[edit]

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

dofile(getSystemMacroValue("$SCENARIO_PATH") .. "filename.lua")

scenarioDir()[edit]

Does the same as getSystemMacroValue("$SCENARIO_PATH"). Exist for GAE compatibility.


getPlayerName(faction)[edit]

Returns the name of the player of a given faction.

playerName(faction)[edit]

Does the same as getPlayerName(faction). Exist for GAE compatibility.

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

unitCount(faction)[edit]

Returns the number of units a given faction has.

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

unitCountOfType(faction, name)[edit]

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()[edit]

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

isGameOver()[edit]

Returns true if the game is over (either by the default game over criteria being met or by calling endGame()). Returns false otherwise.

startLocation(faction)[edit]

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.

setRandomGenInit(seed)[edit]

Generates a random number based on the supplied seed.

getRandomGen(minVal, maxVal)[edit]

Used with setRandomGenInit to get a random number inbetween minVal and maxVal.

getWorldFrameCount()[edit]

Retrieves the world frame count, which can be used in seeding random numbers.

getUnitsForFaction(factionIndex, commandTypeName, field)[edit]

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).
0 for land and 1 for air field.

getUnitCurrentField(unitId)[edit]

For the specified unit, returns 0 if they are land and 1 if they are in the air field.

Network[edit]

networkShowMessageForFaction(text, header, factionIndex)[edit]

Works the same was as showMessage(), 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)[edit]

Works the same was as networkShowMessageForFaction() above, but displays to all players in the specified team.

showMarker(flashCount, factionIndex, note, textureFile, pos)[edit]

Places a marker on the map at a given location.

Parameters:
flashCount -
factionIndex - index of the faction who "placed" the marker.
note - note on the marker.
textureFile - path of texture file to use for marker.
pos - the x and y cell coordinates of the marker.

networkSetCameraPositionForFaction(factionIndex, pos)[edit]

Set the camera position for a specific faction.

Parameters:
factionIndex - index of the faction whose camera you wish to move.
pos - x and y coordinates for the camera's position.

networkSetCameraPositionForTeam(teamNumber, pos)[edit]

Set the camera position for all factions on a team.

Parameters:
teamNumber - team number whose camera you wish to move.
pos - x and y coordinates for the camera's position.

XML events[edit]

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

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

See Also[edit]

External Links[edit]