• Do not use Works in Progress as a way of avoiding the releases system! Works in Progress can be used for sharing early betas and for getting suggestions for improvement. Releases of finished content are not allowed in this forum! If you would like to submit a finished addon, click here for instructions on how to do so.

Monster Iestyn's Lua documentation thread

Status
Not open for further replies.

Monster Iestyn

Fangtastic
30/11/14 - This thread is OUTDATED, check the wiki for up-to-date Lua information! (see https://wiki.srb2.org/wiki/Lua)


Okay guys, you've been waiting for this (cough) *monster* of a documentation thread for ages now, here you go! This will all eventually be up on the wiki in due time, this exists in the meantime to tide you guys over while you wait for (hopefully) better documentation on the wiki than the mess I have here. =P

Do mind many things here may or may not make sense without the source code, so grab a hold if it when (and if) you can for reference. If there's anything you don't quite understand (probably will be plenty at first), I'm sure JTE and myself should be able to help whenever we can either on the MB or on IRC in #srb2fun.

(See also http://mb.srb2.org/showthread.php?t=36736 if you haven't read it already - may or may not help clear up some things here)

Usable constants/flags:
(Note that a lot of these are actually also usable for SOCs, if I'm getting my facts right.)

Main Object/Player Flags:
*MF_ ("Mobj Flag"/Object Flags - see p_mobj.h for the list)
*MF2_ ("Mobj Flag 2")Object Flags 2 - see p_mobj.h for the list)
*MFE_ ("Mobj Flag Extra"/Object Flag Extras - see p_mobj.h for the list)
*PF_ (Player Flags - see d_player.h for the list)

SOC-related constants
*S_ (States - see info.c/info.h for the list)
*MT_ ("Map Thing"/Objects - see info.c/info.h for the list)
*SPR_ (Sprites - see info.c/info.h for the list)
*sfx_ (Sounds - see sounds.c/sounds.h for the list)
*mus_ (Music Slots - see sounds.c/sounds.h for the list)
*HUD_ (Hud item Slots - see st_stuff.c/st_stuff.h for the list)


Misc Object/Player Flags
*MTF_ (Map Thing Flags - see doomdata.h for the list)
*pw_ (Player powers - see d_player.h for the list)
*SKINCOLOR_ (Skin Colors - see doomdef.h for the list)
*SF_ (Character/skin flags - see d_player.h for the list)
*CA_ (Primary character abilities - see d_player.h for the list)
*CA2_ (Secondary character abilities - see d_player.h for the list)
*SF_ (Sound flags (prefix is shared with skin flags) - see s_sound.h for the list)

Integer Type Limit Constants:
*INT8_MIN (-128)
*INT16_MIN (-32768)
*INT32_MIN (-2147483648)
*INT8_MAX (127)
*INT16_MAX (32767)
*INT32_MAX (2147483647)

*UINT8_MAX (0xff, or 255)
*UINT16_MAX (0xffff, or 65535)
*UINT32_MAX (0xffffffff, or 4294967295) (Possibly doesn't give correct value currently, see text for Angles section)

Main/Misc Constants:
m_fixed.h
*FRACUNIT (1<<FRACBITS, or 65536) - Basic unit of measurement for lengths, speeds, object scales ...and sometimes angles?
*FRACBITS (16) - The number of bits to shift up to reach FRACUNIT scale, used to make FRACUNIT itself the value it is; sometimes is used in place of FRACUNIT in some places (i.e. x<<FRACBITS = x*FRACUNIT and x>>FRACBITS = x/FRACUNIT)
doomdef.h
*TICRATE (35) - The number of tics in a second; i.e. anything multiplied by this value is a measurement in seconds.
*RING_DIST (512*FRACUNIT) - Used as the max distance Rings can be away from Attraction Shield-holding players to follow them, or for Players to use homing attack on a badnik. Can also be used for other things for whatever reason.
*PUSHACCEL (2*FRACUNIT) - The speed Pushable Objects with MF2_SLIDEPUSH will be pushed at.
*MODID (for SRB2 Vanilla, this is 1) - EXE Mod ID; could be useful for getting Lua scripts to change stuff depending on the current EXE mod?
*CODEBASE (for SRB2 2.1, this is 210) - The SRB2 version number the EXE is based on.
*LE_ (see doomdef.h for the list) - Special linedef executor tag numbers to be used with P_LinedefExecute. Currently all of these are intended for bosses.
p_local.h
*FLOATSPEED (FRACUNIT*4)
*MAXSTEPMOVE (24*FRACUNIT)
*USERANGE (64*FRACUNIT)
*MELEERANGE (64*FRACUNIT)
*MISSILERANGE (32*64*FRACUNIT)
*ONFLOORZ (INT32_MIN)
*ONCEILINGZ (INT32_MAX)
*PAL_ - Palette type constants for use with P_FlashPal

Translucency/Full Brightness Flags:
*FF_FRAMEMASK (32767) - Highest possible value a State can have without FullBright/translucency settings (Probably isn't going to be very useful for most people)
*FF_FULLBRIGHT (32768) - Turns on full brightness for the State this is set to; can be combined with the translucency flags
*FF_TRANSMASK (983040) - Limit of Translucency value ranges (The values of the State, FullBright and Transclucency flags combined don't ever go this high anyway =V )
*FF_TRANSSHIFT (16) - used to shift the translucency settings' values to become multiples of 65536; could be useful for changing translucency values based on an object's fuse or something, otherwise just use the translucency values themselves!
*tr_trans10 to tr_trans90 - The 9 translucency flags available, differing from each other by 10% of transparency/opaqueness; tr_trans10 is the most opaque, and tr_trans90 is the most transparent (while still visible); can be combined with FF_FULLBRIGHT. However, these need to be shifted using FF_TRANSSHIFT
*TR_TRANS10 to TR_TRANS90 - unlike the lowercase versions of these, these are pre-shifted
*NUMTRANSMAPS (10) - Number of possible translucency flags + 1

Angle Constants:
(Please beware that angles 180° and above in this scale possibly may not give the right values currently - angle_t is UINT32 (unsigned 32-bit, 0 to (2^32)-1), but currently all constants available for Lua appear to be stuck with INT32 (signed 32-bit, -(2^31) to (2^31)-1). I need to test this more thoroughly)
*ANG1 - 1°
*ANG2 - 2°
*ANG10 - 10°
*ANG15 - 15°
*ANG20 - 20°
*ANG30 - 30°
*ANG60 - 60°
*ANG64 - 64.5°
*ANG105 - 105°
*ANG210 - 210°
*ANG255 - 255°
*ANG340 - 340°
*ANG350 - 350°

*ANGLE_11hh - 11.25°, or 1/32 of a revolution
*ANGLE_22h - 22.5°, or 1/16 of a revolution
*ANGLE_45 - 45°, or 1/8 of a revolution
*ANGLE_67h - 67.5°, or 3/16 of a revolution
*ANGLE_90 - 90°, or 1/4 of a revolution
*ANGLE_112h - 112.5°, or 5/16 of a revolution
*ANGLE_135 - 135°, or 3/8 of a revolution
*ANGLE_157h - 157.5°, or 7/16 of a revolution
*ANGLE_180 - 180°, or 1/2 of a revolution
*ANGLE_202h - 202.5°, or 9/16 of a revolution
*ANGLE_225 - 225°, or 5/8 of a revolution
*ANGLE_247h - 247.5°, or 11/16 of a revolution
*ANGLE_270 - 270°, or 3/4 of a revolution
*ANGLE_292h - 292.5°, or 13/16 of a revolution
*ANGLE_315 - 315°, or 7/8 of a revoution
*ANGLE_337h - 337.5°, or 15/16 of a revolution
*ANGLE_MAX - almost 360*°, but not quite~ (do not use this as an actual angle to give Objects; it it meant for other purposes)

More Misc Flags/Constants:
*GF_REDFLAG and GF_BLUEFLAG - Used to check if player has got the red or blue CTF flags respectively (for "gotflag" in player_t)
*EMERALD1 to EMERALD7 - Emerald flags, used with the global variable emeralds (SOC Object properties for each the 7 emeralds have Speed set to these values)
*TOL_ (see doomstat.h for the list) - Flags used for TypeOfLevel in the Level Header, can be used with the global variable maptol
*GRADE_ (see doomstat.h for the list) - NiGHTS Grades
*ML_ (see doomdata.h for the list) - Linedef flags
*GT_ (see doomstat.h for the list) - Gametype constants to be used with the global variable gametype
*PRECIP_ (see doomstat.h for the list) - Level Header Weather types; can be used with the global variables curWeather and globalweather
*SH_ (see d_player.h for the list) - Shield flags; for use with player.powers[pw_shield]. Note that all shields excluding fire flowers are designed to be mutually exclusive in 2.1, and so cannot be combined unlike in 2.0
*PA_ (see d_player.h for the list) - Player animation; used to show which player animation is currently being used
*RW_ (see d_player.h for the list) - Flags for ring weapons currently obtained by the player; for a player's player.ringweapons
*WEP_ (see d_player.h for the list) - Currently selected weapon; for a player's player.currentweapon
*NUM_WEAPONS (Total number of weapons - used with WEP_ constants)
*DI_ (see p_mobj.h for the list) - Current direction being faced; used for P_NewChaseDir and subsequently used by actions such as A_Chase, A_SkimChase etc. Intended only to be used by a mobj's "movedir"
*NUMDIRS (Total number of directions - used with DI_ constants)
*BT_ (see d_ticcmd.h for the list) - Button Flags; these are given when the player is pressing the respective keys for these buttons
*CV_ (see command.h for the list) - Console Variable Flags
*V_ (see v_video.h for the list) - Video Flags - used for determining how to render graphics (such as patches created using the Hud library functions), including a number of options for color, alpha, scale, orientation and miscellaneous


Dynamic Variables: (Values that may change mid-level or through switching maps)
*gamemap (integer) - Current Map's number
*maptol (integer) - Current Map's TypeOfLevel
*mariomode (boolean) (maptol & TOL_MARIO) - Is the map a Mario Mode level?
*twodlevel (boolean) (maptol & TOL_2D) - Is the map a 2D Mode level?
*circuitmap (boolean) - Is the map a Circuit stage?
*netgame (boolean) - Are we in a netgame?
*multiplayer (boolean) - Are we playing a multiplayer game?
*modeattacking (boolean) - Are we using Record Attack?
*splitscreen (boolean) - Are we using Two-Player Mode?
*gamecomplete (boolean) - Has the game been completed?
*devparm (boolean) - Is the command line parameter -debug set? (not meant for DEVMODE console command)
*modifiedgame (boolean) - Game modified?
*menuactive (boolean) - Is the menu active?
*paused (boolean) - Is the game paused?
*gametype (integer) - The gametype currently being played (NOT the same as TypeOfLevel, see the GT_ constants in doomstat.h)
*leveltime (integer) - The amount of time we have been in the level (measured in tics, not seconds)
*curWeather (integer) - Current Weather active in the map
*globalweather (integer) - The map's Level Header Weather value
*server (player_t) - Refers to the server host (unless in a dedicated server)
*admin (player_t) - Refers to the server admin (unless admin is also the server host)
*emeralds (integer) - Emeralds that have been collected (for Single Player/Coop modes)
*gravity (integer) - Current (global) gravity - normally would be FRACUNIT/2

Base Functions:
The list of pre-defined functions from SRB2's source code Lua allows you to make use of!

Please note that things like (void), (fixed_t), (mobj_t) etc written before the function names and parameters are not needed for Lua usage; they are simply there to show what type of values are needed/returned by the functions.

* any functions prefixed with (void) means the function returns nothing at all
* any functions prefixed with anything else means that the function returns a value, which can be used as such:
local spawn = P_SpawnMobj(x, y, z, type)
Here "spawn" is set to the value returned by P_SpawnMobj, which in this case is the object spawned by the function; internally this is a mobj_t value, i.e it has has the structure as a map object (or mobj)
* some functions can even return TWO values at once rather than just one, which are used as shown:
local x, y = P_ClosestPointOnLine(x, y, line)
Here Lua's version of P_ClosestPointOnLine actually returns two seperate values, an x position and y position in that order - "x" is set to the first return value, and "y" to the second

print(string):
Prints the text in string in the console, for all players. (For printing for a particular player, you need CONS_Printf; see console commands/variables post)

strings notes:
*concatination
To be able to print values of variables etc being used, you use + to seperate this from the strings
e.g: "gravity's value = "+gravity will print gravity's value = 32768
and (assuming no emeralds) "emeralds value = "+emeralds+", gravity's value = "+gravity will print emeralds value = 0, gravity's value = 32768
+ is not needed at the other side if at the end of the string to print
*use of " ' or \ within strings
To do able to use these you need to type \" \' or \\ respectively; when printed these will act as the corresponding characters
\" at the very least is important for console commands/variables used in text that require strings within, as " is already used to border the strings themselves

M_RANDOM
(UINT8) P_Random():
Returns a random value from 0 to 255
(INT32) P_SignedRandom():
Returns a random value from -128 to 127
(INT32) P_RandomKey(INT32 a):
Returns a random value from 0 to (a-1)
(INT32) P_RandomRange(INT32 a, INT32 b):
Returns a random value from a to b. Both values are required
P_MAPUTIL
(fixed_t) P_AproxDistance(fixed_t dx, fixed_t dy):
Returns an approximate distance (not exact) between points dx and dy
(fixed_t, fixed_t) P_ClosestPointOnLine(fixed_t x, fixed_t y, line_t line)
Returns both the x and y positions (as two seperate values) of the closest point to x and y on the line specified
P_ENEMY
(boolean) P_CheckMeleeRange(mobj_t actor):
Returns true if the actor's target is within the standard melee range conditions (the target must exist, is within 44 fracunits of the actor, positioned within the height of the actor, and is visible to the actor), otherwise this returns false
(boolean) P_JetbCheckMeleeRange(mobj_t actor):
Returns true if the actor's target is within the melee range conditions for the Jetty-Syn Bomber (the target must exist, is positioned within the actor's radius, at least 40 fracunits under the actor), otherwise this returns false
(boolean) P_FaceStabCheckMeleeRange(mobj_t actor):
Returns true if the actor's target is within the melee range conditions for the CastleBot Facestabber (the target must exist, is within a distance 4x the actor's and target's radii combined, positioned within the height of the actor, and is visible to the actor), otherwise this returns false
(boolean) P_SkimMeleeRange(mobj_t actor):
Returns true if the actor's target is within the melee range conditions for the Skim (the target must exist, is within 44 fracunits of the actor, at least 24 fracunits under the actor), otherwise this returns false
(boolean) P_CheckMissileRange(mobj_t actor):
Returns true if the conditions are right for the actor to fire a missile at its target (the target must exist, is visible to the actor, actor's reaction time is 0), otherwise this returns false. Note that besides the basic conditions, the distance between the actor and target also affects the chance of this returning true or false; the further away they are from each other, the less likely this is to return true
(void) P_NewChaseDir(mobj_t actor):
Changes actor.movedir to be the decided best direction of the actor to be in relation to its target (provided it has one of course). Note that these directions include only the 8 basic cardinal directions (N, S, E, W, NE etc; also see DI_ constants)
(boolean) P_LookForPlayers(mobj_t actor, fixed_t dist, boolean allaround?, boolean tracer?):
Can the object actor find a player with the conditions provided? If yes, this returns true and the actor's target is set to the first player found; otherwise this returns false (but the actor's target is unchanged).
"dist" determines the distance limit for the actor to check for players in; if dist is set to 0 however, this distance limit will be infinite."allaround?" determines whether the actor will look all around itself for players or just within 90° of the direction it is currently facing. "tracer?" determines whether to use actor.tracer instead of actor.target, useful for homing missiles such as the deton (as missiles set their target to the object who shot them, so they can't harm them). "allaround?" and "tracer" both default to false if not set
P_MOBJ
(mobj_t) P_SpawnMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype_t type):
Spawns an object at the given coordinates, with the given Object type. This returns the object spawned by the function
(void) P_RemoveMobj(mobj_t mobj):
Removes the object and its thinker from the map. It is important to realise you cannot use this same object again for anything once this has been used
(mobj_t) P_SpawnMissile(mobj_t source, mobj_t dest, mobjtype_t type):
Spawns a missile object with the default missile positioning, sending it forward to "dest" at its SPEED value. This returns the object spawned by the function
(mobj_t) P_SpawnXYZMissile(mobj_t source, mobj_t dest, mobjtype_t type, fixed_t x, fixed_t y, fixed_t z):
Spawns a missile object at specific co-ordinates, sending it forward to "dest" at its SPEED value. This returns the object spawned by the function
(mobj_t) P_SpawnPointMissile(mobj_t source, fixed_t xa, fixed_t ya, fixed_t za, mobjtype_t type, fixed_t x, fixed_t y, fixed_t z):
Same as P_SpawnXYZMissile, except the destination doesn't have to be an object's coordinates! This returns the object spawned by the function
(mobj_t) P_SpawnAlteredDirectionMissile(mobj_t source, mobjtype_t type, fixed_t x, fixed_t y, fixed_t z, INT32 shiftingAngle):
Spawns a missile object at its SPEED value, but with an angle relative to the direction its source was aiming at. (The source object *must* be a missile itself, and must have a target too so the spawned missile will share it's target!) This returns the object spawned by the function
(void) P_ColorTeamMissile(mobj_t missile, player_t source):
In Team Match or CTF, this changes the missile's color to match the player's team color (red if player is in the red team, or steel blue if in the blue team). In all other gametypes this does nothing
(mobj_t) P_SPMAngle(mobj_t source, mobjtype_t type, angle_t angle, UINT8 allowaim, UINT32 flags2):
Spawns a missile object at its SPEED value, assuming the source is a player. "angle" sets what direction to fire the missile in, "allowaim" allows the player's vertical aiming angle to determine the vertical angle the missile is fired at, and "flags2" allows additional flags to be added on to the missile's flags2 (such as MF2_RAILRING to make the missile act like the rail ring weapon). This returns the object spawned by the function
(mobj_t) P_SpawnPlayerMissile(mobj_t source, mobjtype_t type, UINT32 flags2):
Functionally identical to P_SPMAngle, except with the missile's angle always being the source player's angle, and the player's vertical aiming angle will always be used. This returns the object spawned by the function
(SINT8) P_MobjFlip(mobj_t mobj):
Returns 1 if the mobj is in normal gravity, and returns -1 if the mobj is in reverse gravity (i.e MFE_VERTICALFLIP is set in the mobj's eflags). Intended to be used as a multiplier to flip momz values in comparison checks or similar
(boolean) P_WeaponOrPanel(mobjtype_t type):
Returns true if "type" matches any of the weapon ring/panel object types, otherwise returns false
(void) P_FlashPal(player_t pl, UINT16 type, UINT16 duration):
Sets the type and duration of the player's palette
(mobj_t) P_GetClosestAxis(mobj_t source):
Returns the closest Axis object (of type MT_AXIS) to the "source" object specified
(void) P_SpawnParaloop(fixed_t x, fixed_t y, fixed_t z, fixed_t radius, INT32 number, mobjtype_t type, angle_t rotangle, statenum_t nstate, boolean spawncenter):
Spawns a NiGHTs-style "paraloop" of objects at the x, y, z coordinates supplied. radius determines the starting/finishing size, number determines how many objects are spawned, type determines the type of the objects spawned, nstate is the starting state of the object (defaults to S_NULL if not set, which means this will not be changed), rotangle sets the vertical rotation of the objects (in fact multiple paraloops are spawned with this to form the typical paraloop "ball" seen for NiGHTS Super Sonic and A_RingExplode). If "spawncenter" is true, the objects will all start at the center and move outwards, otherwise they will start at "radius" distance from the center and move inwards
(boolean) P_BossTargetPlayer(mobj_t actor, boolean closest):
Player searching for bosses; returns true if a player is targeted, otherwise returns false. If "closest" is true, the boss will target the closest player it can find, otherwise the boss will target the first player it finds
(boolean) P_SupermanLook4Players(mobj_t actor):
Similar to P_LookForPlayers, except the actor can search anywhere in the map and through walls
(void) P_SetScale(mobj_t mobj, fixed_t newscale):
Changes mobj's current scale to the value of newscale, FRACUNIT is normal scale. Unlike changing mobj.scale directly in Lua, this will not alter mobj.destscale to match it, allowing for gradual scale changes
(boolean) P_CheckDeathPitCollide(mobj_t mo):
Returns true if the mobj "mo" is touching a death pit floor or ceiling, otherwise returns false
P_USER
(fixed_t) P_GetPlayerHeight(player_t player):
Gives what the player's height should be relative to the player's scale (Normally 48*FRACUNIT)
(fixed_t) P_GetPlayerSpinHeight(player_t player):
Gives what the player's *spinning* height (2/3 of full height) should be relative to the player's scale (Normally 32*FRACUNIT)
(INT32) P_GetPlayerControlDirection(player_t player):
Gives a value depending on what is happening with the player's controls at the moment:
0 - no controls pressed
1 - pressing in direction of movement
2 - pressing in opposite direction of movement
(void) P_AddPlayerScore(player_t player, UINT32 amount):
Adds "amount" to player's score. Also corrects score if < MAXSCORE, and awards lives for every 50000 points (if not losing points). Handled somewhat differently for NiGHTS stages (both normal and special stages), modifying player.marescore instead of player.score
(boolean) P_PlayerInPain(player_t player):
Checks if player is in painstate with pw_flashing set (and not sliding), if so returns true, otherwise returns false
(void) P_DoPlayerPain(player_t player, mobj_t source, mobj_t inflictor):
Thows back the player setting the state to the player's pain state (does not spill rings/emeralds/flags nor remove health/shields). Source is the object the damage (or inflictor) came from, and inflictor (which is either the source itself or a projectile from it) the object that dealt the damage, inflictor in particular being used to determine the throw-back speed depending on the flags set. Source and inflictor objects are not required
(void) P_ResetPlayer(player_t player):
Resets the player! Halts anything the player is currently doing
(boolean) P_IsObjectOnGround(mobj_t mo):
Is the object on the ground? Returns true if yes, false if no. ("ground" can be floor or ceiling depending on whether the object is following reverse gravity or not) If the player is currently in goop water, this will always return false
(void) P_SetObjectMomZ(mobj_t mo, fixed_t value, boolean relative):
Sets the Object's momz to the value given. If "relative" is true the value is added to the Object's current momz instead. Also has built-in checks for when the object changes scale or flips gravity, and so will change the momz value given accordingly
(void) P_RestoreMusic(player_t player):
Restores the music to whatever should be depending on whether the player has any powerups or not
(mobj_t) P_SpawnGhostMobj(mobj_t mobj):
Spawns a "ghost" of the mobj which will disappear almost immediately after being spawned, useful for creating afterimages if used repeatedly. This returns the "ghost" object spawned by the function
(void) P_GivePlayerRings(player_t player, INT32 num_rings):
Adds num_rings to player's ring count. Also corrects ring count if > 9999 or < 0. Also awards extra life bonuses for multiples of 100 rings up to the value of maxXtraLife
(void) P_GivePlayerLives(player_t player, INT32 numlives):
Adds numlives to player's lives count. Also corrects lives count if > 99 or < 1
(void) P_ResetScore(player_t player):
Resets the player's scoreadd value to 0, ending any score chains in progress
(void) P_BlackOw(player_t player):
This is used by the armageddon shield to blow up enemies, flash the palettes of all players within the explosion radius (1536 fracunits) and destroy the shield currently being held by the player. Also plays the armageddon explosion sound
(void) P_ElementalFireTrail(player_t player):
Spawns two Elemental Shield-style flames for both sides and behind the specified player, needs to be used repeatedly to spawn an Elemental Shield fire trail
(void) P_DoPlayerExit(player_t player):
This is used to have the player "complete" the level and become immobile; this will not immediately end the level itself
(void) P_InstaThrust(mobj_t mo, angle_t angle, fixed_t move):
Object will instantly be pushed at "move" in the direction of "angle". (The y-axis thrust won't be added if the object has MF2_TWOD set)
(fixed_t) P_ReturnThrustX(mobj_t mo, angle_t angle, fixed_t move):
Gives an x-axis thrust value for "move" depending on what "angle" is set. ("mo" is unused)
(fixed_t) P_ReturnThrustY(mobj_t mo, angle_t angle, fixed_t move):
Gives a y-axis thrust value for "move" depending on what "angle" is set. ("mo" is unused)
(boolean) P_LookForEnemies(player_t player):
Returns true if there is a suitable object for the player to use homing attack on (setting it as the target), otherwise returns false. Note the possible objects to target with this also includes springs and monitors
(void) P_NukeEnemies(mobj_t inflictor, mobj_t source, fixed_t radius):
Damages all enemies and bosses (as well as players in shooting gametypes) within a radius around the "inflictor" mobj (the object causing the damage). The "source" mobj is where the inflictor came from, if not the inflictor itself
(void) P_HomingAttack(mobj_t source, mobj_t enemy):
The "source" mobj faces the "enemy" mobj and moves towards it; needs to be repeatedly used to work properly. The source's movement speed depends on what it is - players will move at 2/3 of their actionspd value, the deton will move at 17/20 of the enemy player's normalspeed value, otherwise all other objects will use their mobjinfo speed value (threshold of 32000 for the source cuts this in half)
(boolean) P_SuperReady(player_t player):
Returns true if the conditions are right for the player to turn super by double-jumping, otherwise this returns false
(void) P_DoJump(player_t player, booleansoundandstate):
Makes the player jump! If soundandstate is set to true (the default value), the player's state will be changed to appropriate jump states and play the jump sound
P_MAP
(boolean, mobj_t) P_CheckPosition(mobj_t thing, fixed_t x, fixed_t y)
Checks if the position is valid for the object "thing" (this does not actually teleport it to the x and y coordinates, only tests what would happen if the object is at the position); returns false if either a) the object has been blocked by a wall or an object, or b) the object has been removed from the map during checking; otherwise it will return true to signal the position isn't blocked. Do note that objects with MF_NOCLIP won't clip with objects or walls at all, while objects with MF_NOCLIPTHING will not clip with things but can still be blocked by walls. Additionally returns the "tmthing" mobj set during the run of the function
(boolean, mobj_t) P_TryMove (mobj_t thing, fixed_t x, fixed_t y, boolean allowdropoff)
Tries to move the object "thing" to the x/y coordinates supplied (all done in the same tic), checking each position to make sure the object is not blocked on the way there; if it is blocked by a wall or another object, or the height of the sector is too small to fit in, this will return false and leave the object where it was to begin with (i.e the move failed); otherwise this will return true with the object at the coordinates supplied. Additionally returns the "tmthing" mobj set during the run of the function
"allowdropoff" determines whether to stop the object from falling off a platform too low to step-down when moving, or let it continue regardless of this - if allowdropoff is false and the object would be falling off a platform if it continued, this will return false. Additionally returns the "tmthing" mobj set during the run of the function
Note that pushable objects will also move along anything on top with them if the pushable itself isn't blocked by something etc. Objects with MF_NOCLIP however will be able to move straight to the position without being blocked by anything, and allowdropoff will not affect them either way
(boolean, mobj_t) //P_ENEMY P_Move(mobj_t actor, fixed_t speed)
Moves the "actor" mobj in it's current direction (using actor.movedir rather than the angle), moving speed fracunits forward (unusually this does not need to be multiplied by FRACUNIT). Returns true when the actor has moved, returns false if the actor cannot move, doesn't have a direction to move in or is dead. Additionally returns the "tmthing" mobj set during the run of the function
(boolean, mobj_t) P_TeleportMove(mobj_t thing, fixed_t x, fixed_t y, fixed_t z)
Teleports the object straight to the coordinates supplied, does not account for whether the object will be stuck in this position though. (Always returns true) Additionally returns the "tmthing" mobj set during the run of the function
(void) P_SlideMove(mobj_t mo)
Slides the mobj mo along a wall using its current xy-momentum; this is assuming the mobj has already been blocked by a wall, so this searches for the wall that blocked it before sliding
(void) P_BounceMove(mobj_t mo)
Bounces the mobj mo off a wall using its current xy-momentum; this is assuming the mobj has already been blocked by a wall, so this searches for the wall that blocked it before bouncing
(boolean) //P_SIGHT P_CheckSight(mobj_t t1, mobj_t t2)
Checks if mobj t1 can "see" mobj t2, if it can, this returns true; otherwise it returns false. This function is able to check if FOFs are blocking, but this is limited to when both mobjs are in the same sector (?)
(void) P_CheckHoopPosition(mobj_t hoopthing, fixed_t x, fixed_t y, fixed_t z, fixed_t radius)
Optimized version of P_CheckPosition specifically designed for MT_HOOPCOLLIDE. ("radius" is unused)
(void) P_RadiusAttack(mobj_t spot, mobj_t source, fixed_t damagedist)
Damages objects around "spot" object, except for itself and its "source" object. "damage" is the distance limit around the spot to damage other objects in
(fixed_t) P_FloorzAtPos(fixed_t x, fixed_t y, fixed_t z, fixed_t height)
Returns what would be the floorz (the absolute z height of the floor) at the x, y, z coordinates supplied. "height" should be the height of the object you want to check this for (needed for checking solid/quicksand FOFs). Keep in mind the coordinates and perhaps even the height don't actually have to be for an existing object neccessarily!
P_INTER
(void) P_RemoveShield(player_t player):
Does what it says on the tin - removes any shield the player may be carrying, and nothing else (does not throw back the player nor play a sound)
(boolean) P_DamageMobj(mobj_t target, mobj_t inflictor, mobj_t source, INT32 damage):
Damages "target" object; "inflictor" is what dealt the damage, "source" is where the inflictor came from (if the inflictor was a missile spawned by another object/player), "damage" determines the amount of damage to deal (10000 is instant-death for players, 42000 affects spectators, and if not set this defaults to 1). "target" object is required, "inflictor" and "source" are not (sector damage effects usually have nil inflictor and source). If the object wasn't damaged however, this returns false; otherwise this should normally return true
(void) P_KillMobj(mobj_t target, mobj_t inflictor, mobj_t source):
Kills "target" object; "inflictor" is what killed the object, "source" is where the inflictor came from (if the inflictor was a missile spawned by another object/player). "target" object is required, "inflictor and "source" are not
(void) P_PlayerRingBurst(player_t player, INT32 num_rings):
Spills a specified number of regular rings, also spills all weapon panels, ammo and emeralds the player may be carrying at the time; does not throw back the player. Exclusive to Lua, if num_rings is set to -1 this will be automatically adjusted to the player's current ring count (player.health-1)
(void) P_PlayerWeaponPanelBurst(player_t player):
Spills all weapon panels the player is carrying; does not throw back the player
(void) P_PlayerWeaponAmmoBurst(player_t player):
The player spills all weapon panels the player is carrying; does not throw back the player
Spills all weapon ammo the player is carrying; does not throw back the player
(void) P_PlayerEmeraldBurst(player_t player, boolean toss):
Spills all emeralds the player is carrying; does not throw back the player If "toss" is true all the emeralds are thrown in the player's forward direction and a toss delay of 2 seconds is set (for players tossing emeralds), otherwise the emeralds are spilled all around the player (for players dropping emeralds after being hurt)
(void) P_PlayerFlagBurst(player_t player, boolean toss):
Spills any CTF flags the player is carrying; does not throw back the player. If "toss" is true the flag is thrown in the player's forward direction and a toss delay of 2 seconds is set (for players tossing a flag), otherwise the direction is random (for players dropping a flag after being hurt)
(void) P_PlayRinglossSound(mobj_t source):
Plays one of the 4 player ring spill sounds randomly, which can vary depending on the skin, or plays the mario ring loss sound if in Mario mode. Source is the object the sound came from
(void) P_PlayDeathSound(mobj_t source):
Plays one of the 4 player death sounds randomly, which can vary depending on the skin. Source is the object the sound came from
(void) P_PlayVictorySound(mobj_t source):
Plays one of the 4 player victory taunt sounds randomly, which can vary depending on the skin. Source is the object the sound came from
(void) //P_USER P_PlayLivesJingle(player_t player):
Plays the Extra life jingle; by default this is the Extra life music, but in mario mode maps and in the case of use1upsound being turned on this is instead a sound. If the music is used, the player's pw_extralife timer is set to extralifetics+1
(boolean) P_CanPickupItem(player_t player, boolean weapon):
Returns true if the player can pick up the item, returns false if the player is a bot or is flashing after being hurt
(void) P_DoNightsScore(player_t player):
Awards score to the player NiGHTS-style; spawns a floating score item which changes appearance depending on current link count and if in bonus time
P_SPEC
(void) //P_USER P_Thrust(mobj_t mo, angle_t angle, fixed_t move):
Object will be pushed at "move" in the direction of "angle". (The y-axis thrust won't be added if the object has MF2_TWOD set)
(boolean) //P_MOBJ P_SetMobjStateNF(mobj_t mobj, statenum_t state):
Changes the Object's state to the state given, but doesn't run the state's Action pointer
(void) //P_USER P_DoSuperTransformation(player_t player, boolean giverings):
Transforms the player into super form, changing to the super music, and in non-SP/Coop gametypes displays a message to all players that the player has turned super. If giverings is true, the player's ring count will be set to 50 rings (the ring count needed to turn super in the first place)
(void) //P_MOBJ P_ExplodeMissile(mobj_t mo):
Death sequence for a missile object. Halts the object's momentum, alters the flags, plays DeathSound and set's its state to DeathState. (Doesn't do anything if object has MF_NOCLIPTHING set, as it is used as a dummy flag to indicate when a missile is already "dead")
(sector_t) P_PlayerTouchingSectorSpecial(player_t player, INT32 section, INT32 number):
Checks if the player is in a sector with a specified sector special (using the section number and special number within the section provided). Also checks FOFs and nearby sectors for the special. If one isn't found anywhere, this returns nil
(INT32) P_FindSpecialLineFromTag(INT16 special, INT16 tag, INT32 start):
Finds the first linedef number after "start" which has the linedef special and tag being searched for. "start" can be -1 to start from the first linedef onwards, or set to another linedef's number to carry on from perhaps the last linedef number found ("start" defaults to -1 if not set)
(void) P_SwitchWeather(INT32 weathernum):
Switches weather in-game with "weathernum" (use PRECIP_)
(void) P_LinedefExecute(INT32 tag, mobj_t actor, sector_t caller):
Executes all linedefs with a specific tag, setting actor and caller as the calling object and sector respectively if either are set (both can be nil if needed)
(void) P_SpawnLightningFlash(sector_t sector):
Starts a lightning flash effect in the sector supplied. Can also be used with an FOF's control sector, which will make the FOF itself flash in-level
(void) P_FadeLight (INT16 tag, INT32 destvalue, INT32 speed):
Fades all tagged sectors' lighting to a new value set by "destvalue". "speed" determines how quickly the sector's light fades to the new value
(sector_t) P_ThingOnSpecial3DFloor(mobj_t mo):
If the object "mo" is on top of or inside an FOF with a sector special, this function returns the FOF's control sector; otherwise returns nil
(void) //P_SETUP P_SetupLevelSky(INT32 skynum, boolean global):
Sets the sky seen in-game to the value of "skynum"; "global" makes the sky apply to all players when true
(void) //(LUA-EXCLUSIVE) P_SetSkyboxMobj(mobj_t mo):
Alternative versions:
* P_SetSkyboxMobj(mobj_t mo, boolean centrepoint?)
* P_SetSkyboxMobj(mobj_t mo, player_t user)
* P_SetSkyboxMobj(mobj_t mo, boolean centrepoint?, player_t user)
Sets which object correponds to either the skybox's viewpoint or centrepoint (defaults to viewpoint). "user" is the player to apply the new skybox view to, otherwise it applies to all players. If mo is nil, the skybox is removed
(void) //(LUA-EXCLUSIVE) P_StartQuake(fixed_t intensity, UINT16 time, table {x, y, z} epicenter, fixed_t radius):
Starts an earthquake camera effect similar to Linedef Type 444. Intensity sets how strongly the camera shakes, time sets how long the earthquake lasts. epicenter and radius are currently not used by SRB2, but they exist here anyway for when they eventually are
R_DEFS
(angle_t) //R_MAIN R_PointToAngle(fixed_t x, fixed_t y)
Returns the angle made with the line from the viewing x and y coords to the point at (x, y); this is far less often used compared to R_PointToAngle2
(angle_t) //R_MAIN R_PointToAngle2(fixed_t pviewx, fixed_t pviewy, fixed_t x, fixed_t y)
Returns the angle made with the line from the point of view coords (pviewx, pviewy) to the point at (x, y); this is far more useful than R_PointToAngle for most purposes
(fixed_t) //R_MAIN R_PointToDist(fixed_t x, fixed_t y)
Returns the distance from the viewing x and y coords to the point at (x, y); this is far less often used compared to R_PointToDist2
(fixed_t) //R_MAIN R_PointToDist2(fixed_t px2, fixed_t py2, fixed_t px1, fixed_t py1)
Returns the distance from the point of view coords (px2, py2) to the point at (px1, py1); this is far more useful than R_PointToDist for most purposes
(subsector_t) //R_MAIN R_PointInSubsector(fixed_t x, fixed_t y)
Returns the subsector that the point at (x, y) is inside, assuming that the point is in a subsector to begin with
R_THINGS
(UINT8) R_Char2Frame(string char)
Converts a text character to the respective frame number (e.g char of "A" returns 0, the first frame number)
(string, UINT8) R_Frame2Char(UINT8 frame)
Converts a frame number to the respective text character, returned as both a string and a number (e.g frame of 0 returns "A" and 65, the text character used for the frame and its ASCII value respectively)
S_SOUND
(void) S_StartSound(mobj_t origin, sfxenum_t sfx_id)
Starts a sound of a specific id at full volume. Origin is the source of the sound, if not set to nil. Keep in mind certain sounds are replaced in mariomode/NiGHTS Xmas mode
(void) S_StartSoundAtVolume(mobj_t origin, sfxenum_t sfx_id, INT32 volume)
Starts a sound of a specific id, but at a specific volume (max is 255) unlike S_StartSound. Origin works the same as in S_StartSound
(void) S_StopSound(mobj_t origin)
Stops any sound the origin is currently playing
(void) S_ChangeMusic(UINT32 music_num, boolean looping)
Switches the music currently playing with the musicslot number set by music_num. If looping is true, the music will loop continuously, if false it will not (defaults to true if not set)
(boolean) S_SpeedMusic(fixed_t speed)
Changes the speed of the music being played to the value of "speed", 1*FRACUNIT being the normal speed. (Note of interest: The "speed" value is actually a floating number in the source, but as floating numbers can't be used in Lua, it takes a fixed_t value here which is converted to a floating number for us)
(void) S_StopMusic()
Stops the music currently playing
(boolean) S_OriginPlaying(mobj_t origin)
Returns true if the "origin" object selected is playing a sound in any sound channel, otherwise this returns false
(boolean) S_IdPlaying(sfxenum_t id)
Returns true if the sound id selected is playing in any sound channel, otherwise this returns false
(boolean) S_SoundPlaying(mobj_t origin, sfxenum_t id)
Turns true if the "origin" object is playing a sound with the sound number "id", otherwise this returns false
G_GAME
(string) G_BuildMapName(INT32 map):
Returns the map name as a string in the format MAPXX using the map number specified. If the number is 100 or more, A0-ZZ will be used.
(void) G_DoReborn(INT32 playernum):
Respawns the player specified
(void) G_ExitLevel():
Exits the level! The game is told that the level has finished, sets up the appropriate intermission screen for the gametype, and will get ready to switch to the next map (if one doesn't exist this will be set to MAP01)
(boolean) G_IsSpecialStage(INT32 mapnum):
Checks whether the map given is a special stage (must be in Coop gametype, isn't in Record Attack mode, and mapnum is between sstage_start and sstage_end); returns true if yes, false if no
(boolean) G_GametypeUsesLives():
Checks whether the current gametype uses lives (i.e either Coop or Competition, and not in Record Attack mode or a NiGHTS mode level); returns true if yes, false if no
(boolean) G_GametypeHasTeams():
Checks whether the current gametype has teams (i.e either Team Match or CTF); returns true if yes, false if no
(boolean) G_GametypeHasSpectators():
Checks whether the current gametype has spectators (i.e anything not Coop/Competition/Race); returns true if yes, false if no
(boolean) G_RingSlingerGametype():
Checks whether the current gametype is a ringslinger gametype (i.e anything not Coop/Competition/Race, EXCEPT if ringslinger cheat is turned on); returns true if yes, false if no
(boolean) G_PlatformGametype():
Checks whether the current gametype is a platforming gametype (i.e any of Coop/Compeition/Race); returns true if yes, false if no
(boolean) G_TagGametype():
Checks whether the current gametype is a Tag gametype (i.e either Tag or Hide-and-Seek); returns true if yes, false if no
(UINT32) G_TicsToHours(UINT32 tics):
Converts a time in tics to hours (126000 tics = 3600*TICRATE = 1 hour)
(UINT32) G_TicsToMinutes(UINT32 tics, boolean full):
Converts a time in tics to minutes (2100 tics = 60*TICRATE = 1 minute). If "full" is true, the minutes will be able to reach 60 and over without looping, for cases where hours aren't needed (e.g 3600*TICRATE (1 hour in tics) returns 0 when "full" is off, and 60 when "full" is on)
(UINT32) G_TicsToSeconds(UINT32 tics):
Converts a time in tics to seconds (35 tics = TICRATE = 1 second). Return value will loop to less than a minute if tics > 60*TICRATE
(UINT32) G_TicsToCentiseconds(UINT32 tics):
Converts a time in tics to centiseconds (1/100 of a second). Return value will loop to less than a second if tics > TICRATE
(UINT32) G_TicsToMilliseconds(UINT32 tics):
Converts a time in tics to milliseconds (1/1000 of a second). Return value will loop to less than a second if tics > TICRATE

Actions:
Syntax:
A_actionname(mobj_t actor, INT32 var1, INT32 var2)

All of the Actions you may recognise from SOC (plus new ones added to 2.1 of course) can be used in Lua - this is not limited to states, they can be called within Actions themselves, and even outside of states altogether! There is more Lua can do though; Lua can both create new Actions, and can also overwrite existing ones. Custom Actions do not even neccessarily have to have names starting with "A_".

super(mobj_t actor, INT32 var1, INT32 var2): A special function to call the original Action, for Actions overwriting a hardcoded one already existing.

Iterates:
Syntax:
for [name] in [iterate].iterate[("[option]") if needed]

*name can be called anything you want, as long as you remember each item in the iterate will use this same name each time the block is run
*iterate is the iterate to search though, this can only take one of the names listed below
*option is only used for thinkers.iterate currently, this acts as a sub-iterate to search though in this case

E.g "for player in players.iterate [block] end" runs everything in the block of code for all the players in the game once each, setting "player" as the player each time.

"for mobj in thinkers.iterate("mobjs") [block] end" will similarly run everything in the block of code, but for all mobj thinkers instead once each, setting "mobj" as the object (or mobj) with the thinker each time.

Iterates list:
*players.iterate
Runs everything in the block for all existing players in the map, name is a player_t structure
*thinkers.iterate("[option]")
Runs everything in the block for all (or a select type of) thinkers in the map, for option "mobj" name is a mobj_t structure
Options:
*"all" -- (all thinkers in the map; objects that run P_MobjThinker are treated as mobj_t structures, but anything else can't be used as anything)
*"mobj" -- (only thinkers running the function P_MobjThinker; i.e normal objects that are not precipitation)
*skins.iterate
Runs everything in the block for all existing skins loaded, name is a skin_t structure
*mapthings.iterate
Runs everything in the block for all thing spawn points in the map, name is a mapthing_t structure
*sectors.iterate
Runs everything in the block for all sectors in the map, name is a sector_t structure
*subsectors.iterate
Runs everything in the block for all subsectors in the map, name is a subsector_t structure
*lines.iterate
Runs everything in the block for all linedefs in the map, name is a line_t structure
*sides.iterate
Runs everything in the block for all sidedefs in the map, name is a side_t structure
*vertexes.iterate
Runs everything in the block for all vertices in the map, name is a vertex_t structure

Hooks:

Syntax:
addhook("[hook]", [function], [extra parameter (not all hooks have these)])

e.g:
*addhook("MobjFuse", P_RemoveMobj, MT_CRAWLA)
*addhook("MobjFuse", function(mobj) print("Object is being removed!") P_RemoveMobj(mobj) end, MT_CRAWLA)
The above two should do basically the same thing: in the 1st example the function is written without the brackets and parameters, when written like this it should take exactly the right number of variables needed for the hook otherwise it doesn't work; for the second "function(mobj) ... end" acts as the hook's function instead, calling everything inside the block being created here.
Keep in mind in both examples the function will only be called for all objects of type MT_CRAWLA, as this is the type this hook is set to be linked to.

*addhook("ThinkFrame", do print("Think Think Think") end)
Here in this example, for "ThinkFrame" the function (here it is the "do ... end" block) doesn't need any parameters nor is hooked to a specific object etc, it just runs once every tic while the map is running.

For any of the hooks with boolean functions attached, these will by default return false unless directed to return true. Returning true generally stops further effects from occuring in the functions they alter (even for vanilla SRB2 objects), returning false allows them to continue as normal.

For MobjSpawn, MobjFuse, MobjThinker, BossThinker, BossDeath and MobjRemoved, the return value of the function determines the effect; no return value (or return false/nil) allows use of default behavior as well as the function, and return true stops the default behavior from running.

For all hooks listed with a mobj type parameter, this is actually optional and will run for all types instead if not set.

Hooks list:
*"NetVars", [function(network)]:
For syncronising local variables between client and server on a netgame, adding their values to $$$.sav
*"MapChange", [function(gamemap)]:
For setting up effects that activate when a map is changed
*"MapLoad", [function(gamemap)]:
For setting up effects that activate when a map loads
*"PlayerJoin", [function(playernum)]:
Sets up effects for when a player has just joined a netgame
*"ThinkFrame", [function]:
For setting up extra effects for one or multiple objects and such mid-level that aren't neccessarily thinkers, this hook should be used. Note that this is run after all other thinkers are done
*"MobjSpawn", [function(mobj_t mobj)], [mobjtype_t object type]:
Changes Spawning setup for a selected object (see P_SpawnMobj)
*"MobjCollide", [function(mobj_t thing, mobj_t tmthing)], [mobjtype_t object type]:
Should "thing" (non-moving thing) collide with "tmthing" (moving thing) with these conditions? (provided tmthing doesn't have MF_NOCLIP/MF_NOCLIPTHING set) The return value of the function determines the effect; no return value (or return nil) uses default behavior, return true is force yes, and return false is force no (alters PIT_CheckThing, which is in turn part of P_CheckPosition)
*"MobjMoveCollide", [function(mobj_t tmthing, mobj_t thing)], [mobjtype_t object type]:
Should "tmthing" (moving thing) collide with "thing" (non-moving thing) with these conditions? (provided tmthing doesn't have MF_NOCLIP/MF_NOCLIPTHING set) The return value of the function determines the effect; no return value (or return nil) uses default behavior, return true is force yes, and return false is force no (alters PIT_CheckThing, which is in turn part of P_CheckPosition)
*"TouchSpecial", [boolean function(mobj_t special,mobj_t toucher)], [mobjtype_t object type]:
Changes the effects that occur when a Player touches the selected object (provided the object has MF_SPECIAL set) (see P_TouchSpecialThing)
*"MobjFuse", [function(mobj_t mobj)], [mobjtype_t object type]:
Changes the effect that occurs when the chosen object's fuse reaches 0 (The default effect being to remove the object)
*"MobjThinker", [function(mobj_t mobj)], [mobjtype_t object type]:
Changes the thinker for a regular object (see P_MobjThinker)
*"BossThinker", [function(mobj_t mobj)], [mobjtype_t object type]:
Changes the thinker for a boss object, including vanilla SRB2 bosses (note: MobjThinker is used before this hook in P_MobjThinker; furthermore if MobjThinker overwrites default effects BossThinker's effects will not be used)
*"ShouldDamage", [function(mobj_t target, mobj_t inflictor, mobj_t source, INT32 damage)],[mobjtype_t object type]:
Should the specified target object take damage with these conditions? The return value of the function determines the effect; no return value (or return nil) uses default behavior, return true is force yes (overrides all cases that would force no), and return false is force no (see P_DamageMobj)
*"MobjDamage", [boolean function(mobj_t target, mobj_t inflictor, mobj_t source, INT32 damage)],[mobjtype_t object type]:
Changes the effect for when the specified target object recieves damage (see P_DamageMobj)
*"MobjDeath", [boolean function(mobj_t target, mobj_t inflictor, mobj_t source)], [mobjtype_t object type]:
Changes the effect that occurs when the specified target object "dies" (see P_KillMobj)
*"BossDeath", [function(mobj_t mobj)], [mobjtype_t object type]:
Changes the extra effects for when the specified boss object uses A_BossDeath
*"MobjRemoved", [function(mobj_t mobj)], [mobjtype_t object type]:
Adds extra effects for when an object is removed (see P_RemoveMobj)
*"BotTiccmd", [boolean [boolean function(player_t bot, ticcmd_t cmd)]:
Changes cmd attributes for a bot player
*"BotAI", [ (boolean 8 values) function(mobj_t player, mobj_t bot)], ["bot skin name"]:
Changes the Bot AI for a specific player skin. The function needs to return any or all of these (boolean) variables: forward, backwards, left, right, strafeleft, straferight, jump, or spin
*"LinedefExecute", [boolean function(line_t line, mobj_t mo)], ["functionname"]:
Executes a function for any linedef (with type 443) with "functionname" written across its front textures, creating a custom linedef executor effect
 
Last edited:
Math Functions:
General Math Functions:
*abs(a):
Gives the absolute value of a (|a|, which is a without regard to its sign, i.e. it is forced to be positive)
*min(a, b):
Gives the smaller of the two values
*max(a, b):
Gives the larger of the two values
Angle-related Functions:
*(fixed_t) sin(angle_t angle):
Gives the sine value of the given angle, shifted up to fracunit scale (e.g, sin(ANGLE_90) = 1*FRACUNIT, sin(ANGLE_180) = 0); commonly used for setting an object's y momentum
*(fixed_t) cos(angle_t angle):
Gives the cosine value of the given angle, shifted up to fracunit scale (e.g, cos(ANGLE_90) = 0, cos(ANGLE_180) = 1*FRACUNIT); commonly used for setting an object's x momentum
*(fixed_t) tan(angle_t angle):
Gives the tangent value of the given angle, shifted up to fracunit scale (e.g, tan(ANGLE_45) = 1*FRACUNIT, tan(ANGLE_180) = 0); no general purpose unlike sin and cos
*(angle_t) FixedAngle(fixed_t angle):
Converts a fixed value to an angle value; e.g 45*FRACUNIT to ANGLE_45
*(fixed_t) AngleFixed(angle_t angle):
Converts an angle value to a fixed value; e.g ANGLE_45 to 45*FRACUNIT
*(angle_t) InvAngle(angle_t angle):
Inverts the angle chosen; e.g InvAngle(ANGLE_45) = ANGLE_315
Fixed Math Functions:
Please note that by "fixed math" this means everything has to be *FRACUNIT; 1*FRACUNIT (or simply FRACUNIT) is treated as 1, FRACUNIT/2 is treated as 0.5, and so on. All these functions should take values expressed in fixed form, and will nearly always return values expressed in fixed form respectively
*(fixed_t) FixedMul(fixed_t a,fixed_t b):
(a*b)/FRACUNIT - used to multiply together a and b, assuming both were multiplied by FRACUNIT
*(fixed_t) FixedInt(fixed_t a):
a/FRACUNIT - divides a by FRACUNIT, converting a from fixed_t to an integer (i.e. a whole number)
*(fixed_t) FixedDiv(fixed_t a,fixed_t b):
(a/b)*FRACUNIT - used to divide a by b, assuming both were multiplied by FRACUNIT
*(fixed_t) FixedRem(fixed_t a,fixed_t b):
Gives the remainder of a/b
*(fixed_t) FixedSqrt(fixed_t a):
Gives the square root of a
*(fixed_t) FixedHypot(fixed_t a,fixed_t b):
Gives the length of the hypotenuse of a triangle with sides of length a and b (i.e the square root of a²+b²)
*(fixed_t) FixedFloor(fixed_t a):
Gives the largest whole (fixed) number not larger than a
*(fixed_t) FixedTrunc(fixed_t a):
Rounds a (towards 0 - down if positive, up if negative) to the nearest whole number (basically cutting off the fraction in a)
*(fixed_t) FixedCeil(fixed_t a):
Gives the smallest whole (fixed) number not less than a
*(fixed_t) FixedRound(fixed_t a):
Rounds a (away from 0 - up if positive, down if negative) to the nearest whole number
Misc. Functions:
*GetSecSpecial(i, j):
i = sector->special, j = sector special section number (1 to 4); gives the special number of the specified sector's special in specified section
*All7Emeralds(v):
Returns true if v has all emerald flags (EMERALD1 to EMERALD7) set, otherwise false (use with either global variable "emeralds" for SP/coop, or player.powers[pw_emeralds] for Match/CTF)
*(color, frame) ColorOpposite(color):
Returns both the opposite color for color, and the associated sprite frame number for the opposite color (latter is used for the exit sign)
 
Last edited:
Console Commands/Variables
Functions
*(void) COM_AddCommand("name", func, flags):
Adds/registers a new console command to the game - "name" is the name of the command to be used in the console, and "func" is the Lua function, with arguments (player, arg1, arg2, ...), that the console command will call when used. "flags" determines who can use it:
- 0 = default (anyone can use it)
- 1 = server/admin-only
- 2 = player 2 (splitscreen) only
- 3 = server/admin only + player 2 (splitscreen) only
(alternatively, "flags" can accept "true" or "false", determining whether only server/admin players can use it or not)
*(void) COM_BufAddText(player_t *player, "ptext"):
Adds text to the console for a specific player - "ptext" is the text to be added
*(void) COM_BufInsertText(player_t *player, "ptext"):
Similar to COM_BuffAddText, except it also executes the text immediately (provided it is an actual console command/variable that is usable), automatically starting a new line in the console
*(consvar_t) CV_RegisterVar({"name", "defaultvalue", flags, PossibleValue, func}):
Registers a new console variable (or cvar), which you can then use later via the console. The function converts the contents of the table within to a consvar_t:-
-name: name given to the cvar for use in-game
-defaultvalue: default value set in-game for the cvar
-flags: sets which of the cvflags_t flags (see command.h for the list) are applied to the cvar
-PossibleValue: sets the range of possible values that are usable (can use either the ranges listed below or a custom range in the form of {Low=0, Mid=1, High=2} or {MIN=0, MAX=999} etc)
-func: the Lua function to call when the variable is changed in the console (optional parameter, this can only be set if the variable has the flag CV_CALL)
*(void) CONS_Printf(player_t *player, "text"):
Prints text in the console for a specific player. (Use the base function "print" instead for text that appears for all players)

Default PossibleValue Options
*CV_OnOff: "Off" = 0, "On" = 1
*CV_YesNo: "No" = 0, "Yes" = 1
*CV_Unsigned: "MIN" = 0, "MAX" = 999999999
*CV_Natural: "MIN" = 1, "MAX" = 999999999
 
Last edited:
Code:
do -- Remove spawn invulnerability from spectators
    addHook("MobjThinker", function(mobj)
        if not mobj.player return end
        if mobj.player.spectator
            mobj.player.powers[pw_flashing] = 0 end
    end, MT_PLAYER)
end

do -- Make red rings fling very fast, and with gravity.
    mobjinfo[MT_REDRING] = {
        spawnstate = S_RING1,
        seesound = sfx_thok,
        deathstate = S_SPRK1,
        deathsound = sfx_itemup,
        speed = 120*FRACUNIT,
        radius = 16*FRACUNIT,
        height = 24*FRACUNIT,
        flags = MF_NOBLOCKMAP|MF_MISSILE
    }

    addHook("MobjThinker", function(mobj)
        if not (mobj.flags & MF_MISSILE) -- sparkles, not a ring
            return
        end
        if not mobj.arc
            mobj.momz = mobj.momz + 10*FRACUNIT
            mobj.arc = true
        end
        mobj.momz = mobj.momz - 6*FRACUNIT/4
    end, MT_REDRING)
end

do -- Hide all these standard match weapons.
    local hideme = {
        spawnstate = S_INVISIBLE,
        flags = MF_NOBLOCKMAP|MF_NOSECTOR
    }
    local list = {
        MT_BOUNCERING,
        MT_RAILRING,
        MT_AUTOMATICRING,
        MT_EXPLOSIONRING,
        MT_SCATTERRING,
        MT_GRENADERING,
        MT_BOUNCEPICKUP,
        MT_RAILPICKUP,
        MT_AUTOPICKUP,
        MT_EXPLODEPICKUP,
        MT_SCATTERPICKUP,
        MT_GRENADEPICKUP
    }
    local function normalRing(mobj)
        P_SpawnMobj(mobj.x, mobj.y, mobj.z, MT_RING)
    end
    for _,i in ipairs(list) -- for every mobjtype in the list
        for k,v in pairs(hideme)
            mobjinfo[i][k] = v -- add the properties in hideme to mobjinfo
        end
        addHook("MobjSpawn", normalRing, i) -- make it spawn a normal ring instead
    end
end
Pasting a conversation about the stuff up there to keep track of it.

Stuff about "do" syntax:
16:01] <Prime_2> do -- Remove spawn invulnerability from spectators
[16:01] <Prime_2> ...new syntax?
[16:01] <JTE> naw, "do ... end" blocks are just a way of declaring scopes. it's like putting { and } in C without having a related "if()" statement.
[16:01] <JTE> I used it to seperate this script into multiple sub-scripts, in a sense.
[16:02] <JTE> and labelled them with -- comments on the same line, instead of // because I'm silly.
[16:02] <Prime_2> yet with nothing to apparently differentiate them in a way that would let you do something different with them than just not having the do...?
[16:02] <Prime_2> huh.
[16:02] <JTE> I uh, forgot. that I added // comments to lua.
[16:03] <JTE> nyan? All the local variables inside the do .. end block are removed at the bottom of end.
[16:03] <Prime_2> oh!
[16:03] <Prime_2> Okay yeah, that makes more sense
[16:04] <JTE> all the global variables like mobjinfo changes and addHook calls and such are kept of course.
[16:05] <Prime_2> ...
[16:06] <Prime_2> you added 10 FU/T to the starting velocity of redrings?
[16:06] <JTE> Problem? :3
[16:06] <JTE> yesh. so that they have a firing arc.
[16:06] <Prime_2> well, that'll be weird to work with, but okay!
[16:06] <JTE> they go up and then they fall down. their MF_NOGRAVITY has been removed.
Stuff about pairs(), ipairs() and mobjinfo[][] syntax:
[16:32] <Prime_2> for _,i in ipairs(list)
[16:32] <Prime_2> ...underscore comma i?
[16:32] <JTE> Mystic, Prime_2 is a jerk who starts every other netgame by having all emeralds and an armageddon shield before you even join. ;~;
[16:32] <Prime_2> Dude, I'm telling you
[16:32] <Prime_2> I would have reset the map if you had asked
[16:32] <Prime_2> I thought you didn't mind. ;-;
[16:33] <JTE> fixed the climb camera thing
[16:33] <Prime_2> woo
[16:35] <JTE> adding "climbing" checks to everywhere cv_chasecam appears...
[16:37] <Rob> [Mon, 17:31:26 PM] <@Mystic> lol, I think I'm getting a little better at SS8 =P < Should I make it harder then?
[16:38] <Prime_2> lol
[16:38] <Prime_2> ...now to try and understand what the difference between ipairs(bleh) and pairs(bleh) is
[16:40] <JTE> changing a million refrences to cv_chasecam.value to camera.chase ... @@; and same for splitscreen player...
[16:40] <JTE> ipairs() is for ordered pairs that start at 1 and go in a linear list upwards
[16:40] <JTE> pairs() is for unordered pairs that can include strings and everything else.
[16:40] <Prime_2> ah
[16:41] <Prime_2> so the "for a,b" thing is to assign a variable to each individual item in a pair?
[16:41] <Prime_2> so in an item in the list that reads spawnstate = S_WHATEVER, a would be spawnstate and b would be whatever, same for any other item in that list?
[16:41] <Prime_2> am I getting that right?
[16:42] <JTE> I am so gonna need to change cv_flipcam to being a player flag like autoaim
[16:43] <JTE> Prime_2, it goes "for k,v in pairs(table)" because the pairs() function returns an iterator function to go over table, which itself returns two values - "key" and "value" - each time it is called.
[16:43] <JTE> similarly, "for player in players.iterate" doesn't have the () at the end because "players.iterate" IS the iterate function itself already, and it only returns one value - "player" - each time it is called.
[16:44] <JTE> So confusing, yes? @_@
[16:44] <Prime_2> key is the item in the list, v is the value of that item
[16:45] <JTE> yes, in the case of hideme, key would be the string "spawnstate" while value would be the number S_INVISIBLE
[16:45] <JTE> or key would be the string "flags" and value would be the number MF_NOBLOCKMAP|MF_NOSECTOR
[16:47] <Prime_2> Ah, so the ipairs thing is for where the key is just the order of appearance
[16:47] <JTE> for ipairs(list), the variables are _ and i. I named the first one underscore because it is unused, but its value will be the number 1, then the value of i is the number MT_BOUNCERING, then _ is 2 and i is MT_RAILRING, then _ is 3 and i is MT_AUTOMATICRING etc.
[16:47] <Prime_2> yeah
[16:47] <JTE> When list[_] is nil, it stops and exits the loop.
[16:49] <Prime_2> hm.
[16:50] <Prime_2> the meaning of mobjinfo[k] = v is pretty clear then, but this is actually the first thing I've seen that uses a syntax like that, with those brackets
[16:51] <JTE> I should add a P_ResetCamera(player) function to Lua. it calls P_ResetCamera if player is the current displayplayer. :3
[16:51] <Prime_2> Would I be correct to assume that mobjinfo[MT_BOUNCERING][spawnstate] = S_INVISIBLE would work, or is the brackets thing only for lists?
[16:52] <JTE> mobjinfo[MT_BOUNCERING].spawnstate = S_INVISIBLE is the exact same thing as mobjinfo[MT_BOUNCERING]["spawnstate"] = S_INVISIBLE
[16:52] <JTE> so, correct, but the quotes are necessary.
[16:52] <Prime_2> ah
[16:52] <Prime_2> ...for spawnstate but not MT_BOUNCERING, for some reason.
[16:52] <Prime_2> kay
[16:52] <JTE> MT_BOUNCERING is a number
[16:53] <Prime_2> and spawnstate is a... something else, nothing comes to mind right now
[16:53] <JTE> string. ...
[16:53] <Prime_2> Really? Just a string? XD
[16:53] <JTE> anything in quotation marks is a string.
[16:53] <JTE> yep.
[16:54] <Prime_2> I figured it would be a... field, or key, or something that refers to what it actually does. But I guess mobjinfo just takes the string and then finds the real whatchyoumajiggit from that, huh.
[16:54] <JTE> my magical C code sees "oh hey. you're accessing the mobjinfo table. let's see what you're trying to do... okay, for the mobj number 2270-bajillion, you want to set the 'spawnstate' to the number 2... Got it. Done!"
[16:54] <JTE> Yes, spawnstate is a key. but the key is just a string.
[16:56] <JTE> and it reads the string to find the matching C-key to set, by way of checking the string against every possible value. XD (and if you put in a nonsense string for players or mobjs, it makes a new Lua variable thingy -- mobjinfo just spews errors instead)
[16:57] <Prime_2> well
[16:57] <Prime_2> that was informative
[16:58] <Prime_2> thanks
 
Last edited by a moderator:
Usable Structures:

cannot be changed (in other words, retrieve-only)
Unimplemented, unusable for Lua

mobjinfo_t
(Len operation, #, on a mobjinfo_t struct variable returns the object/mobj type number)
*doomednum
*spawnstate (statenum_t, S_)
*spawnhealth
*seestate (statenum_t, S_)
*seesound (sfxenum_t, sfx_)
*reactiontime
*attacksound (sfxenum_t, sfx_)
*painstate (statenum_t, S_)
*painchance
*painsound (sfxenum_t, sfx_)
*meleestate (statenum_t, S_)
*missilestate (statenum_t, S_)
*deathstate (statenum_t, S_)
*xdeathstate (statenum_t, S_)
*deathsound (sfxenum_t, sfx_)
*speed
*radius
*height
*dispoffset
*mass
*damage
*activesound (sfxenum_t, sfx_)
*flags (MF_ flags)
*raisestate (statenum_t, S_)
*(extra variables can be added here)

state_t
(Len operation, #, on a state_t struct variable returns the state number)
*sprite (spritenum_t, SPR_)
*frame
*tics
*action (Action pointers, usually with names starting with "A_", retrieving this returns both the function itself and the function's name as a string)
*var1
*var2
*nextstate (statenum_t, S_)

sfxinfo_t
(Len operation, #, on a sfxinfo_t struct variable returns the sound number)
*name (returns name of sound without "sfx_" prefix)
*singular
*priority
*flags (SF_ flags for sounds)
*volume
*skinsound (will return -1 for sounds not usable for skins, otherwise returns skin sound #)

mobj_t
*valid
*thinker
*x
*y
*z
*snext (mobj_t)
*sprev
*angle
*sprite (spritenum_t, SPR_)
*frame
*touching_sectorlist
*subsector (subsector_t)
*floorz
*ceilingz
*radius
*height
*momx (x-axis momentum)
*momy (y-axis momentum)
*momz (z-axis (vertical) momentum)
*pmomz (vertical momentum of moving FOF platforms or similar, added to momz)
*tics (state tic timer, when this reaches 0 the state is changed and this is set to the new state's tic count)
*state (statenum_t, S_ - originally state_t in-game; calls P_SetMobjState()/P_SetPlayerMobjState() on change)
*flags (MF_ flags)
*flags2 (MF2_ flags)
*eflags (MFE_ flags)
*skin (skin name, e.g "sonic" or "tails", usually just used by players except in a few character-specific cases such as 1up monitors and exit signs)
*color (SKINCOLOR_)
*bnext (mobj_t)
*bprev
*hnext (mobj_t)
*hprev (mobj_t)
*type (mobjtype_t, MT_)
*info (mobj's infotable properties, mobjinfo_t)
*health
*movedir
*movecount
*target (mobj_t)
*reactiontime
*threshold
*player (player properties (only valid if a player/bot), player_t)
*lastlook
*spawnpoint (map thing spawn point this mobj was spawned by, mapthing_t)
*tracer (mobj_t)
*friction (fixed_t factor to multiply (or rather, diminish) speed by, default is 59392, or 0.90625*FRACUNIT)
*movefactor (used only for misc purposes despite code being around for use with friction effects - this in fact does nothing)
*fuse (fuse timer, when this reaches 0 this will do something)
*watertop (top of a water FOF)
*waterbottom (bottom of a water FOF)
*mobjnum
*scale (default scale is FRACUNIT; for Lua exclusively this sets destscale to match and calls P_SetScale() on change)
*destscale (destination scale, scale gradually changes to match this value)
*scalespeed (scale-changing speed)
*extravalue1 (extra variable for various uses)
*extravalue2 (extra variable for various uses)
*cusval (mobj's custom value, from SRB2Morphed)
*cvmem (mobj's custom value in memory, from SRB2Morphed)
*(extra variables can be added)

player_t
(Len operation, #, on a player_t struct variable returns the player number)
*valid
*name (returns player's name as a string)
*mo (mobj_t)
*cmd (ticcmd_t)
*playerstate (PST_)
*viewz (absolute viewing height for 1st person cam)
*viewheight (base viewing height from player bottom)
*deltaviewheight (amount to alter viewheight by)
*bob
*aiming (vertical viewing angle)
*awayviewaiming (vertical viewing angle for alternate view cam)
*health
*pity
*currentweapon (Current weapon selected, WEP_)
*ringweapons (Weapons obtained, RW_ flags)
*powers[(powers_t, pw_)] (requires table for most purposes, this sets value for the selected power; e.g power[pw_invulnerability] = 20*TICRATE sets invincibility to last 20 seconds)
*pflags (pflags_t, PF_ flags)
*panim (panim_t, PA_)
*flashcount
*flashpal (PAL_)
*skincolor (SKINCOLOR_)
*score
*dashspeed
*dashtime
*normalspeed (S_SKIN "normalspeed")
*runspeed (S_SKIN "runspeed")
*thrustfactor (S_SKIN "thrustfactor")
*accelstart (S_SKIN "accelstart")
*acceleration (S_SKIN "acceleration")
*charability (S_SKIN "ability", CA_)
*charability2 (S_SKIN "ability2", CA2_)
*charflags (S_SKIN "flags", SF_ flags)
*thokitem (S_SKIN "thokitem", mobjtype_t MT_)
*spinitem (S_SKIN "spinitem", mobjtype_t MT_)
*revitem (S_SKIN "revitem", mobjtype_t MT_)
*actionspd (S_SKIN "actionspd")
*mindash (S_SKIN "mindash")
*maxdash (S_SKIN "maxdash")
*jumpfactor (S_SKIN "jumpfactor")
*lives
*continues
*xtralife
*gotcontinue
*speed (normally obtained using rmomx/rmomy, this will always be positive; for zoomtubes/rope hangs this is the speed of the effect)
*jumping (not the same as PF_JUMPED), this is turned on when jumping, turned off when the jump button is pressed to cause momz cut)
*secondjump (normally just set to 1 if using special ability; also used in other ways for morph's abilities)
*fly1 (tails flight timer, decreases to 0)
*scoreadd (# of enemies destroyed for score chains)
*glidetime (time spent gliding, increases)
*climbing
*deadtimer (player death timer)
*exiting (exiting level timer)
*homing (homing attack timer)
*cmomx (conveyor momx)
*cmomy (conveyor momy)
*rmomx ("real" momx, calculated as player.mo.momx - player.cmomx)
*rmomy ("real" momy, calculated as player.mo.momy - player.cmomy)
*numboxes
*totalring
*realtime
*laps
*ctfteam (0 = no team, 1 = red, 2 = blue)
*gotflag (use with GF_REDFLAG/GF_BLUEFLAG)
*weapondelay
*tossdelay
*starpostx
*starposty
*starpostz
*starpostnum
*starposttime
*starpostangle
*angle_pos
*old_angle_pos
*axis1 (mobj_t)
*axis2 (mobj_t)
*bumpertime
*flyangle
*drilltimer
*linkcount
*linktimer
*anotherflyangle
*nightstime
*drillmeter
*drilldelay
*bonustime (boolean)
*capsule (mobj_t)
*mare
*marebegunat
*startedtime
*finishedtime
*finishedrings
*marescore
*lastmarescore
*lastmare
*maxlink
*texttimer
*textvar
*lastsidehit
*lastlinehit
*losstime
*onconveyor
*awayviewmobj (alternate view camera, mobj_t)
*awayviewtics (alt. view cam timer)
*spectator (boolean)
*bot
*jointime
*fovadd (OpenGL-only)
*(extra variables can be added)

ticcmd_t
*forwardmove (positive if moving forward, negative if backwards)
*sidemove (positive if moving rightwards, negative if leftwards)
*angleturn (angle being turned)
*aiming
*buttons (BT_ flags)

skin_t (retrieve-only)
(Len operation, #, on a skin_t struct variable returns the skin number)
*valid
*name
*spritedef
*wadnum
*flags
*realname
*hudname
*charsel
*face
*superface
*ability
*ability2
*thokitem
*spinitem
*revitem
*actionspd
*mindash
*maxdash
*normalspeed
*runspeed
*thrustfactor
*accelstart
*acceleration
*jumpfactor
*starttranscolor
*prefcolor
*highresscale
*soundsid

mapthing_t
*valid
*x
*y
*angle
*type (map thing number, or "doomednum")
*options (MTF_ flags)
*z
*extrainfo (multiple of 4096s added to actual thing type in map)
*mobj (mobj this spawnpoint is linked to, mobj_t)

sector_t
(Len operation, #, on a sector_t struct variable returns the sector number)
*valid
*floorheight
*ceilingheight
*floorpic
*ceilingpic
*lightlevel
*special
*tag

subsector_t (retrieve-only)
(Len operation, #, on a subsector_t struct variable returns the subsector number)
*valid
*sector (sector_t)
*numlines
*firstline
*validcount

line_t (retrieve-only)
(Len operation, #, on a line_t struct variable returns the linedef number)
*valid
*v1 (vertex_t)
*v2 (vertex_t)
*dx
*dy
*flags (ML_ flags)
*special
*tag
*sidenum[(side number, can be 0 or 1)] (returns sidedef # of selected side, or alternatively "sidenum.valid" can be used to test if the attached linedef is still valid or not)
*frontside (side_t, same as sides[sidenum[0]])
*backside (side_t, same as sides[sidenum[1]], returns nothing if linedef doesn't have a back sidedef set)
*slopetype ("horizontal", "vertical", "positive" or "negative")
*frontsector (sector_t)
*backsector (sector_t)
*validcount
*firsttag
*nexttag
*text

side_t (retrieve-only)
(Len operation, #, on a side_t struct variable returns the sidedef number)
*valid
*textureoffset
*rowoffset
*toptexture
*bottomtexture
*midtexture
*sector (sector_t)
*special
*repeatcnt
*text

vertex_t (retrieve-only)
(Len operation, #, on a vertex_t struct variable returns the vertex number)
*valid
*x
*y
*z

consvar_t (retrieve-only)
*name
*defaultvalue
*flags (cv_flags_t, CV_)
*value
*string
*changed

hudinfo_t
(Len operation, #, on a hudinfo_t struct variable returns the hudinfo number)
*valid
*x
*y

patch_t (retrieve-only)
*valid
*width
*height
*leftoffset
*rightoffset
 
Last edited:
Tables:

Custom Tables:

* local tablename = {val1 = a, val2 = b, val3 = c, ...}
Defines/creates a new table including all values listed, giving each of them values. Can be left blank if needed!

* structure.tablename = {val1 = a, val2 = b, val3 = c, ...}
Same as above, except for tieing the newly made table to an existing structure (such as mobj_t or player_t) at the same time


*tablename[val]
Brings up a specific value to be used from the table, to say, attribute properties to the value selected rather than with any value (like how mobjinfo[MT_NAME].val is used instead of mobj.info.val to bring up a specific object's mobjinfo property) Note that when this is printed in the console in-game, this will be shown as "userdata: [hex value]"

* tablename[n]
Same as above, in a way. Brings up the value/entry in the table assigned to the number given.

* #tablename[val/n]
Gives the number of the entry in the table given; e.g #mobjinfo[MT_PLAYER] = 3

* #tablename
Gives the total number of values/entries contained in selected table, so e.g. if there are no entries whatsoever, #tablename = 0


Existing tables of note:

* (mobjinfo_t) mobjinfo[mobjtype_t MT_NAME] (stand-alone version of mobj.info for bringing up a specific object type's property (for most cases mobjinfo[mobj.type] = mobj.info), #mobjinfo = NUMMOBJTYPES - number of object types)
* (state_t) states[statenum_t S_NAME] (In Lua, mobj.state is converted from state_t (containing state info) to statenum_t (just the state number), so states[mobj.state] is needed for bringing up the properties for the state a mobj is using, #states = NUMSTATES - number of states)
* (sfxinfo_t) S_sfx[sfxinfo_t sfx_name] ([Alternative name: sfxinfo[] ] Used for obtaining/setting sound info properties, #S_sfx = NUMSFX - number of object types)
*(string or spritenum_t) sprname[spritenum_t SPR_NAME or string "NAME"] (if a sprite number is used, as in sprnames[SPR_NAME], this will return the four-letter prefix of the sprite as a string ("NAME"). This also works the other way round, so sprnames["NAME"] will return the sprite number for that prefix (SPR_NAME).
* (player_t) players[playernum] (stand-alone version of mobj.player for getting properties of a specific player number in-game, #players = MAXPLAYERS - max number of players)
* (player.powers) powers[powertype_t pw_name] (for setting the value/duration of a specific player power, #powers = NUMPOWERS - number of powers)
* (skin_t) skins[skinnum] (for retrieving a specific skin number's properties, skin names e.g "sonic" can also be used in place of a number which in turn means an object's/player's mobj.skin or player.mo.skin can be used too, #skins = numskins - number of existing skins)
* (mapthing_t) mapthings[i] (map things, #mapthings = nummapthings - number of map things in map)
* (vertex_t) vertexes[i] (vertexes, #vertexes = numvertexes - number of vertexes in map)
* (line_t) lines[i] (linedefs, #lines = numlines - number of linedefs in map)
* (side_t) sides[i] (sidedefs, #sides = numsides - number of sidedefs in map)
* (subsector_t) subsectors[i] (subsectors, #subsectors = numsubsectors - number of subsectors in map)
* (sector_t) sectors[i] (sectors, #sectors = numsectors - number of sectors in map)
* (line.sidenum) sidenum[i] (side number on a linedef: 0 = front, 1 = back; returns sidedef #)
* (hudinfo_t) hudinfo[hudnum] (for hud items and their coordinates, #hudinfo = NUMHUDITEMS - number of hud items)


(Unrelated?)

* function structure:functionname() (shorthand for function structure.functionname(self))
Basically works like creating a typical custom function, except this is tied to a structure, and has only one variable to use. Mind that using colons make the value within the brackets default to "self", meaning you cannot change the name if you use them

* structure:functionname(self) (shorthand for structure.functionname(self))
...and of course this would be actually executing functions tied to structures, like you could also be able to do with typical custom functions



Metatable events: (see here for some sort of explanation because I have no hope of doing so myself)

Key:
New to Lua, or not documented at lua.org

*"__index"
*"__newindex"
*"__usedindex"
*"__gc" (garbage collection?)
*"__mode"
*"__eq" (== operation)
*"__add" (+ operation)
*"__sub" (- operation)
*"__mul" (* operation)
*"__div" (/ operation)
*"__mod" (% (modulus/remainder) operation)
*"__pow" (^ (power/exponent) operation)
*"__unm" (unary - operation)
*"__len" (# (length) operation)
*"__lt" (< (less than) operation)
*"__le" (<= (less than or equals) operation)
*"__concat" (concatenation operation)
*"__call"
*"__strhook"
*"__and" (& (bitwise and) operation)
*"__or" (| (bitwise or) operation)
*"__xor" (^^ (bitwise xor) operation)
*"__shl" (<< (left shift) operation)
*"__shr" (>> (right shift) operation)
*"__not" (~ (bitwise not) operation
 
Last edited:
Lua Standard Library Functions:
(For now this post is just a list of what we've got of them, since I'm certainly not a know-all about this stuff - look to the "explanations" links for full info on lua.org's manual)

Key:
Lua cannot use this function
Not documented at lua.org

Basic Library: (explanations)
*assert
*collectgarbage
*dofile
*error
*_G
*gcinfo
*getfenv
*getmetatable
*ipairs
*load
*loadfile
*loadstring
*next
*pairs
*pcall
*print
*rawequal
*rawget
*rawset
*select
*setfenv
*setmetatable
*tonumber
*tostring
*type
*unpack
*_VERSION
*xpcall
*Sublibrary - Coroutine Manipulation: (explanations)
(These need to be prefixed with "coroutine.")
*create
*resume
*running
*status
*wrap
*yield

String Manipulation: (explanations)
(These need to be prefixed with "string.", or alternatively they can be attached to strings themselves, e.g string.byte(s, i) can also have the format s:byte(i))
*byte
*char
*dump
*find
*format
*gfind
*gmatch
*gsub
*len
*lower
*match
*rep
*reverse
*sub
*upper

Table Manipulation: (explanations)
(These need to be prefixed with "table.")
*concat
*foreach
*foreachi
*getn
*maxn
*insert
*remove
*setn
*sort
 
Last edited:
Reserved keywords:
*and
*break
*continue
*do
*else
*elseif
*end
*false
*for
*function
*if
*in
*local
*nil
*not
*or
*repeat
*return
*then
*true
*until
*while

*<number>
*<name>
*<string>
*<eof>

Reserved symbols:
+ (addition, also can be used for concatination)
- (subtraction or unary negation)
* (multiplication)
/ (division)
% (modulo)
^ (exponentiation)
# (the "len" symbol - used to get the length of a value, string or table)
== (equals, for if checks)
~= (or !=) (not equals, for if checks)
<= (less than or equals, for if checks)
>= (greater than or equals, for if checks)
< (less than, for if checks)
> (greater than, for if checks)
= (equals, for setting a variable to a new value)
( and ) (regular brackets)
{ and } (brackets used for table creation)
[ and ] (brackets used for table entry grabbing)
;
:
,
.
.. (for concatination)
...
& (binary and)
| (binary or)
^^ (binary xor)
<< (binary left shift)
>> (binary right shift)
~ (binary not)
$ (for pseudo-numbers, can also be used for concatination)

Commenting:
-- comment (vanilla Lua short comment)
--[[ comment ]] (vanilla Lua long comment)
// comment (BLUA/C short comment)
/* comment */ (BLUA/C long comment)

Strings stuff:
* \a - bell
* \b - backspace
* \f - formfeed
* \n - newline
* \r - carriage return
* \t - horizontal tab
* \v - vertical tab
* \\ - backslash
* \" - quotation marks/double quote
* \' - apostrophe/single quote
* \x0000 - hex
* \u0000 - unicode
 
Last edited:
On triggering screen flashes(previously done with bonuscount/flashcount):
<JTE> you don't just set flashcount directly anymore
<JTE> you call P_FlashPal(player_t *pl, UINT16 type, UINT16 duration)
<JTE> which sets both flashcount and flashpal
<JTE> flashpal can be:
<JTE> #define PAL_WHITE 1
<JTE> #define PAL_MIXUP 2
<JTE> #define PAL_RECYCLE 3
<JTE> #define PAL_NUKE 4
<JTE> All P_FlashPal(player, PAL_WHITE, 16) does is set player.flashcount to 16 and player.flashpal to 1 (PAL_WHITE)
Duration is in tics, if that wasn't obvious.
 
Last edited:
...since when did the teleporter, recycler or nuke use non-white palettes for flashing?

(Although if they do use white, but there's support for them to use something else, we should probably take advantage of that.)
 
...since when did the teleporter, recycler or nuke use non-white palettes for flashing?

(Although if they do use white, but there's support for them to use something else, we should probably take advantage of that.)
Since really recently, I guess. I don't know that the teleporter or recycler have changed color, but the nuke flash is red right now.
 
Misc stuff for the benifit of people who don't code:

"$1", "$2", "$3" etc...:
These basically work like in these examples:

#1: value = $1 + something
#2: value1, value2 = $1 + $2, $2 - $1

The operations being done here are irrelevant, the point here is that $1, $2 and so on are the numbered original values of each of the variables being changed - so in example 1, $1 = value; and in example 2, $1 = value1 and $2 = value2.

Do note that when using multiple values as in example 2, $1 remains unchanged when changing value2 even after value1 itself has been altered.

Bitwise operations (&, |, ~ etc):
Okay, the quickest way to explain where most bitwise operations should be used is with the examples of an object's state (mobj.state) in comparison to an object's flags (mobj.flags)

An object's state only ever needs to hold ONE piece of information at a time, that is, the object's current state. As thus bitwise operations should generally not be used for these (think "if mobj.state == value", or "mobj.state = value", but not "mobj.state & value").

On the other hand an object's flags, as any experienced SOCCer should be aware of, contain not one but several flags in one value usually, each being equal to different powers of 2. As in, if my previous wording was terrible, an object can have both MF_SOLID (2) and MF_PUSHABLE (64) for instance, no?

This is where bitwise operations come in. A lot of the time in SRB2's source code especially we need to be able to check if an object has a particular flag or not, rather than the combined value of all the object's current flags.

This doesn't even apply just to object flags though, this also applies to the familiar linedef flags and object flags 2, as well as perhaps unfamiliar things such as the internal player flags (player.pflags) or character skin flags (player.skinflags), and probably more obscure uses I can't think of right now.

flags & FLAG : here this statement will return the value of FLAG if FLAG is set in flags, otherwise it will return 0 (effectively asking if true or false when placed after an "if").

flags | FLAG : here this statement will return the values of flags and FLAG combined. However if flags already has the value of FLAG contained within, this will instead be just flags alone. Very useful for adding a new object flag to an object, i.e "mobj.flags = $1|MF_ENEMY"

flags & ~FLAG : here this statement will return the value of flags with the value of FLAG removed. However if flags already doesn't have the value of FLAG contained, this will instead be flags as it is. As such this is equally useful for removing an object flag from an object, i.e "mobj.flags = $1 & ~MF_ENEMY"

flags & (FLAG1|FLAG2) : here, the statement will return FLAG1 if set, FLAG2 if set and FLAG1+FLAG2 if both are set. If we're putting this after an "if", this would be practically the same as "if flags & FLAG1 or flags & FLAG2"

flags & (FLAG1|FLAG2) == FLAG1|FLAG2 : for checking if the previous statement will return both FLAG1 AND FLAG2, e.g. whether an object has both of two flags and not just one, it is ideal to do this. This will therefore return either 1 or 0 (AKA true or false). If we're putting this after an "if", this would be practically the same as "if flags & FLAG1 and flags & FLAG2"

And just for confirmation, yes, "flags = $1 & ~(FLAG1|FLAG2)" will indeed remove both FLAG1 and FLAG2 from flags.

To be fair, maybe my explanation might seem a little too specific and doesn't quite explain the whole thing, perhaps a wikipedia page may help?

http://en.wikipedia.org/wiki/Bitwise_operation

& = Bitwise AND
| = Bitwise OR
^^ = Bitwise XOR (C uses ^ for XOR, but Lua uses it for powers/exponents)
~ = Bitwise NOT
<< = Left Shift (same as multiplying by 2 to a power)
>> = Right Shift (same as dividing by 2 to a power)

EDIT: Oooh, some more uses I just remembered:

In actions using both lower and upper 16 bits (like A_SpawnObjectRelative), bitwise operations are vital to make clear which set of bits to use.

locvar1 & 65535 would be var1's lower 16 bits, as this will return the value of locvar1 with all bits up to bit 15 (65536 is 2^16, so is the 17th bit if we remember bit 1 is for 1 (2^0) - this bit and above will not be included). It's difficult for me to explain what goes on with negative numbers, but this should still work anyway. =P

locvar1 >> 16 in turn would be var1's upper 16 bits, as this will return locvar1 bit-shifted down by 16 (i.e. divided by 65536 or 2^16). Any fractions are always cut off (rounded down if number is positive, rounded up if negative), so lower 16 bits will not affect this.

^^:

flags ^^ FLAG : This is similar to using | in that it will add the value of FLAG to flags if it is not already set, however if it is already set the value of FLAG would be removed from flags instead.

The basic reason why object flags and the like are each set to powers of 2 are because these then represent a single "bit", and any regular number can be a combination of various bits (think binary: 1 = 1, 2 = 10, 4 = 100, 8 = 1000, etc). So for "flags & FLAG" this is the value of all bits represented by FLAG in flags that are turned on, "flags | FLAG" or "flags ^^ FLAG" will be all bits in flags with FLAG's bits also turned on (or possibly off for ^^), and for "flags & ~FLAG" this is the value of all bits in flags turned on except the bits in FLAG.
 
Last edited:
Hud Library:

Important note: hud drawing functions cannot be used outside of hud hook functions, and similarly most base SRB2 functions cannot be used in hud hook functions either. Lua can detect if either situation is occurring and display errors warning about this.

Lua's Hud names list: (not related to SOC's HUD_ constants for hud items and hud item-position editing)
*"stagetitle"
*"textspectator"
*"score"
*"time"
*"rings"
*"lives"
*"nightslink"
*"nightsdrill"
*"nightsrings"
*"nightsscore"
*"nightstime"
*"nightsrecords"
*"rankings"
*"coopemeralds"
*"tokens"
*"tabemblems"

Hud Hooks: (for use with hud.add)
*"game" (main game hud, function takes variables v and stplyr)
*"scores" (hud displayed for tab stats, function takes a variable v)

Alignment options: (for use with drawString)
*"left"
*"right"
*"center"
*"fixed"

Functions:
Base:
*hud.enable(hudnum):
Turns back on the hud item selected from the hud names list above, if it had been disabled by hud.disable
*hud.disable(hudnum):
Turns off the hud item selected from the hud names list above
*hud.add(function(v, [stplyr]), hudhook):
Adds new hud items to be called by the selected Hud hook (see list above).
For the hook "game" (the default hook if not given), the function given can take a local variable with a name such as "v", used to give access to drawing library functions as listed below (used as such: v.catchPatch or v.draw etc), and "stplyr" is the player to display the hud items for. Hook "score" however only takes the first variable

Drawing library functions: (To be used with hud.add, see above for usage details)
*(patch_t) catchePatch("name"):
Caches a new patch using a graphic with the name given in string form. Returns the patch.
*(void) draw(INT32 x, INT32 y, patch_t patch, INT32 flags, colormap):
Draws a patch at the screen coordinates given, flags determines the patch's flags if given (see V_ flags). If colormap is given, it will be applied to the patch drawn
*(void) drawScaled(fixed_t x, fixed_t y, fixed_t scale, patch_t patch, INT32 flags):
Draws a scaled patch at the coordinates given (defaults for scale and flags if not given are FRACUNIT and 0)
*(void) drawFill(INT32 x, INT32 y, INT32 width, INT32 height, INT32 color):
Draws a box of a single palette color of a set width and height, can be given with no variables whatsoever - this just draws a black screen by default (defaults are 0, 0 320, 200 and 31 (black) respectively)
*(void) drawString(fixed_t x, fixed_t y, "string", INT32 flags, align):
Draws a string with optional flags (see V_ flags) and alignment settings (defaults are V_ALLOWLOWERCASE and "left"). If align is set to "fixed", x and y become fixed_t coordinates (i.e 1*FRACUNIT is one pixel on the screen)
*(INT32) stringWidth("string", INT32 flags):
Returns the length of the string with flags (see V_ flags) applied (flags defaults to V_ALLOWLOWERCASE if not set)
 
Last edited:
This should go without saying, but having the source on-hand for reference is pretty important here.

Just a heads up, but this thread has not yet been updated with the changes in patch 2.1.4 as of March 21st, 2014, and so some information may be incorrect. In the meantime, some of the differences are listed here.

EDIT: This is not a meant to be a Q&A topic, but rather a quick reference for people making Lua scripts. Please make new topics in editing help for asking questions.
 
Last edited:
Posting these WIP Lua documentation pages of my own from the wiki here for convenience:

Lua basics
Userdata structures
Misc. Lua documentation
 
Last edited:
Status
Not open for further replies.

Who is viewing this thread (Total: 1, Members: 0, Guests: 1)

Back
Top