Back to homepage
LuaGameplay
History
List of gameplay-related functions in the Lua API
LuaFunctions
Updated Wed, 28 Jun 2023 22:16:01 +0000 by Wuzzy

Lua API: Gameplay functions

This page is a list of all gameplay-related functions in the Lua API.

GameFlags functions

GameFlags are boolean settings of the game. You should call these functions only in the onGameInit event. See LuaGlobals#GameFlags.

ClearGameFlags()

Disables all GameFlags.

DisableGameFlags(gameflag, ...)

Disables the listed GameFlags, without changing the status of other GameFlags.

EnableGameFlags(gameflag, ...)

Enables the listed GameFlags, without changing the status of other GameFlags. In missions, no GameFlags are set initially.

GetGameFlag(gameflag)

Returns true if the specified gameflag is enabled, otherwise false .

Turns

SkipTurn()

Forces the current hedgehog to skip its turn.

EndTurn([noTaunts])

Ends the current turn immediately.

Normally, a “Coward” taunt may be played and an announcer message may be shown (depending on the situation). Set the optional noTaunts parameter to true to force the engine to never play a taunt or show a message. noTaunts is false by default.

Retreat(time [, respectGetAwayTimeFactor])

Forces the current turn into the retreating phase, as if the hog made an attack. That is, the current hedgehog is unable to attack or select a weapon, only movement is possible until the retreat time is up.

The retreat time must be set with time in milliseconds. By default, this time is automatically multiplied with get-away time percentage from the game scheme for seamless integration with schemes. If you want to ignore the game scheme and set the retreat time to a fixed value, set respectGetAwayTimeFactor to false .

If the current hedgehog was busy doing an attack, the attack is aborted, no shot is made. If this function is called in the ready phase of a turn, the ready phase continues normally, but the turn will begin in the retreat phase instead.

Note: If you want the turn to end instantly, it is recommended to use EndTurn instead.

SetTurnTimeLeft(newTurnTimeLeft)

Set the remaining turn time in milliseconds. The current remaining turn time can be read from the variable TurnTimeLeft .

SetReadyTimeLeft(newReadyTimeLeft)

Set the remaining ready time in milliseconds. This function should only be called in onNewTurn. The current remaining ready time can be read from the variable ReadyTimeLeft .

SetTurnTimePaused(isPaused)

Pauses the turn time indefinitely if isPaused is set to true , disabled the turn time pause if isPaused is set to false .

GetTurnTimePaused()

Returns true if the turn time is currently paused by SetTurnTimePaused , otherwise returns false .

EndGame()

Makes the game end.

Environment

SetGravity(percent)

Changes the current gravity of the game in percent (relative to default, integer value). Setting it to 100 will set gravity to default gravity of Hedgewars, 200 will double it, etc.

GetGravity()

Returns the current gravity in percent.

SetWaterLine(waterline)

Sets the water level ( WaterLine ) to the specified y-coordinate.

SetWind(windSpeed)

Sets the current wind in the range of -100 to 100 inclusive. Use together with gfDisableWind for full control.

GetWind()

Returns current wind, expressed as a floating point number between -100 to 100 inclusive. Note there may be rounding errors.

SetMaxBuildDistance(distInPx)

Sets the maximum building distance for of girders and rubber bands in pixels to distInPx . If distInPx is 0 , the limit is disabled. If called without arguments, the distance will be reset to the default value.

Explode(x, y, radius[, options])

Cause an explosion or erase land, push or damage gears.

By default, an explosion destroys a circular piece of land and damages and pushes gears in its radius.

The explosion occurs at coordinates (x, y) with the given radius . Assuming 100% damage, the explosion damage at the center equals the explosion radius.

The explosion will also have a visual effect (by spawning an explosion visual gear), unless the radius is very small.

options is a bitmask which can be used to tweak how the explosion behaves:

Flag Meaning
EXPLAutoSound Plays an appropriate sound
EXPLNoDamage Deal no damage to gears
EXPLDoNotTouchHH Do not push hedgehogs
EXPLDoNotTouchAny Do not push any gears
EXPLDontDraw Do not destroy land
EXPLForceDraw Destroy land, even if gfSolidLand is active
EXPLNoGfx Do not show an explosion animation and do not shake the screen
EXPLPoisoned Poison all hedgehogs in explosion radius

