#summary API for writing Lua scripts in Hedgewars. #labels Featured == Introduction == Version 0.9.13 of Hedgewars introduced the ability to use Lua scripts to modify Hedgewars behaviour for different maps without having to recompile the whole game. The till then used triggers (only appeared in training maps) were removed. Lua is an easy to learn scripting language that's implemented using open source libraries. If you'd like to learn more about Lua, have a look at [http://www.lua.org Lua's official homepage]. Even though its easy to learn syntax this wiki page won't explain all basics of using Lua, e.g. declaring variables or using control structures. There are tons of step-by-step tutorials and documentation available on the internet. Just throw "Lua" into your favourite search engine and give it a try. How Hedgewars handles Lua scripts As of Version 0.9.13 Hedgewars supports Lua scripts for two similar tasks: Define tutorial missions or provide special map behaviour for precreated maps. === About this wiki page === This page tends to become outdated. For a list of undocumented functions, see [http://hw.ercatec.net/docs/lua_wiki_check.php]. === Tutorial missions === Tutorial missions are located within text files inside "share/hedgewars/Data/Missions/Training". The game will list all files with the lua extension inside this directory in the Training selection screen. You'll find some premade example scripts within this directory that contain several comments on the script lines and what they do./ === Special maps === In addition to tutorial missions predrawn maps (maps not created using the random map creator) may contain a single lua script file named "map.lua". If it's there it will be used once the map is played. This way it's possible to play maps alone or over the internet using custom goals. Maps containing lua scripts will be listed with a "Mission:" prefix in map selection. === How Lua scripts are used === Several parts of script files are executed multiple times. In general, the whole script file is read while loading the map. Declarations as well as function calls outside functions are executed at once. Later on the game will call special predefined function names at special occassions such as the creation of new game objects (called gears). === Important things to know === It is possible to play missions in multiplayer. However this requires all participating players to have the exact same version of the map files, including the "map.lua" script file. If this isn't the case the game will probably desync and kick at least the one player using a different version of the map files. To avoid problems when running prepackaged maps, you should never modify any maps provided with the Hedgewars default package. Instead, create a copy of the existing map and modify this one. Feel free to share your work on the forums. Another thing to note is the current status of our scripting implementation. Similar to the whole game, this is still work in progress and we can't guarantee that scripts working in this version will run in future revisions of the game as we might extend, change or rename parts of the scripting engine. === Global variables/constants === Global variables are used by the game to interact with the scripts by passing and retrieving their values. While some of the variables are never read by the engine some allow you to modify the engine's behaviour, e.g. the theme to be used for the current map. === Functions called by the game: Event Handlers === After successfully loading the Lua script the game will call the following functions on different occasions. To be used, they have to use the exact same name as defined below. == Global available Constants ==
LAND_WIDTH, LAND_HEIGHT
!ScreenWidth, !ScreenHeight, !WaterLine
Game flags:
gfForts, gfMultiWeapon, gfBorder, gfSolidLand, gfDivideTeams, gfLowGravity, gfLaserSight, gfInvulnerable, gfMines, gfVampiric, gfKarma, gfArtillery, gfOneClanMode, gfRandomOrder, gfKing, gfPlaceHog, gfSharedAmmo, gfDisableGirders, gfExplosives, gfDisableLandObjects, gfAISurvival, gfInfAttack, gfResetWeps, gfResetHealth, gfPerHogAmmo, gfDisableWind, gfMoreWind, gfTagTeam
*Note:* A few of these, e.g. gfResetHealth (and probably gfTagTeam) are not yet exposed to lua. More constants at [GearTypes Gear Types] , [AmmoTypes Ammo Types], [Sounds], [States], [Sprites], [VisualGearTypes Visual Gear Types] Additional global changing variables accessible: * !ClansCount - number of clans in the game (teams with the same color belong to one clan) * !TeamsCount - number of teams in the game * !TurnTimeLeft - number of game ticks left until the current turn ends * !GameTime - number of total game ticks * !TotalRounds - number of round that has passed * !CurrentHedgehog - the hedgehog gear that is currently in play == Event Handlers == === onGameInit() ===
This function is called before the game loads its resources. One can modify various game variables here:
* Seed = 0 - sets the seed of the random number generator * !EnableGameFlags(gfSolidLand, gfArtillery) - sets the !GameFlags (just 2 of them in this example), see above for the available flags/ * !TurnTime = 60000 - set the turntime in ms * !CaseFreq = 0 - frequency of crate drops * !HealthCaseProb = 35 - chance of receiving a health crate * !HealthCaseAmount = 25 - amount of health in a health crate * !DamagePercent = 100 - percent of damage to inforce * !MinesNum = 0 - number of mines being placed (before 0.9.14 !LandAdds) * !MinesTime = 3 - time for a mine to explode from activated, -1 for random * !MineDudPercent = 0 - chance of mine being a dud * Explosives = 0 - number of explosives being placed * Delay = 0 - delay between each round * !SuddenDeathTurns = 30 - turns until sudden death begins * !WaterRise = 47 - height of water rise at sudden death in pixels * !HealthDecrease = 5 - amount of health decreased on sudden death * Map = "Bamboo" - the map being played * Theme = "Bamboo" - the theme to be used * Ready = 5000 - the ready timer at the start of the round * !MapGen - type of map generator. One of `mgRandom`, `mgMaze`, `mgPerlin`, `mgDrawn`. * !TemplateFilter * Goals = "Jumping is disabled" - if you want to add info to the game mode dialog, use "|" to separate lines If you want to add teams or hogs manually you have to do it here. If you want to draw your own map using `AddPoint` and `FlushPoints`, you have to do this within this function as well. === onGameStart() ===
This function is called when the first round starts.
Can be used to show the mission and for more setup, for example initial target spawning. === onGameTick() ===
This function is called on every game tick, i.e. 1000 times a second. If you just need to check on something periodically, consider...
=== onGameTick20() ===
This function is called every 20 game ticks, i.e. 50 times a second. It reduces lua overhead for simple monitoring that doesn't need to happen every single tick.
=== onNewTurn() ===
This function calls at the start of every turn.
=== onGearAdd(gearUid) ===
This function is called when a new gear is added. Useful in combination with !GetGearType(gearUid).
=== onGearDelete(gearUid) ===
This function is called when a new gear is deleted. Useful in combination with !GetGearType(gearUid).
=== onGearDamage(gearUid, damage) ===
This function is called when a gear is damaged.
Example: function onGearDamage(gear, damage) if (GetGearType(gear) == gtHedgehog) then -- adds a message saying, e.g. "Hoggy H took 25 points of damage" AddCaption(GetHogName(gear) .. ' took ' .. damage .. ' points of damage') end end === onGearResurrect(gearUid) ===
This function is called when a gear is resurrected. CPU Hogs will resurrect if the !GameFlag gfAISurvival is enabled. Alternatively, specific gears can have heResurrectable set to true via !SetEffect.
=== onAmmoStoreInit() ===
This function is called when the game is initialized to request the available ammo and ammo probabilities. Use !SetAmmo here.
=== onNewAmmoStore(team/clan index, hog index) ===
This function is identical to onAmmoStoreInit in function, but is called once per ammo store. This allows different ammo sets for each clan, team or hedgehog depending on the mode.
If gfSharedAmmo is set, the parameters passed are the clan index, and -1, and the function will be called once for each clan. If gfPerHogAmmo is set, the parameters passed are the team index and the hog index in that team, and the function will be called once for each hedgehog. If neither is set, the parameters passed are the team index and -1, and the function will be called once for each team. These indexes can be used to look up details of the clan/team/hedgehog prior to gear creation. Routines to do these lookups will be created as needed. If you add this hook, the expectation is that you will call SetAmmo appropriately. Any values from onAmmoStoreInit are ignored. === onScreenResize() (0.9.16) ===
This function is called when you resize the screen. Useful place to put a redraw function for any vgtHealthTags you're using.
=== onAttack() ===
This function is called when your Hedgehog attacks.
=== onHJump() ===
This function is called when you press the high jump key.
=== onLJump() ===
This function is called when you press the long jump key.
=== onPrecise() ===
This function is called when you press the precise key.
=== onLeft() ===
This function is called when you press the left key.
=== onRight() ===
This function is called when you press the right key.
=== onUp() ===
This function is called when you press the up key.
=== onDown() ===
This function is called when you press the down key.
=== onAttackUp() ===
This function is called when you release the attack key.
=== onDownUp() ===
This function is called when you release the down key.
=== onHogAttack() ===
This function is called when you press the attack key.
=== onLeftUp() ===
This function is called when you release the left key.
=== onPreciseUp() ===
This function is called when you release the precise key.
=== onRightUp() ===
This function is called when you release the right key.
=== onSetWeapon() ===
It is get called when a weapon is selected or switched.
=== onSlot() ===
This function is called when a weapon slot (row in the weapon menu) is selected.
=== onSwitch() ===
This function is called when a hog is switched to another.
=== onTaunt() ===
This function is called when the player uses an animated emote for example "/wave, /juggle and etc.
=== onTimer() ===
This function is called when one of the timer keys is pressed.
=== onUpUp() ===
This function is called when you release the up key.
=== onHogHide() (0.9.16) ===
This function is called when a hedgehog is hidden(removed from the map).
=== onHogRestore() (0.9.16) ===
This function is called when a hedgehog is restored (unhidden).
=== onSpritePlacement(spriteId, centerX, centerY) (0.9.21) === This function is called when a [Sprites Sprite] has been placed. `spriteID` is the type of the sprite, you find a list at [Sprites Sprites]. `centerX` and `centerY` are the coordinates of the center of the sprite. === onGirderPlacement(frameIdx, centerX, centerY) (0.9.21) === This function is called when a girder has been placed. `frameIdx` is an integer and declares the length and orientation of the girder: || `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 || `centerX` and `centerY` are the coordinates of the girder’s center. === onRubberPlacement(frameIdx, centerX, centerY) (0.9.21) === This function is called when a rubber has been placed. `frameIdx` is an integer which stands for the orientation of the rubber. || `frameIdx` || orientation || || 0 || horizontal || || 1 || decreasing right || || 2 || vertical || || 3 || increasing right || `centerX` and `centerY` are the coordinates of the rubber’s center. == Functions for creating gears == === !AddGear(x, y, gearType, state, dx, dy, timer) ===
This creates a new gear at position x,y (measured from top left) of kind gearType (see [GearTypes Gear Types]). The initial velocities are dx and dy. All arguments are numbers. The function returns the uid of the gear created. Gears can have multple states at once: `state` is a bitmask, the flag variables can be found in [States].
Example: local gear = AddGear(0, 0, gtTarget, 0, 0, 0, 0) FindPlace(gear, true, 0, LAND_WIDTH) === !AddVisualGear(x, y, visualGearType, state, critical) ===
This creates a new visual gear at position x,y (measured from top left) of kind visualGearType (see [VisualGearTypes Visual Gear Types]). The function returns the uid of the visual gear created. Set critical to true if the visual gear is crucial to game play. False if it is just an effect, and can be skipped when in fastforward (such as when joining a room). A critical visual gear will always be created, a non-critical one may fail. Most visual gears delete themselves.
Example: -- adds an non-critical explosion at position 1000,1000. Returns 0 if it was not created. vgear = AddVisualGear(1000, 1000, vgtExplosion, 0, false) === !SpawnHealthCrate(x, y) === Spawns a health crate at the specified position. If `x` and `y` are set to 0, the crate will spawn on a random position (but always on land). === !SpawnAmmoCrate(x, y, ammoType) === Spawns an ammo crate at the specified position with content of ammoType (see [AmmoTypes Ammo Types]). If `x` and `y` are set to 0, the crate will spawn on a random position (but always on land). Because by default settings the number of ammo in crates is zero it has to be increased to at least one with SetAmmo first, see the example: Example: SetAmmo(amGrenade, 0, 0, 0, 1) -- see below SpawnAmmoCrate(0, 0, amGrenade) -- x=y=0 means random position on map === !SpawnUtilityCrate(x, y, ammoType) === Spawns an utility crate at specified position with content of ammoType. If `x` and `y` are set to 0, the crate will spawn on a random position (but always on land). Example: SetAmmo(amLaserSight, 0, 0, 0, 1) SpawnUtilityCrate(0, 0, amLaserSight) === !SpawnFakeAmmoCrate(x, y, explode, poison) === Spawns a crate at the specified coordinates which looks exactly like a real ammo crate but contains not any ammo. It can be use useful for scripted events or to create a trap. If `x` and `y` are set to 0, the crate will spawn on a random position (but always on land). `explode` and `poison` are booleans. If `explode` is `true`, the crate will explode when collected. If `poison` is `true`, the collector will be poisoned. Example: SpawnFakeAmmoCrate(500, 432, false, false) -- Spawns a fake ammo crate at the coordinates (500, 434) without explosion and poison. === !SpawnFakeHealthCrate(x, y, explode, poison) === Spawns a crate at the specified coordinates which looks exactly like a real health crate but it will not heal the player. It can be use useful for scripted events or to create a trap. If `x` and `y` are set to 0, the crate will spawn on a random position (but always on land). `explode` and `poison` are booleans. If `explode` is `true`, the crate will explode when collected. If `poison` is `true`, the collector will be poisoned. === !SpawnFakeUtilityCrate(x, y, explode, poison) === Spawns a crate at the specified coordinates which looks exactly like a real utility crate but contains not any ammo. It can be use useful for scripted events or to create a trap. If `x` and `y` are set to 0, the crate will spawn on a random position (but always on land). `explode` and `poison` are booleans. If `explode` is `true`, the crate will explode when collected. If `poison` is `true`, the collector will be poisoned. === !AddHog(hogname, botlevel, health, hat) === Adds a new hedgehog for current team (last created one with the `AddTeam` function), with bot level and specified health, also hat. `botlevel` ranges from `0` to `5`, where `0` denotes a human player and `1` to `5` denote the skill level of a bot. Notice: This works only for singleplayers training missions for now and will desync multiplayer games. Example: local player = AddHog("HH 1", 0, 100, "NoHat") -- botlevel 0 means human player SetGearPosition(player, 1500, 1000) == Functions to get gear properties == === !GetGearType(gearUid) ===
returns one of [GearTypes Gear Types] for the specified gear
=== !GetGearPosition(gearUid) ===
returns x,y coordinates for the specified gear
=== !GetGearRadius(gearUid) ===
Returns radius for the specified gear
=== !GetGearVelocity(gearUid) ===
returns tuple of dx,dy values for the specified gear
=== !GetGearElasticity(gearUid) ===
Returns the elasticity of the specified gear. Useful for determining if a hog is on a rope or not. If a hog is attached to a rope, or is busy firing one, the elasticity of the rope will be non-zero.
=== !GetHogClan(gearUid) ===
returns the clan id of the specified hedgehog gear
=== !GetHogTeamName(gearUid) ===
returns the name of the specified hedgehog gear's team
=== !GetHogName(gearUid) ===
returns the name of the specified hedgehog gear
=== !GetEffect(gearUid, effect) ===
Returns the state of given effect for the given hedgehog gear.
see !SetEffect for further details === !GetHogHat(gearUid) ===
Returns the hat of the specified hedgehog gear
=== !GetAmmoCount(gearUid, ammoType) (0.9.16) ===
Returns the ammo count of the specified ammo type for the specified hedgehog gear.
=== !GetGearTarget(gearUid, x, y) (0.9.16) ===
Returns the x and y coordinate of target-based weapons/utilities. Note: : This can't be used in onGearAdd() but must be called after gear creation.
=== GetX(gearUid) ===
returns x coordinate of the gear
=== GetY(gearUid) ===
returns y coordinate of the gear
=== !GetState(gearUid) === Returns the state of the gear. The gear state is a bitmask which is built out of the variables as shown in [States]. This function is usually used in combination with `band` to extract the truth value of a single flag. It is also used together with `SetState` and `bor` in order to activate a single flag. Examples: local state = GetState(gear) --[[ Stores the full raw bitmask of gear in state. Usually useless on its own. ]] isDrowning = band(GetState(CurrentHedgehog),gstDrowning) ~= 0 --[[ GetState(CurrentHedgehog) returns the state bitmask of CurrentHedgehog, gstDrowning is a bitmask where only the “drowning” bit is set. band does a bitwise AND on both, if it returns a non-zero value, the hedgehog is drowning.]] SetState(CurrentHedgehog, bor(GetState(CurrentHedgehog), gstInvisible)) --[[ first the state bitmask of CurrentHedgehog is bitwise ORed with the gstInvisible flag, thus making the bit responsible for invisiblity to become 1. Then the new bitmask is applied to CurrentHedgehog, thus making it invisible.]] === !GetGearMessage(gearUid) ===
returns the message of the gear.
=== !GetTag(gearUid) === Returns the tag of the specified gear (by `gearUid`). A “tag” of a gear is simply an extra variable to modify misc. things. The meaning of a tag depends on the gear type. For example, for gtBall gears, it specifies the ball color, for gtAirAttack gears (airplane) it specifies the direction of the plane, etc. `tag` has to be an integer. Note that the word “tag” here does _not_ refer to the name and health tags you see above hedgehogs, this is something different. -- This adds a ball (the one from the ballgun) at (123, 456): ball = AddGear(123, 456, gtBall, 0, 0, 0, 0) -- The tag of a ball defines its color. It will automatically chosen at random when created. colorTag = GetTag(ball) -- Now colorTag stores the tag of ball (in this case a number denoting its color) The meaning of tags are described in [GearTypes]. === !GetFollowGear() ===
Returns the uid of the gear that is currently being followed.
=== !GetTimer(gearUid) ===
returns the timer of the gear. This is for example the time it takes for watermelon, mine, etc. to explode. This is also the time used to specify the blowtorch or rcplane time.
=== !GetHealth(gearUid) ===
returns the health of the gear
=== !GetHogLevel(gearUid) ===
returns the bot level from 0 to 5. 0 means human player.
=== !GetVisualGearValues(vgUid) ===
This returns the typically set visual gear values, useful if manipulating things like smoke or bubbles or circles. It returns the following values: X, Y, dX, dY, Angle, Frame, FrameTicks, State, Timer, Tint X, Y typically position, dX, dY typically speed, Angle is usually the rotation angle, Frame is typically the animation frame, FrameTicks is usually an animation counter. State can have a variety of values, but is typically bit packed, Timer is usually the gear lifetime and Tint is the colour. Most visual gears require little to no modification of parameters.
Example: GetVisualGearValues(vgUid) -- return visual gear values == Functions to modify gears == === !HideHog(gearUid) ===
Removes a hedgehog from the map. The hidden hedgehog can be restored with !RestoreHog(gearUid). The current hedgehog cannot be hidden!
Example: gear = AddGear(...) HideHog(gear) -- Hide the newly created gear. === !RestoreHog(gearUid) ===
Restores a previously hidden hedgehog.
Example: gear = AddGear(...) HideHog(gear) -- Hide the newly created gear. RestoreHog(gear) -- Restore the newly hidden gear. === !DeleteGear(gearUid) ===
Deletes a Gear
Example: gear = AddGear(...) DeleteGear(gear) -- Delete the newly created gear. === !DeleteVisualGear(vgUid) ===
Deletes a Visual Gear. Note, most visual gears delete themselves.
Example: vgear = AddVisualGear(...) DeleteVisualGear(vgear) -- Delete the newly created visual gear. === !SetVisualGearValues(vgUid, X, Y, dX, dY, Angle, Frame, FrameTicks, State, Timer, Tint) ===
This allows manipulation of many of the visual gear values. Calling GetVisualGearValues first is recommended on most visual gears unless you are controlling all the key values. In the case of vgtCircle, the visual gear values are mapped as follows. X, Y: position. State: radius. Timer: Thickness. FrameTicks: pulsation speed (0 to disable). dX, dY: min/max pulsation opacity (0-255). Tint: colour, RGBA. Most visual gears require little to no modification of parameters.
Example: -- set a circle to position 1000,1000 pulsing from opacity 20 to 200 (8%-78%), radius of 50, 3px thickness, bright red. SetVisualGearValues(circleUid, 1000,1000, 20, 200, 0, 0, 100, 50, 3, 0xff0000ff) === !FindPlace(gearUid, fall, left, right, tryHarder) (0.9.16) ===
Finds a place for the specified gear between x=left and x=right and places it there. 0.9.16 adds an optional fifth parameter, tryHarder. Setting to true/false will determine whether the engine attempts to make additional passes, even attempting to place gears on top of each other.
Example: gear = AddGear(...) FindPlace(gear, true, 0, LAND_WIDTH) -- places the gear randomly between 0 and LAND_WIDTH === !HogSay(gearUid, text, manner) ===
Makes the specified gear say, think, or shout some text in a bubble.
Example: HogSay(CurrentHedgehog, "I wonder what to do...", SAY_THINK) -- thought bubble with text HogSay(CurrentHedgehog, "I'm hungry...", SAY_SAY) -- speech bubble with text HogSay(CurrentHedgehog, "I smell CAKE!", SAY_SHOUT) -- exclamatory bubble with text === !HogTurnLeft(gearUid, boolean) ===
Faces the specified hog left or right.
Example: HogTurnLeft(CurrentHedgehog, true) -- turns CurrentHedgehog left HogTurnLeft(CurrentHedgehog, false) -- turns CurrentHedgehog right === !SetGearPosition(gearUid, x, y) ===
Places the specified gear exactly at the position (x,y).
=== !SetGearVelocity(gearUid, dx, dy) ===
Gives the specified gear the velocity of dx, dy.
=== !SetAmmo(ammoType, count, probability, delay, numberInCrate) ===
This updates the settings for a specified [AmmoTypes Ammo Type] as of count available for players, spawn probability, availability delay in turns, and the number available in crates. This is supposed to be used in the onAmmoStoreInit() event handler.
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 === !AddAmmo(gearUid, ammoType, ammoCount) (0.9.16) ===
Adds ammoType to the specified gear. The amount added is determined by the arguments passed via !SetAmmo() in the onAmmoStoreInit() event handler. In 0.9.16 ammo can be set directly via the optional third parameter, ammoCount. A value of 0 will remove the weapon, a value of 100 will give infinite ammo. *Note:* The effectiveness of this function may be limited due to problems with gfPerHogAmmo in lua scripting.
=== !SetHealth(gearUid, health) ===
Sets the health of the specified gear. This can be used for purposes other than killing hedgehogs. For example: * Starting the RC Plane 10 shots * Starting Flying Saucer (gtJetpack) with only 50% fuel. * Setting all the mines to duds. * (And more!) function onGearAdd(gear) if (GetGearType(gear) == gtRCPlaane) then SetHealth(gear, 10) end if (GetGearType(gear) == gtJetpack) then SetHealth(gear, 1000) end if (GetGearType(gear) == gtMine) then SetHealth(gear, 0) end end
=== !SetEffect(gearUid, effect, effectState) ===
Sets the state for one of the effects heInvulnerable, heResurrectable, hePoisoned, heResurrected, heFrozen for the specified hedgehog gear. A value of 0 usually means the effect is disabled, values other than that indicate that it is enabled and in some cases specify e.g. the remaining time of that effect.
Example: (sets all bots poisoned) function onGearAdd(gear) if (GetGearType(gear) == gtHedgehog) and (GetBotLevel(gear) > 0) then SetEffect(gear, hePoisoned, 1) end end Note: prior to the ice-gun release, 0.9.19 (commit 10a0a31804f3 ) effectState was of boolean type (true = effect enabled, false = effect disabled) === CopyPV(gearUid, gearUid) ===
This sets the position and velocity of the second gear to the first one.
=== CopyPV2(gearUid, gearUid) (deprecated) ===
This sets the position of the second gear to that of the first one, but makes its velocity twice the one of the first.
Notice: This function is no longer used, use GetGearVelocity and SetGearVelocity instead. === !FollowGear(gearUid) ===
Makes the gameclient follow the specifiec gear.
=== !SetHogName(gearUid, name) ===
Sets the name of the specified hedgehog gear
=== !SetHogTeamName(gearUid, name) ===
Sets the team name of the specified hedgehog gear
=== !SetWeapon(ammoType) ===
Sets the selected weapon of CurrentHedgehog to one of the [AmmoTypes Ammo Type]. Example: AddAmmo(CurrentHedgehog, amBazooka, 1) -- give the CurrentHedgehog a bazooka SetWeapon(amBazooka) -- select the Bazooka.
=== !SetNextWeapon() (0.9.21) === 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. === !SetHogHat(gearUid, hat) ===
Sets the hat of the specified hedgehog gear
=== !SetGearTarget(gearUid, x, y) (0.9.16) ===
Sets the x and y coordinate of target-based weapons/utilities. Note: : This can't be used in onGearAdd() but must be called after gear creation.
=== !SetState(gearUid, state) === Sets the state of the specified gear to the specified `state`. This is a bitmask made out of the variables as seen in [States]. This function is often used together with `GetState` and the bitmask utility functions `band` and `bnot` in order to manipulate a single flag. Examples: SetState(CurrentHedgehog, bor(GetState(CurrentHedgehog), gstInvisible)) --[[ first the state bitmask of CurrentHedgehog is bitwise ORed with the gstInvisible flag, thus making the bit responsible for invisiblity to become 1. Then the new bitmask is applied to CurrentHedgehog, thus making it invisible. ]] SetState(CurrentHedgehog, band(GetState(CurrentHedgehog), bnot(gstInvisible))) --[[ The reverse of the above: This function toggles CurrentHedgehog’s gstInvisible flag off, thus making it visible again. ]] === !SetGearMessage(gearUid, message) ===
Sets the message of the specified gear.
=== !SetTag(gearUid, tag) === Sets the tag of the specified gear (by `gearUid`). A “tag” of a gear is simply an extra variable to modify misc. things. The meaning of a tag depends on the gear type. For example, for gtBall gears, it specifies the ball color, for gtAirAttack gears (airplane) it specifies the direction of the plane, etc. `tag` has to be an integer. Note that the word “tag” here does _not_ refer to the name and health tags you see above hedgehogs, this is something different. -- This adds a ball (the one from the ballgun) at (123, 456): ball = AddGear(123, 456, gtBall, 0, 0, 0, 0) -- This sets the tag of the gear. For gtBall, the tag specified the color. “8” is the color white. SetTag(ball, 8) -- The meaning of tags are described in [GearTypes]. === !SetTimer(gearUid, timer) ===
Sets the timer of the specified gear. Also see !GetTimer.
=== !SetHogLevel(gearUid, level) ===
Sets the bot level from 0 to 5. 0 means human player.
=== !SetGearPos(gearUid, value) (0.9.18-dev) ===
Set pos of specified gear to specified value.
== Gameplay functions == === `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
==== !GetGameFlag(gameflag) ====
Returns true if the specified gameflag is enabled, otherwise false
=== 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 to the specified y-coordinate
==== !SetWind(windSpeed) ====
Sets the current wind in the range of -100 to 100. Use together with gfDisableWind for full control.
==== !EndGame() ====
Makes the game end.
=== Map === ==== !MapHasBorder() ====
Returns true/false if the map has a border or not.
==== !TestRectForObstacle(x1, y1, x2, y2, landOnly) (0.9.16) ====
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, state) (0.9.16) ====
Places a girder with centre points x, y and the chosen state. These are the accepted states: * 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
==== !AddPoint(x, y [, width [, erase] ]) (0.9.21) ==== 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. ==== !FlushPoints() (0.9.21) ==== 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() (0.9.16) ====
Returns the currently selected [AmmoTypes Ammo Type].
==== !SwitchHog(gearUid) (0.9.16) ====
This function will switch to the hedgehog with the specified Uid.
==== !SetInputMask(mask) ====
Masks specified player input.
Example: -- masks the long and high jump commands 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. ==== !GetInputMask() ==== Returns the current input mask of the player. === Randomness === ==== !GetRandom(number) ====
Returns a randomly generated number in the range of 0 to 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 can use the Lua random, but adding a regular gear should use GetRandom.
=== Clans and teams === ==== !AddTeam(teamname, color, grave, fort, voicepack, flag) ====
Adds a new team. Note that this can only be done in `onGameInit`, not at a later time. First argument is the team name followed by color, grave, fort, voicepack and flag settings.
Notice: This works only for singleplayer's training missions for now and will desync multiplayer games. Flag setting is dev only. Example: AddTeam("team 1", 0xDD0000, "Simple", "Island", "Default", "hedgewars") ==== !DismissTeam(teamname) ==== Removes the team with the given team name from the game. ==== !GetClanColor(clan) ====
Returns the colour of the chosen clan by its number.
==== !SetClanColor(clan, color) ====
Sets the colour of the chosen clan by its number.
== Functions affecting the GUI == === !AddCaption(text) ===
Display event text in the upper part of the screen.
=== !ShowMission(caption, subcaption, text, icon, time) ===
Use to tell the player what he is supposed to do. As of (0.9.15), icon currently accepts: * -amBazooka, -amShotgun etc. (and other ammo types) * 0 (Gold Crown icon) * 1 (Target icon) * 2 (Exclamation mark) * 3 (Question mark) * 4 (Gold star)
=== !HideMission() ===
Hides the mission. This function is currently bugged somehow and will completely ruin your life, and your script should you happen to use it.
=== !SetZoom(zoomLevel) ===
Sets the zoom level. The value for maximum zoom is currently 1.0 and for minimum 3.0 The default zoom level is 2.0
=== !GetZoom() ===
Returns the current zoom level
== Sound functions == === !PlaySound(soundId) ===
Plays the specified sound.
=== !PlaySound(soundId, gearUid) === /
Plays the specified sound for the chosen hedgehog's team.
== File system functions == === !HedgewarsScriptLoad(scriptPath) === Loads a script (i.e. a [LuaLibraries library]) from the specified `scriptPath`. The root directory is here Hedgewars’ data directory. Example: HedgewarsScriptLoad("/Scripts/Locale.lua") -- loads locale library === !GetDataPath() ===
Returns the path to the data directory, used when adding libraries.
=== !GetUserDataPath() ===
Returns the path to the user data directory, used when adding libraries.
== Stats functions == === !SendStat(TStatInfoType, statMessage[, teamName]) (0.9.20) === This function exposes the uIO SendStat to the Lua scripts. Use it to produce custom stat pages. `TStatInfoType` is the piece of information you want to manipulate. The result of this functions varies greatly for different `TStatInfoType`s. The parameter `statMessage` is mandatory and is a string used for the statistics, its meaning depends on the `TStatInfoType`. The parameter `teamName` contains the name of a team which is relevant to the chosen stat. This parameter is not always required, this also depends on `TStatInfoType`. This tables explains the different behaviours of this function for different values of `TStatInfoType`: || `TStatInfoType` || Meaning of `statMessage` || Team parameter used? || || `siGraphTitle` || Title of the graph. If you use this, the health icon changes into a star. || No || || `siGameResult` || Title of the stats screen, used to show the result of the game, i.e. who won the game || No || || `siCustomAchievement` || A freeform text for a single “bullet point” in the “bullet point” list in the details section. For each time you call `SendStat` with this `TStatInfoType`, a new “bullet point” gets added to the list. || No || || `siPointType` || Replaces the word “kills” in the ranking list. Sadly, grammatical number is currently not respected at all here. || No || || `siPlayerKills` || The number of kills for the specified team (converted to a string), as shown in the ranking list. Unless the word “kills” has been replaced by `siPointType`, then that word is used instead. Only integers (converted to string) are possible. || Yes || || `siClanHealth` || Value of a data point (converted to a string). This sets a single data point on the graph for the specified team. Subsequent calls will draw the next point along the horizontal axis; the frontend will then simply connect the dots in the final graph. The graphs are treated independently for each other. Currently the graph only can display positive values. You also should have called `SendHealthStatsOff` if you use this to prevent the default health graphs to be drawn. || Yes || || `siMaxStepKills` || Most hedgehogs killed in a round. `statText` must be in format “` ()`”. || No || || `siMaxTeamDamage` || Hedgehog with most damage inflicted to his own team. `statText` must be in the format “` `”. || No || || `siKilledHHs` || Total number of killed hedgehogs (converted to string). || No || || `siTeamStats` || Increases the wins of local teams in case the given number is greater than 0. || No || || `siMaxStepDamage` || Best shot award (most damage in one turn). `statText` must be in format “` ()`”. || No || || `siMaxTurnSkips` || Team with most skips. `statText` must be of format “` `”. || No || Examples: -- will automatically change the health icon to a star SendStat(siGraphTitle,'Custom Graph Title') SendStat(siGameResult,'Winner is Team A!') SendStat(siCustomAchievement,'This is a custom message posted in the Details section!') -- Changes the word kill to Point, call it just before sending kills/score for each hog -- in case you want to change the word i.e. print Point or Points SendStat(siPointType,'Point') -- if above function call was not used it will print 3 kills for teamName in Ranking section. -- if it was used it will print 3 Point for teamName in Ranking section. SendStat(siPlayerKills,'3',teamName) -- call siClanHealth to send the "value" of a clan that will be used for the graph creation -- a good idea is to call it always for every hog by using the runOnGears(function) -- in normal mode "value" represents clan health SendStat(siClanHealth, "100",teamName) -- most hedgehogs killed in a round (hedgeHogName is who killed them) SendStat(siMaxStepKills, "1 hedgeHogName (teamName)") -- hog with most damage inflicted to his own team SendStat(siMaxTeamDamage, "100 hedgeHogName") -- total number of killed hedgehogs SendStat(siKilledHHs, "1") -- increases the wins of local teams in case the given number is greater than 0 SendStat(siTeamStats, "teamName:0:") -- best shot award SendStat(siMaxStepDamage, "30 hedgeHogName (teamName)") -- team with most kills of own hedgehogs SendStat(siMaxStepDamage, "2 teamName") -- team with most skips SendStat(siMaxTurnSkips, "3 teamName") Important: * As the game engine send stats to the front end at the end of the game one should send her stats when the game is going to finish and right before the call of EndGame(). (Note: Stats are sent from the engine in CheckForWin. If conditions are met(win or draw) then SendStats(uStats) is called.) * Calling just EndGame() won't produce any stats. * If one would like to produce a custom graph see also SendHealthStatsOff(). === !SendHealthStatsOff() (0.9.20) ===
Prevents the engine of sending health stats to the front end. If any health stats haven't been sent before this will cause the health graph to the stats page to be hidden. Use this function in the lua scripts to produce custom graphs by calling it inside onGameStart() and using the SendStat().
== Math Functions == === div(dividend, divisor) ===
Performs an integer division and returns the result. The result is an integer and has the value of the first parameter (integer) divided by the second parameter (integer), rounded towards zero.
=== band(value1, value2) === Returns the bitwise logical AND of `value1` and `value2`. === bor(value1, value2) === Returns the bitwise logical OR of `value1` and `value2`. === bnot(value) === Returns the bitwise logical NOT of `value`. == Debugging Functions == === !ParseCommand(string) ===
Makes the gameclient parse the specified custom command. *Note*: Please be aware that the *engine protocol can (and will) change* between releases. If you do use ParseCommand to overcome a shortcoming in our Lua API (e.g. a missing Function), please make sure to [https://code.google.com/p/hedgewars/issues/entry report the issue]. With your report we can fix the shortcoming in future releases. This will allow scripts to use the previously missing feature in a way that won't break!
=== !WriteLnToConsole(string) ===
Writes (string) to the game0.log, found in the user data directory.