Garry's Mod Wiki


This is the list of utility functions.


number util.AddNetworkString( string str )
Adds the specified string to a string table, which will cache it and network it to all clients automatically. Whenever you want to create a net message with net. Start, you must add the name of that message as a networked string via this function. If the passed string already exists, nothing will happen and the ID of the existing item will be returned. Each unique network name needs to be pooled once - do not put this function call into any other functions if you're using a constant string. Preferable place for this function is in a serverside lua file, or in a shared file with the net. Receive function. The string table used for this function does not interfere with the engine string tables and has 4095 slots. This limit is shared among all entities, SetNW* and SetGlobal* functions. If you exceed the limit, you cannot create new variables, and you will get the following warning: Warning: Table networkstring is full, can't add [key]Existing variables will still get updated without the warning. You can check the limit by counting up until util. NetworkIDToString returns nil
Vector util.AimVector( Angle ViewAngles, number ViewFOV, number x, number y, number scrWidth, number scrHeight )
Function used to calculate aim vector from 2D screen position. It is used in SuperDOF calculate Distance. Essentially a generic version of gui.ScreenToVector.
string util.Base64Decode( string str )
Decodes the specified string from base64.
string util.Base64Encode( string str, boolean inline = false )
Encodes the specified string to base64. Unless disabled with the inline argument, the Base64 returned is compliant to the RFC 2045 standard. This means it will have a line break after every 76th character.
util.BlastDamage( Entity inflictor, Entity attacker, Vector damageOrigin, number damageRadius, number damage )
Applies explosion damage to all entities in the specified radius.
util.BlastDamageInfo( CTakeDamageInfo dmg, Vector damageOrigin, number damageRadius )
Applies spherical damage based on damage info to all entities in the specified radius.
string util.Compress( string str )
Compresses the given string using the LZMA algorithm. Use with net.WriteData and net.ReadData for networking and util.Decompress to decompress the data.
string util.CRC( string stringToChecksum )
Generates the CRC Checksum of the specified string. This is NOT a hashing function. It is a checksum, typically used for error detection/data corruption detection. It is possible for this function to generate "collisions", where two different strings will produce the same CRC. If you need a hashing function, use util. SHA256.
string util.DateStamp()
Returns the current date formatted like '2012-10-31 18-00-00'
util.Decal( string name, Vector start, Vector end, Entity filter = NULL )
Performs a trace and paints a decal to the surface hit.
util.DecalEx( IMaterial material, Entity ent, Vector position, Vector normal, table color, number w, number h )
Performs a trace and paints a decal to the surface hit. This function has trouble spanning across multiple brushes on the map.
string util.DecalMaterial( string decalName )
Gets the full material path by the decal name. Used with util.DecalEx.
string util.Decompress( string compressedString, number maxSize = nil )
Decompresses the given string using LZMA algorithm. Used to decompress strings previously compressed with util.Compress.
number, Vector, number util.DistanceToLine( Vector lineStart, Vector lineEnd, Vector pointPos )
Gets the distance between a line and a point in 3d space.
util.Effect( string effectName, CEffectData effectData, boolean allowOverride = true, any ignorePredictionOrRecipientFilter = nil )
Creates an effect with the specified data. For Orange Box .pcf particles, see ParticleEffect, ParticleEffectAttach and CreateParticleSystem. When dispatching an effect from the server, some values may be clamped for networking optimizations. Visit the Set accessors on CEffectData to see which ones are affected. You will need to couple this function with IsFirstTimePredicted if you want to use it in predicted hook.
string util.FilterText( string str, number context = TEXT_FILTER_UNKNOWN, Player player = nil )
Filters given text using Steam's filtering system. The function will obey local client's Steam settings for chat filtering: In some cases, especially in a chatbox, messages from some players may return an empty string if the context argument used for filtering is TEXT_FILTER_CHAT and if the local player has blocked the sender of the message on Steam.
table util.GetModelInfo( string mdl )
Returns a table containing the info about the model. This function will silently fail if used on models with following strings in them: _shared _anims _gestures _anim _postures _gst _pst _shd _ss _anm _include
table, table util.GetModelMeshes( string model, number lod = 0, number bodygroupMask = 0 )
Returns a table of visual meshes of given model. This does not work on brush models (*number models) See also ENTITY:GetRenderMesh.
string util.GetPData( string steamID, string name, string default )
Gets PData of an offline player using their SteamID This function internally uses Player:UniqueID, which can cause collisions (two or more players sharing the same PData entry). It's recommended that you don't use it. See the related wiki page for more information.
pixelvis handle t util.GetPixelVisibleHandle()
Creates a new PixVis handle. See util.PixelVisible.
table util.GetPlayerTrace( Player ply, Vector dir = ply:GetAimVector() )
Utility function to quickly generate a trace table that starts at the players view position, and ends 32768 units along a specified direction.
table util.GetSunInfo()
Gets information about the sun position and obstruction or nil if there is no sun.
table util.GetSurfaceData( number id )
Returns data of a surface property at given ID.
number util.GetSurfaceIndex( string surfaceName )
Returns the matching surface property index for the given surface property name. See also util.GetSurfaceData and util.GetSurfacePropName for opposite function.
string util.GetSurfacePropName( number id )
Returns the name of a surface property at given ID. See also util.GetSurfaceData and util.GetSurfaceIndex for opposite function.
table util.GetUserGroups()
Returns a table of all SteamIDs that have a usergroup. This returns the original usergroups table, changes done to this table are not retroactive and will only affect newly connected usersThis returns only groups that are registered in the settings/users. txt file of your server. In order to get the usergroup of a connected player, please use Player:GetUserGroup instead.
Vector, Vector, number util.IntersectRayWithOBB( Vector rayStart, Vector rayDelta, Vector boxOrigin, Angle boxAngles, Vector boxMins, Vector boxMaxs )
Performs a "ray" box intersection and returns position, normal and the fraction.
Vector util.IntersectRayWithPlane( Vector rayOrigin, Vector rayDirection, Vector planePosition, Vector planeNormal )
Performs a ray-plane intersection and returns the hit position or nil.
boolean util.IsBinaryModuleInstalled( string name )
Returns whether a binary module is installed and is resolvable by require.
boolean util.IsInWorld( Vector position )
Checks if a certain position is within the world bounds.
boolean util.IsModelLoaded( string modelName )
Checks if the model is loaded in the game.
boolean util.IsSkyboxVisibleFromPoint( Vector position )
Check whether the skybox is visible from the point specified. This will always return true in fullbright maps.
boolean util.IsValidModel( string modelName )
Checks if the specified model is valid. A model is considered invalid in following cases: Starts with a space or maps Doesn't start with models Contains any of the following: _gestures _animations _postures _gst _pst _shd _ss _anm .bsp cs_fix On server: If the model isn't precached, if the model file doesn't exist on the disk If precache failed Model is the error model Running this function will also precache the model.
boolean util.IsValidPhysicsObject( Entity ent, number physobj )
Checks if given numbered physics object of given entity is valid or not. Most useful for ragdolls.
boolean util.IsValidProp( string modelName )
Checks if the specified prop is valid.
boolean util.IsValidRagdoll( string ragdollName )
Checks if the specified model name points to a valid ragdoll.
table util.JSONToTable( string json )
Converts a JSON string to a Lua table. Keys are converted to numbers wherever possible. This means using Player:SteamID64 as keys won't work. There is a limit of 15,000 keys total.Colors will not have the color metatable.Issue Tracker: 2407
table util.KeyValuesToTable( string keyValues, boolean usesEscapeSequences = false, boolean preserveKeyCase = false )
Converts a Valve KeyValue string (typically from util. TableToKeyValues) to a Lua table. Due to how tables work in Lua, keys will not repeat within a table. See util. KeyValuesToTablePreserveOrder for alternative.
table util.KeyValuesToTablePreserveOrder( string keyvals, boolean usesEscapeSequences = false, boolean preserveKeyCase = false )
Similar to util. KeyValuesToTable but it also preserves order of keys.
Vector util.LocalToWorld( Entity ent, Vector lpos, number bonenum )
Returns a vector in world coordinates based on an entity and local coordinates
string util.MD5( string stringToHash )
Generates the MD5 hash of the specified string. MD5 is considered cryptographically broken and is known to be vulnerable to a variety of attacks. If security is a concern, use util. SHA256.
string util.NetworkIDToString( number stringTableID )
Returns the networked string associated with the given ID from the string table.
number util.NetworkStringToID( string networkString )
Returns the networked ID associated with the given string from the string table.
string util.NiceFloat( number float )
Formats a float by stripping off extra 0's and . 's.
util.ParticleTracer( string name, Vector startPos, Vector endPos, boolean doWhiz )
Creates a tracer effect with the given parameters.
util.ParticleTracerEx( string name, Vector startPos, Vector endPos, boolean doWhiz, number entityIndex, number attachmentIndex )
Creates a tracer effect with the given parameters.
number util.PixelVisible( Vector position, number radius, pixelvis handle t PixVis )
Returns the visibility of a sphere in the world.
number util.PointContents( Vector position )
Returns the contents of the position specified. This function will sample only the world environments. It can be used to check if Entity:GetPos is underwater for example unlike Entity:WaterLevel which works for players only.
util.PrecacheModel( string modelName )
Precaches a model for later use. Model is cached after being loaded once. Modelprecache is limited to 4096 unique models. When it reaches the limit the game will crash.
util.PrecacheSound( string soundName )
Precaches a sound for later use. Sound is cached after being loaded once. Soundcache is limited to 16384 unique sounds on the server.Broken on purpose because hitting the limit above causes the server to shutdownUltimately does nothing on client, and only works with sound scripts, not direct paths.
table util.QuickTrace( Vector origin, Vector dir, Entity filter = nil )
Performs a trace with the given origin, direction, and filter.
util.RemovePData( string steamID, string name )
Removes PData of offline player using their SteamID. This function internally uses Player:UniqueID, which can cause collisions (two or more players sharing the same PData entry). It's recommended that you don't use it. See the related wiki page for more information.
util.ScreenShake( Vector pos, number amplitude, number frequency, number duration, number radius )
Makes the screen shake. The screen shake effect is rendered by modifying the view origin on the client. If you override the view origin in GM:CalcView you may not be able to see the shake effect.
util.SetPData( string steamID, string name, any value )
Sets PData for offline player using his SteamID. This function internally uses Player:UniqueID, which can cause collisions (two or more players sharing the same PData entry). It's recommended that you don't use it. See the related wiki page for more information.
string util.SHA1( string stringToHash )
Generates the SHA-1 hash of the specified string. SHA-1 is considered cryptographically broken and is known to be vulnerable to a variety of attacks. If security is a concern, use util. SHA256.
string util.SHA256( string stringToHash )
Generates the SHA-256 hash of the specified string.
number util.SharedRandom( string uniqueName, number min, number max, number additionalSeed = 0 )
Generates a random float value that should be the same on client and server. This function is best used in a Predicted Hook
Entity util.SpriteTrail( Entity ent, number attachmentID, table color, boolean additive, number startWidth, number endWidth, number lifetime, number textureRes, string texture )
Adds a trail to the specified entity.
Stack util.Stack()
Returns a new Stack object.
string util.SteamIDFrom64( string id )
Given a 64bit SteamID will return a STEAM_0: style Steam ID
string util.SteamIDTo64( string id )
Given a STEAM_0 style Steam ID will return a 64bit Steam ID
any util.StringToType( string str, string typename )
Converts a string to the specified type. This can be useful when dealing with ConVars.
string util.TableToJSON( table table, boolean prettyPrint = false )
Converts a table to a JSON string. Trying to serialize or deserialize SteamID64s in JSON will NOT work correctly. They will be interpreted as numbers which cannot be precisely stored by JavaScript, Lua and JSON, leading to loss of data. You may want to use util. SteamIDFrom64 to work around this. Alternatively, just append a character to the SteamID64 to force util. JSONToTable to treat it as a string. All keys are strings in the JSON format, so all keys will be converted to strings!This will produce invalid JSON if the provided table contains nan or inf values. Issue Tracker: 3561
string util.TableToKeyValues( table table, string rootKey = "TableToKeyValues" )
Converts the given table into a Valve key value string. Use util. KeyValuesToTable to perform the opposite transformation. You should consider using util. TableToJSON instead.
table util.Timer( number startdelay = 0 )
Creates a timer object.
number util.TimerCycle()
Returns the time since this function has been last called
boolean util.tobool( any input )
We advise against using this. It may be changed or removed in a future update. You should use tobool instead. Converts string or a number to a bool, if possible. Alias of tobool.
table util.TraceEntity( table tracedata, Entity ent )
Runs a trace using the entity's collisionmodel between two points. This does not take the entity's angles into account and will trace its unrotated collisionmodel. Clientside entities will not be hit by traces.
table util.TraceEntityHull( Entity ent1, Entity ent2 )
We advise against using this. It may be changed or removed in a future update. This function is broken and returns the same values all the time Traces from one entity to another.
table util.TraceHull( table TraceData )
Performs an AABB hull (axis-aligned bounding box, aka not rotated) trace with the given trace data. Clientside entities will not be hit by traces. This function may not always give desired results clientside due to certain physics mechanisms not existing on the client. Use it serverside for accurate results.
table util.TraceLine( table TraceData )
Performs a trace with the given trace data. Clientside entities will not be hit by traces. When server side trace starts inside a solid, it will hit the most inner solid the beam start position is located in. Traces are triggered by change of boundary.
string util.TypeToString( any input )
Converts a type to a (nice, but still parsable) string
boolean util.worldpicker.Active()
Returns if the user is currently picking an entity.
util.worldpicker.Finish( table tr )
This is used internally - although you're able to use it you probably shouldn't. Finishes the world picking. This is called when a user presses their mouse after calling util.worldpicker.Start.
util.worldpicker.Start( function callback )
Starts picking an entity in the world. This will suppress the next mouse click, and instead use it as a direction in the trace sent to the callback.