options is assumed to be EXPLAutoSound by default. Set options to 0 to disable all flags.

Examples: -- Simple explosion at (100, 50) with radius 50 Explode(100, 50, 50) -- Simple explosion without sound Explode(100, 50, 50, 0) -- Fake explosion which only pushes gears but deals no damage to gears and terrain Explode(500, 1000, 50, EXPLAutoSound + EXPLNoDamage + EXPLDontDraw) -- Erase a circle of land without side effects Explode(500, 100, 100, EXPLNoDamage + EXPLDoNotTouchAny + EXPLNoGfx)

GetEngineString(stringType, msgId) (1.1.0-dev)

Returns a string that is used in the engine in localized form. For example, "Round draw!". Useful to avoid repeating common gameplay-relevant texts in Lua which reduces redundancy.

  • stringType : One of:
    • "TMsgStrId" for basic messages (section 01 in en.txt ) or
    • "TGoalStrId" for strings used to describe game rules in the mission panel (section 05 in en.txt )
  • msgId : The corresponding message ID (see StringIDs)

Example: -- Shows the "round draw" text from the engine, localized to the player's language AddCaption(GetEngineString("TMsgStrId", sidDraw), capcolDefault, capgrpGameState)

For engine strings that use placeholders like %1 , you can use formatEngineString from the Utils library.

Ammo

SetAmmo(ammoType, count, probability, delay, numberInCrate)

This updates the settings (initial ammo, crate probability, etc.) for a specified ammo type. This must only be used in the onAmmoStoreInit() event handler. In other places, this function will not work.

In Lua missions, for all ammo types, the ammo count, probability, delay and number in crates is set to 0 initially. Note: This also includes skip!

Parameters:

  • ammoType : Ammo type to be set
  • count : Initial ammo count. 9 = infinite
  • probability : Crate probability. Value between 0 (never) and 8 (highest probability)
  • delay : Number of rounds this ammo is delayed
  • numberInCrate : Amount of ammo in a crate

Example:

SetAmmo(amShotgun, 9, 0, 0, 0) -- unlimited amount of shotgun ammo for players SetAmmo(amGrenade, 0, 0, 0, 3) -- crates should contain always three grenade SetAmmo(amSkip, 9, 0, 0, 0) -- enable skip

Hint: It is recommended to always enable skip in missions. Only in exceptional circumstances you should choose to not enable skip.

GetAmmo(ammoType)

Returns ammo settings (initial ammo, crate probability, etc.) for a specified ammo type. This function is analogue to SetAmmo .

This function returns four numbers, in this order: initial ammo count, probability, delay and number in crate. These values correspond to the parameters 2-5 provided in SetAmmo and have the same meaning.

The delay has a special case. If delay is 10000 or greater, then this means you're in the hedgehog placement phase. To get the “true” delay (after the placement phase is over), you must subtract 10000 from this value.

Example:

count, prob, delay, numberInCrate = GetAmmo(amGrenade) -- Get ammo settings of amGrenade

SetAmmoDelay(ammoType, delay)

Changes the delay of a specified Ammo Type. If delay is set to 9999 , the ammo type is disabled indefinitely.

SetAmmoTexts(ammoType, name, caption, description [, showExtra])

Allows you to overwrite the displayed name and tooltip descriptions of a given ammo type. This function must only be called either inside the onGameStart callback function, or after the engine has called onGameStart .

  • ammoType : The ammo type to set the text for
  • name : Name of the ammo type (e.g. “Grenade” for amGrenade ), affects both name in ammo menu and in the “ticker” message on the screen top.
  • caption : The second line in the ammo menu (below the title). E.g. “Timed grenade” for amGrenade .
  • description : Description text in ammo menu, below the caption.
  • showExtra : If false the special “extra” text line like “Weapon is not yet available” or “Weapon does not end turn” will be suppressed

title , caption , description can be nil , in which case they will be reverted to the engine default value. This function returns nil .

