Garry's Mod Wiki

util

This is the list of utility functions.

Methods

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.
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. Performs block checking.
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.
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 a 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.
string util.FullPathToRelative_Menu( string gma, string gamePath = "GAME" )
Converts the Full path of the given GMA file to the Relative Path. You can use util. RelativePathToFull_Menu to convert the Relative path back to the Full Path.
Returns a name for given automatically generated numerical animation event ID. This is useful for NPC models that define custom animation events.
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 persistent data of an offline player using their SteamID. See also Player:GetPData for a more convenient version of this function for online players, util. RemovePData and util. SetPData for the other accompanying functions. This function internally uses util. SteamIDTo64, it previously utilized Player:UniqueID which can cause collisions (two or more players sharing the same PData entry). This function now only uses the old method as a fallback if the name isn't found.
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.
Gets information about the sun position and obstruction or nil if there is no sun.
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.
Returns the name of a surface property at given ID. See also util. GetSurfaceData and util. GetSurfaceIndex for opposite function.
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-OBB (Orientated Bounding Box) intersection and returns position, normal and the fraction if there was an intersection.
Vector util.IntersectRayWithPlane( Vector rayOrigin, Vector rayDirection, Vector planePosition, Vector planeNormal )
Performs a ray-plane intersection and returns the hit position or nil.
number, number util.IntersectRayWithSphere( Vector rayOrigin, Vector rayDelta, Vector shperePosition, number sphereRadius )
Performs a ray-sphere intersection and returns the intersection positions or nil.
Returns whether a binary module is installed and is resolvable by require.
boolean util.IsBoxIntersectingSphere( Vector boxMin, Vector boxMax, Vector shpere2Position, number sphere2Radius )
Performs a box-sphere intersection and returns whether there was an intersection or not.
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.IsOBBIntersectingOBB( Vector box1Origin, Angle box1Angles, Vector box1Mins, Vector box1Maxs, Vector box2Origin, Angle box2Angles, Vector box2Mins, Vector box2Maxs, number tolerance )
Performs OBB on OBB intersection test.
boolean util.IsPointInCone( Vector point, Vector coneOrigin, Vector coneAxis, number coneSine, number coneLength )
Returns whether a point is within a cone or not.
boolean, number, number util.IsRayIntersectingRay( Vector ray1Start, Vector ray1End, Vector ray2Start, Vector ray2End )
Performs a ray-ray intersection and returns whether there was an intersection or not.
Check whether the skybox is visible from the point specified. This will always return true in fullbright maps.
boolean util.IsSphereIntersectingCone( Vector sphereCenter, number sphereRadius, Vector coneOrigin, Vector coneAxis, number coneSine, number coneCosine )
Returns whether a sphere is intersecting a cone or not.
boolean util.IsSphereIntersectingSphere( Vector sphere1Position, number sphere1Radius, Vector sphere2Position, number sphere2Radius )
Performs a sphere-sphere intersection and returns whether there was an intersection or not.
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 If the model isn't precached on the server, AND if the model file doesn't exist on disk If precache failed Model is the error model Running this function will also precache the model.
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, boolean ignoreLimits = false, boolean ignoreConversions = false )
Converts a JSON string to a Lua table. This will attempt to cast the string keys "inf", "nan", "true", and "false" to their respective Lua values. This completely ignores nulls in arrays. Issue Tracker: 3561Colors 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 including duplicate return values. If security or duplicate returns 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. This function will throw an error in the menu realm because it internally uses util. TraceLine which doesn't exist in the menu realm and thus error.
string util.RelativePathToFull_Menu( string gma, string gamePath = "GAME" )
Converts the relative path of the given GMA file to the Full Path. You can use util. FullPathToRelative_Menu to convert the Full path back to the Relative Path.
Returns the AddonInfo of the Addon the given file belongs to.
util.RemovePData( string steamID, string name )
Removes persistent data of an offline player using their SteamID. See also Player:RemovePData for a more convenient version of this function for online players, util. SetPData and util. GetPData for the other accompanying functions. This function internally uses util. SteamIDTo64, it previously utilized Player:UniqueID which can cause collisions (two or more players sharing the same PData entry). This function now tries to remove both old and new entries.
util.ScreenShake( Vector pos, number amplitude, number frequency, number duration, number radius, boolean airshake = false, CRecipientFilter filter = nil )
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 persistent data for offline player using their SteamID. See also Player:SetPData for a more convenient version of this function for online players, util. RemovePData and util. GetPData for the other accompanying functions. This function internally uses util. SteamIDTo64, it previously utilized Player:UniqueID which can cause collisions (two or more players sharing the same PData entry).
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. This is unique and will never return the same hash for a different string unlike util. CRC or util. MD5 which are both vulnerable to duplicate returns.
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.
Given a 64bit SteamID will return a STEAM_0:0:0 style Steam ID. This operation induces data loss. Not all fields of a 64bit SteamID can be represented using the STEAM_0:0:0 format.
Converts a STEAM_0:0:0 style SteamID to a 64bit SteamID.
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. All keys are strings in the JSON format, so all keys will be converted to strings! All integers will be converted to decimals (5 -> 5. 0). 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.
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( table tracedata, Entity ent )
Identical to util. TraceHull but uses an entity for mins/maxs inputs.
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
Returns if the user is currently picking an entity.
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.