Example: -- Overwrites bazooka name and description SetAmmoTexts(amBazooka, "Spoon Missile", "Crazy weapon", "This crazy weapon looks like a spoon and explodes on impact.|Attack: Hold to launch with more power")

SetAmmoDescriptionAppendix(ammoType, descAppend)

Will set a string descAppend to be appended below the “core” description (ammo tooltip) of the specified ammoType , without changing the ordinary description. Note that calling this function always sets the complete appended string, you can't use this function to append multiple texts in row.

This function is recommended if you have tweaked an existing ammo type only a little and want to keep the original description intact as much as possible.

Example: -- Appends a text to the ammo tooltip of the bazooka but leaves name and main description intact SetAmmoTexts(amBazooka, "This weapon deals double the damage than usually.")

AddAmmo(gearUid, ammoType [, ammoCount])

Adds or sets the amount of ammo to the specified hedgehog gear.

If ammoCount is nil , then X ammos of the type ammoType will be added to gearUid , where X equals the “number in crate” setting of the weapon scheme, or, if onAmmoStoreInit() is used, X equals the numberInCrate argument passed via SetAmmo() in the onAmmoStoreInit() event handler. Note that if you use onAmmoStoreInit() , numberInCrate defaults to 0 if SetAmmo() was not called for the ammo type before.

If ammoCount is a number, the ammo will not be added, but instead set to ammoCount . A value of 0 will remove the ammo, a value of AMMO_INFINITE will set it to infinite.

Note: By default, ammo is per-team, so calling AddAmmo for a hedgehog will add/set the ammo for the whole team. The game flags gfPerHogAmmo and gfSharedAmmo change how ammo is managed in the game, so these game flags also affect AddAmmo .

GetAmmoName(ammoType [, ignoreOverwrite ])

Returns the localized name for the specified ammoType , taking an ammo name overwritten by SetAmmoTexts into account. If ignoreOverwrite is true , this function will always return the original ammo name of the weapon and ignores names which may have been overwritten by SetAmmoTexts .

SetAmmoSlot(ammoType, slot)

Sets the slot number of ammoType to the given slot (counting starts from 1).

Use with care! It is your responsibility that each ammo slot does not hold more weapons than the maximum ammo menu width, otherwise, crashes are possible. Test with a full ammo menu to be sure.

Use this function only if you absolutely must! For usability reasons and to help the player's muscle memory, we should normally not re-arrange the weapons. This function was actually only created for the “Frenzy” game style in which we needed to re-arrange the ammo slots to give each weapon an unique ammo slot.

Map

MapHasBorder()

Returns true / false if the map has a border or not.

TestRectForObstacle(x1, y1, x2, y2, landOnly)

Checks the rectangle between the given coordinates for possible collisions. Set landOnly to true if you don’t want to check for collisions with gears (hedgehogs, etc.).

PlaceGirder(x, y, frameIdx)

Attempts to place a girder with centre points x , y and a certain length and orientation, specified by frameIdx . The girder can only be placed in open space and must not collide with anything so this function may fail. It will return true on successful placement and false on failure.

These are the accepted values for frameIdx :

frameIdx Length Orientation
0 short horizontal
1 short decreasing right
2 short vertical
3 short increasing right
4 long horizontal
5 long decreasing right
6 long vertical
7 long increasing right

PlaceRubber(x, y, frameIdx)

Attempts to place a rubber with centre points x , y and a certain orientation, specified by frameIdx . The rubber can only be placed in open space and must not collide with anything so this function may fail. It will return true on successful placement and false on failure.

These are the accepted values for frameIdx :

frameIdx Orientation
0 horizontal
1 decreasing right
2 vertical
3 increasing right

PlaceSprite(x, y, sprite, frameIdx, tint, behind, flipHoriz, flipVert, [, landFlag, ...])

Places a sprite at the specified position ( x , y ) on the map, it behaves like terrain then. Unlike PlaceGirder , this function does not check for collisions, so the sprite can be placed anywhere within map boundaries. The function returns true if the placement was successful, false otherwise. frameIdx is the frame index starting by 0. frameIdx is used if the sprite consists of several sub-images. Only a subset of the sprites is currently supported by this function:

  • sprAmGirder
  • sprAmRubber
  • sprAMSlot
  • sprAMAmmos
  • sprAMAmmosBW
  • sprAMCorners
  • sprHHTelepMask
  • sprTurnsLeft
  • sprSpeechCorner
  • sprSpeechEdge
  • sprSpeechTail
  • sprTargetBee
  • sprThoughtCorner
  • sprThoughtEdge
  • sprThoughtTail
  • sprShoutCorner
  • sprShoutEdge
  • sprShoutTail
  • sprBotlevels
  • sprIceTexture
  • sprCustom1
  • sprCustom2

tint is for an RGBA colouring to apply, this works about the same as Tint in gears. If nil , the original color is used.

behind indicates the sprite should not replace existing land.

flipHoriz and flipVert are for mirroring the sprite vertically and horizontally before placing, respectively.

The 9th and later arguments specify land flags (see the constants section) to be used for the newly created terrain. If omitted, lfNormal is assumed.

Example:

PlaceSprite(2836, 634, sprAmGirder, 5) -- Places the girder sprite as normal terrain at (2836, 634). The `frameIdx` 5 is for the long decreasing right girder. PlaceSprite(1411, 625, sprAmRubber, 1, nil, nil, nil, nil, lfBouncy) -- Places the rubber band sprite as bouncy terrain at (2836, 634). The `frameIdx` 1 is for the decreasing right rubber band.

EraseSprite(x, y, sprite, frameIdx, eraseOnLFMatch, onlyEraseLF, flipHoriz, flipVert, [, landFlag, ...])

Erases a sprite at the specified position ( x , y ) on the map. frameIdx is the frame index starting by 0. sprite , frameIdx , flipHoriz and flipVert behave the same as in PlaceSprite . For sprite , the same subset of sprites is permitted.

Set eraseOnLFMatch to true to erase all land for a pixel that matches any of the passed in land flags. This is useful if, for example, an lfBouncy sprite was placed “behind” land using PlaceSprite and you want to remove it without destroying the non-bouncy terrain.

Set onlyEraseLF to true to only remove specific land flags. If for example a sprite consists of lfIndestructible and lfBouncy , and you call EraseSprite with onlyEraseLF and lfIndestructible set, the sprite will remain bouncy but can be destroyed. You can use this to entirely remove all land flags from a sprite—at this point the sprite will be visual only, painted on the map but with no collision.

Examples:

EraseSprite(2836, 634, sprAmGirder, 5) -- Removes the girder sprite at (2836, 634). The frameIdx 5 is for the long decreasing right girder. EraseSprite(1411, 625, sprAmRubber, 1, true, true, nil, nil, lfIndestructible) -- Removes indestructibility from a rubber band sprite at (2836, 634). The frameIdx 1 is for the decreasing right rubber band.

AddPoint(x, y [, width [, erase] ])

This function is used to draw your own maps using Lua. The maps drawn with this are of type “hand-drawn”.

The function takes a x , y location, a width (means start of a new line) and erase (if false , this function will draw normally, if true , this function will erase drawn stuff).

This function must be called within onGameInit , where MapGen has been set to mgDrawn . You also should call FlushPoints when you are finished with drawing.

See LuaDrawning? for some examples.

FlushPoints()

Makes sure that all the points/lines specified using AddPoint are actually applied to the map. This function must be called within onGameInit .

Current hedgehog

GetCurAmmoType()

Returns the currently selected Ammo Type.

SwitchHog(gearUid)

This function will switch to the hedgehog with the specifiedd gearUid .

SetWeapon(ammoType)

Sets the selected weapon of CurrentHedgehog to one of the Ammo Type.

Examples:

SetWeapon(amBazooka) -- select the bazooka (if hog has one) SetWeapon(amNothing) -- unselects the weapon.

SetNextWeapon()

This function makes the current hedgehog switch to the next weapon in list of available weapons. It can be used for example in trainings to pre-select a weapon.

SetInputMask(mask)

Masks specified player input. mask is a gear message bitmask (see GearMessages). This means that Hedgewars ignores certain player inputs, such as walking or jumping. However, the controls event functions such as onAttack or onLeft will still be called, even when masked.

Example: -- masks the long and high jump commands, making it impossible to jump SetInputMask(band(0xFFFFFFFF, bnot(gmLJump + gmHJump))) -- clears input mask, allowing player to take actions SetInputMask(0xFFFFFFFF) Note: Using the input mask is an effective way to script uninterrupted cinematics, or create modes such as No Jumping.

Note: If you use the Animate library, you should not call SetInputMask directly and use AnimSetInputMask from the library instead. This is because the Animate library uses SetInputMask internally.

See also GearMessages.

GetInputMask()

Returns the current input mask of the player.

SetVampiric(bool)

Toggles vampirism mode for this turn. Set bool to true to enable (same effect as if the hedgehog has used Vampirism), false to disable.

GetVampiric()

Returns true if vampirism mode is currently active.

SetLaserSight(bool)

Toggles laser sight for this turn. Set bool to true to enable (same effect as if the hedgehog has used Laser Sight), false to disable.

GetLaserSight()

Returns true if laser sight (as utility) is currently active. The sniper rifle's built-in laser sight does not count.

EnableSwitchHog()

Enable hog switching mode for the current hedgehog. This function should be called while the hedgehog is standing on solid ground ( GetFlightTime returns 0).

Internally, this tries to spawn a gtSwitcher gear which, as long it exists, handles the hog switching. You can delete this gear to stop the hog switching prematurely. If there already is a gtSwitcher gear, no additional gear is spawned.

On success, returns the gtSwitcher gear being spawned or, if hog switching mode is already active, returns the exsting gear. On failure, returns nil .

Clans and teams

AddTeam(teamname, color, grave, fort, voicepack, flag)

Adds a new team.

You must call it only in onGameInit . You must add at least one hedgehog with AddHog after calling this. The engine does not support empty teams. AddTeam is only supported for singleplayer missions. You must not call this function in multiplayer.

Arguments:

  • teamname : The name of the team (might be force-changed)
  • color : Team color, usually a number from -9 to -1 (see below)
  • grave : The name of the team’s grave (equals file name without the suffix)
  • fort : The name of the team’s fort (equals file name without the suffix and without the letter “L” or “R” before that suffix)
  • voicepack : The name of the team’s voice pack (equals the directory name). Since version 1.0.0, you can append “ _qau ” so Hedgewars will automatically pick the appropriate language version of the voicepack (e.g. instead of “Default”, use “ Default_qau ”). This is preferred.
  • flag : Optional argument for the name of the team’s flag (equals the file name case-sensitively without the suffix). If set to nil or the flag can not be found on the local computer, the flag “hedgewars” is used.

Since version 1.0.0, the team name might be force-changed in case of a naming collision. Since version 1.0.0, this function returns two values: <real team name>, <team index> . For functions that need the team name as input (lke DismissTeam ), you must use this returned <real team name> .

Clan color

Each team must have a color. The color also determines clan membership: Teams with equal color are in the same clan.

The team color is specified as a number from -9 to -1. This will select one of the 9 possible team colors as specified in the player's settings. As the actual colors are set by the player, you can't predict them, but you can usually trust these defaults:

  • -1 : red
  • -2 : blue
  • -3 : cyan
  • -4 : purple
  • -5 : magenta
  • -6 : green
  • -7 : orange
  • -8 : brown
  • -9 : yellow

An older (and now discouraged) method of specifying the color is by hardcoding it as an RGB color (i.e. 0xDD0000 ). This practice is now strongly discouraged because it will ignore the player-chosen color (which is bad for players with color blindness) and in 99% of cases you don't need it anyway. It should be only used for testing and debugging.

Voicepack language

Voicepacks can be localized. A localized voicepack has the language code in its name after an underscore, e.g. “Default_pl” is the Polish version of “Default”. If you specify the exact name in voicepack , Hedgewars uses this exact language version. But if you replace the language suffix with _qau , Hedgewars will try to pick the appropriate localized version of that voicepack, depending on the user's language, if a localized version exists. If not, Hedgewars will pick the version of the voicepack without a language suffix (which is English, normally).

For example, if voicepack is set to “ Default_qau ”, Hedgewars will pick “Default_pl” if the user language is Polish. If the user language is set to a language for which there is no localize version of the Default voicepack, Hedgewars will pick the “Default” voicepack (which is in English).

We strongly recommend to always use the “ _qau ” suffix from version 1.0.0 on, unless you really want to force a particular language.

Example

AddTeam("team 1", -1, "Simple", "Tank", "Default_qau", "hedgewars") --[[ Adds a new team with name “team 1”, the first default color (usually red), the grave “Simple”, the fort “Tank” the voicepack “Default” (in the appropriate language version) and the flag “hedgewars”. ]]

AddMissionTeam(color)

Adds a new team using the player-chosen team identity when playing a singleplayer mission. Does not work in multiplayer.

This function is very similar to AddTeam . Team settings like team name and flag will be taken from the player-chosen team. You only need to specify the clan color, which has the same meaning as in AddTeam .

This function returns two values: <team name>, <team index> . For functions that need the team name as input (lke DismissTeam ), you must use this returned <team name> .

Use AddMissionHog or AddHog afterwards to add hedgehogs for this team. You can mix AddMissionHog and AddHog as you wish.

Example: -- Add mission team with default clan color AddMissionTeam(-1)

GetTeamName(teamIdx)

Returns the name of the team with the index teamIdx . teamIdx is a number between 0 and TeamsCount-1 .

GetTeamIndex(teamname)

Returns the team index (number between 0 and TeamsCount-1 ) of the team with the name teamName .

GetTeamClan(teamname)

Returns the clan ID of the team with the given teamName .

DismissTeam(teamname)

Vaporizes all the hogs of the team with the given team name in a puff of smoke.

This function must not be called while it's the team's turn.

SetTeamLabel(teamname[, label])

Set or remove a label for the team with the given team name. The label is a string and will be displayed next to the team's health bar.

If label is nil , the label will be removed.

There's a special case: If the AI Survival game modifier is active, the AI kill counter will be replaced by the custom team label if it has been set. If label is set to nil , the default AI counter is shown again.

Use this to display a score, power value or another important team attribute. There's no hard length limit, but please try to keep it as short as possible to avoid visual clutter.

SetTeamPassive(teamname, isPassive)

Mark a team as passive if isPassive is true . Passive teams do not participate in the game and are treated like frozen teams. When determining the team order, passive teams are completely ignored.

GetClanColor(clan)

Returns the RGBA color of the chosen clan by its number. The color data type is described in LuaOverview#Color.

SetClanColor(clan, color)

Sets the RGBA color of the chosen clan by its number. The color argument works the same as in AddTeam . The new clan color must be different from the color of all clans (you can't use this function to change clan memberships of teams).

Note: The stats graph does not support clan colors that change in mid-game. If the clan colors change in mid-game, the graph might get confused and shows weird stuff. You may want to turn off the graph with if this is the case (see SendHealthStatsOff ).

Campaign/mission management

SaveCampaignVar(varname, value)

Stores the value value (a string) into the campaign variable varname (also a string). Campaign variables allow you to save progress of a team in a certain campaign. Campaign variables are saved on a per-team per-campaign basis. They are written into the team file (see ConfigurationFiles#TeamName.hwt).

There are some special campaign variables which are used by Hedgewars to determine which missions to display in the campaign menu. This is described here.

GetCampaignVar(varname)

Returns the value of the campaign variable varname as a string. See also SaveCampaignVar .

SaveMissionVar(varname, value)

Stores the value value (a string) into the mission variable varname (also a string). A mission variable is like a campaign variable, but it applies for singleplayer missions only (Training/Challenge/Scenario), excluding campaign missions.

GetMissionVar(varname)

Returns the value of the mission variable varname as a string. See also SaveMissionVar .

Randomness

GetRandom(number)

Returns a randomly generated whole number in the range of 0 to number - 1 . number must be a whole number >= 1. This random number uses the game seed, so is synchronised, and thus safe for multiplayer and saved games.

Use GetRandom for anything that could impact the engine state. For example, a visual gear could simply use Lua’s math.random , but adding a regular gear should use GetRandom .