ax.util¶
Source: gamemode/framework/util/util_core.lua
Utility helpers used across the Parallax framework (printing, file handling, text utilities, etc.).
Documented functions: 36
Functions¶
ax.util:ApproachAngle(fraction, startAng, finishAng, opts)ax.util:ApproachFraction(fraction, smooth, linear)ax.util:ApproachNumber(fraction, start, finish, opts)ax.util:ApproachVector(fraction, startVec, finishVec, opts)ax.util:Assert(condition, errorMessage, ...)ax.util:AssertDebug(condition, errorMessage, ...)ax.util:ClampRound(n, min, max, decimals)ax.util:DrawBlur(r, x, y, width, height, color)ax.util:DrawCircle(x, y, radius, segments, startAngle, endAngle)ax.util:DrawGradient(r, name, x, y, w, h, color)ax.util:DrawSlice(x, y, radius, startAngle, endAngle, color)ax.util:FindInCrosshair(client, target, range)ax.util:GetGradient(name)ax.util:GetGradientPath(name)ax.util:GetHeadTransform(entity)ax.util:GetMaterial(path, parameters)ax.util:GetPlayerFromAttachedRagdoll(entity)ax.util:GetProjectName()ax.util:GetServerAddress()ax.util:GetSortedEntries(entries, comparator)ax.util:GetSurfaceDataViaName(surfaceName)ax.util:GetSurfaceDataViaTrace(tr)ax.util:IsValidPlayer(client)ax.util:NameToUniqueID(name)ax.util:NormalizeColor(value)ax.util:PadNumber(num, digits)ax.util:ResolveBodygroupIndex(entity, groupID)ax.util:SafeCall(fn, ...)ax.util:SafeParseTable(tInput, bToJson)ax.util:SanitizeKey(key)ax.util:Scale(value)ax.util:ScreenScale(value)ax.util:ScreenScaleH(value)ax.util:TokenizeString(str)ax.util:UniqueIDToCamel(id)ax.util:UniqueIDToName(id)
ax.util:ApproachAngle(fraction, startAng, finishAng, opts)¶
Interpolates an Angle component-wise from startAng to finishAng.
Delegates to ApproachNumber independently for pitch (p), yaw (y), and roll (r) and assembles the results into a new Angle. Note that raw lerping of angles can wrap unexpectedly near 180°/−180° boundaries; for large yaw sweeps, normalise the angles before calling this function.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
fraction |
number |
Progress fraction in [0, 1]. |
startAng |
Angle |
The starting angle (fraction = 0). |
finishAng |
Angle |
The target angle (fraction = 1). |
opts |
table\|nil |
Options forwarded to ApproachNumber (smooth, linear, transition). |
Returns
Angle: The interpolated angle.
Usage
ax.util:ApproachFraction(fraction, smooth, linear)¶
Scales a 0–1 progress fraction by a smoothness percentage.
This is a low-level helper used by ApproachNumber, ApproachVector, and ApproachAngle. smooth is expressed as a percentage (0–100): a value of 100 leaves the fraction unchanged; lower values compress it toward 0, making transitions feel slower or more eased. The result is always clamped to [0, 1] regardless of input.
linear is accepted for signature compatibility but does not currently alter the calculation — the distinction between linear and non-linear movement is handled at the ApproachNumber level.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
fraction |
number |
The raw progress fraction, expected in [0, 1]. |
smooth |
number |
Smoothness multiplier as a percentage (0–100). Defaults to 100 (no scaling) when nil or non-numeric. |
linear |
boolean\|nil |
Reserved for future use; has no effect currently. |
Returns
number: The scaled and clamped fraction in [0, 1].
Usage
ax.util:ApproachNumber(fraction, start, finish, opts)¶
Interpolates a number from start to finish using a progress fraction.
The fraction is first passed through ApproachFraction using opts.smooth (default 100, i.e. no compression). The transition mode then determines how the adjusted fraction maps to the final value:
"lerp"(default): standard linear interpolation viaLerp."smoothstep": applies a cubic ease-in/ease-out curve (t² × (3 − 2t)) before lerping, producing a gentle S-curve acceleration/deceleration."linear"oropts.linear = true: usesmath.Approach, which moves at a constant step-size per call rather than lerping, useful for physics-style clamped movement.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
fraction |
number |
Progress fraction in [0, 1]. |
start |
number |
The value at fraction = 0. |
finish |
number |
The value at fraction = 1. |
opts |
table\|nil |
Optional settings table: smooth number (0–100) smoothness percent passed to ApproachFraction; linear boolean when true forces the "linear" transition mode; transition string "lerp" | "smoothstep" | "linear". |
Returns
number: The interpolated value betweenstartandfinish.
Usage
local v = ax.util:ApproachNumber(0.5, 0, 100) -- 50
local v = ax.util:ApproachNumber(0.5, 0, 100, { transition = "smoothstep" })
ax.util:ApproachVector(fraction, startVec, finishVec, opts)¶
Interpolates a Vector component-wise from startVec to finishVec.
Delegates to ApproachNumber independently for X, Y, and Z and assembles the results into a new Vector. All transition modes and smoothness options supported by ApproachNumber work here too. Useful for smoothly animating world positions or velocities over time in a Think hook.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
fraction |
number |
Progress fraction in [0, 1]. |
startVec |
Vector |
The starting vector (fraction = 0). |
finishVec |
Vector |
The target vector (fraction = 1). |
opts |
table\|nil |
Options forwarded to ApproachNumber (smooth, linear, transition). |
Returns
Vector: The interpolated vector.
Usage
ax.util:Assert(condition, errorMessage, ...)¶
Asserts a condition, printing an error message when it is false.
Unlike Lua's built-in assert, this does NOT throw — execution continues after the call. The error is printed via PrintError (which uses ErrorNoHaltWithStack, so a stack trace is included in the output).
When condition is falsy, returns false followed by any extra arguments.
When condition is truthy, returns it unchanged followed by extra arguments.
Use this for precondition checks where you want to log the failure clearly but still allow the caller to handle it gracefully.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
condition |
any |
The value to test. Falsy (false/nil) triggers the error. |
errorMessage |
string\|nil |
The message to print on failure. Defaults to "Assertion failed". |
... |
any |
Extra values appended to the error output and forwarded as additional return values. |
Returns
boolean|any:condition(or false on failure), followed by....
Usage
local ok = ax.util:Assert(istable(data), "Expected table, got", type(data))
if ( !ok ) then return end
ax.util:AssertDebug(condition, errorMessage, ...)¶
Asserts a condition, printing a debug message when it is false.
Behaves identically to Assert except the failure message is routed through PrintDebug instead of PrintError. This means the output is only visible when the developer convar is ≥ 1 AND ax_debug_realm is set to match the current realm — making it suitable for internal consistency checks that should be silent in production but informative during development.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
condition |
any |
The value to test. Falsy (false/nil) triggers the debug message. |
errorMessage |
string\|nil |
The message to print on failure. Defaults to "Assertion failed". |
... |
any |
Extra values appended to the debug output and forwarded as additional return values. |
Returns
boolean|any:condition(or false on failure), followed by....
Usage
ax.util:ClampRound(n, min, max, decimals)¶
Clamps a number to a range, then rounds it to a given precision.
Clamping is applied first, so the rounded result is always within [min, max]. When decimals is 0 or omitted, math.Round is used (nearest integer). For positive decimals, the number is scaled by 10^decimals, rounded, then scaled back, preserving that many decimal places. min and max are both optional; pass nil to skip either bound.
Non-numeric input for n is treated as 0.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
n |
number |
The number to clamp and round. |
min |
number\|nil |
Lower bound (inclusive). Skipped when nil. |
max |
number\|nil |
Upper bound (inclusive). Skipped when nil. |
decimals |
number\|nil |
Number of decimal places to preserve (default 0). |
Returns
number: The clamped and rounded result.
Usage
ax.util:ClampRound(3.14159, 0, 10, 2) -- 3.14
ax.util:ClampRound(150, 0, 100) -- 100
ax.util:ClampRound(4.6) -- 5
ax.util:DrawBlur(r, x, y, width, height, color)¶
Draws a blurred, optionally rounded rectangle on the screen.
Thin wrapper around ax.render.Draw using ax.render.BLUR mode.
The blur is rendered over whatever is already on screen at that region, making it useful for frosted-glass UI elements. Alpha on color controls the overall opacity of the blur overlay.
Realm: client
Parameters
| Name | Type | Description |
|---|---|---|
r |
number |
Corner roundness in pixels (0 for a sharp rectangle). |
x |
number |
Left edge of the rectangle in screen pixels. |
y |
number |
Top edge of the rectangle in screen pixels. |
width |
number |
Width of the rectangle in pixels. |
height |
number |
Height of the rectangle in pixels. |
color |
Color |
Color applied over the blur; alpha controls opacity. |
Usage
ax.util:DrawCircle(x, y, radius, segments, startAngle, endAngle)¶
Draws a smooth arc or full circle outline using polygons.
Generates vertices along the arc from startAngle to endAngle (both in degrees) and draws them as a polygon using surface.DrawPoly. The arc is not filled — it is an open polyline. For a filled circle, use DrawSlice instead. segments controls smoothness; 64 is a good default for most sizes. Call surface.SetDrawColor before this function to set the line colour.
Realm: client
Parameters
| Name | Type | Description |
|---|---|---|
x |
number |
Center X of the arc in screen pixels. |
y |
number |
Center Y of the arc in screen pixels. |
radius |
number |
Radius of the arc in pixels. |
segments |
number\|nil |
Number of polygon segments (default: 64). Higher values produce a smoother curve. |
startAngle |
number\|nil |
Starting angle in degrees (default: 0). 0 is the 3-o'clock position; angles increase clockwise. |
endAngle |
number\|nil |
Ending angle in degrees (default: 360, full circle). Set to less than 360 for a partial arc. |
Usage
surface.SetDrawColor(255, 255, 255, 200)
ax.util:DrawCircle(ScrW() / 2, ScrH() / 2, 64) -- full circle
ax.util:DrawCircle(100, 100, 32, 32, 0, 180) -- half-circle arc
ax.util:DrawGradient(r, name, x, y, w, h, color)¶
Draws a gradient material tinted with a color on the screen.
Resolves the gradient via GetGradient(name), then draws it using ax.render.DrawMaterial with optional corner rounding and tint color. When color is omitted, an opaque white tint is used (no tinting).
Realm: client
Parameters
| Name | Type | Description |
|---|---|---|
r |
number |
Corner roundness in pixels (0 for a sharp rectangle). |
name |
string |
A direction alias ("left", "right", etc.) or a full material path. See GetGradientPath for all accepted aliases. |
x |
number |
Left edge of the draw area in screen pixels. |
y |
number |
Top edge of the draw area in screen pixels. |
w |
number |
Width of the draw area in pixels. |
h |
number |
Height of the draw area in pixels. |
color |
Color\|nil |
Optional tint applied to the gradient texture. Alpha controls overall opacity. Defaults to Color(255, 255, 255, 255). |
Usage
ax.util:DrawGradient(0, "left", 0, 0, 200, 400, Color(0, 0, 0, 200))
ax.util:DrawGradient(4, "right", ScrW() - 64, 0, 64, ScrH())
ax.util:DrawSlice(x, y, radius, startAngle, endAngle, color)¶
Draws a filled pie slice, useful for circular progress indicators.
Constructs a polygon with the centre point as vertex 0 and arc vertices fanning out from startAngle to endAngle. An internal –90° offset is applied so that 0° corresponds to the top of the circle (12-o'clock position), making it intuitive for progress bars that start at the top.
Uses a fixed 64-segment resolution. The slice is filled solid with color.
Realm: client
Parameters
| Name | Type | Description |
|---|---|---|
x |
number |
Center X of the slice in screen pixels. |
y |
number |
Center Y of the slice in screen pixels. |
radius |
number |
Radius of the slice in pixels. |
startAngle |
number |
Starting angle in degrees. 0 = top (12 o'clock). |
endAngle |
number |
Ending angle in degrees. 360 = full circle. |
color |
table |
Color table with r, g, b, a fields. |
Usage
ax.util:FindInCrosshair(client, target, range)¶
Returns true when target falls within client's crosshair cone.
Uses the dot product of client's aim vector and the normalised direction to target's eye position (or world centre for non-player entities). The dot product is compared against range as a threshold: a value of 1.0 means the target must be directly on-axis; 0.9 (default) allows roughly ±26°; 0.0 accepts any direction in front of the player. A lower range value produces a wider acceptance cone.
Returns nil (falsy) when either client or target is not a valid player.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
client |
Player |
The player whose aim vector is used. |
target |
Entity |
The entity to test against the crosshair cone. |
range |
number\|nil |
Dot-product threshold in [0, 1]. Higher values require tighter aim. Defaults to 0.9. |
Returns
boolean|nil: True iftargetis within the crosshair cone, nil if either argument is not a valid player.
Usage
-- Is Entity(2) roughly in Entity(1)'s sights?
ax.util:FindInCrosshair(Entity(1), Entity(2)) -- default 0.9
-- Wider cone (accepts targets up to ~60° off-axis):
ax.util:FindInCrosshair(Entity(1), Entity(2), 0.5)
-- Very tight aim required (almost pixel-perfect):
ax.util:FindInCrosshair(Entity(1), Entity(2), 0.99)
ax.util:GetGradient(name)¶
Returns a cached gradient IMaterial by direction name or path.
Resolves name to a path via GetGradientPath, then fetches or creates the material via GetMaterial. Subsequent calls with the same name are served from the material cache at no extra cost.
Realm: client
Parameters
| Name | Type | Description |
|---|---|---|
name |
string |
A direction alias ("left", "right", etc.) or a full material path. See GetGradientPath for all accepted values. |
Returns
IMaterial: The corresponding gradient material.
Usage
ax.util:GetGradientPath(name)¶
Resolves a short gradient direction name to a GMod vgui material path.
Accepted short names and their aliases (case-insensitive):
"left"/"l"/1→"vgui/gradient-l""right"/"r"/2→"vgui/gradient-r""top"/"up"/"u"/3→"vgui/gradient-u""bottom"/"down"/"d"/4→"vgui/gradient-d"
Any unrecognised string is returned as-is, allowing full material paths to be passed through without translation. An empty or non-string name defaults to "vgui/gradient-l".
Realm: client
Parameters
| Name | Type | Description |
|---|---|---|
name |
string |
A direction alias or a full material path. |
Returns
string: The resolved material path.
Usage
ax.util:GetGradientPath("right") -- "vgui/gradient-r"
ax.util:GetGradientPath("vgui/my_gradient") -- "vgui/my_gradient"
ax.util:GetHeadTransform(entity)¶
Returns the world position and angle of an entity's head.
Checks for the "eyes" attachment first; if found and valid, its position and angle are returned. Falls back to the ValveBiped.Bip01_Head1 bone when the attachment is absent or returns no data. Returns nil for both values when neither source is available (e.g. a prop with no skeleton).
A debug axis overlay is drawn at the resolved position for 0.1 seconds — this is intentional for development use.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
entity |
Entity |
The entity to inspect (player, NPC, or ragdoll). |
Returns
Vector|nil: World position of the head, or nil when not found.Angle|nil: World angle at the head, or nil when not found.
Usage
local headPos, headAng = ax.util:GetHeadTransform(entity)
if ( headPos ) then -- render something at head level end
ax.util:GetMaterial(path, parameters)¶
Returns a cached IMaterial, creating it on first use.
Materials are cached by a compound key of path and parameters so that the same path with different parameter strings produces distinct cache entries. parameters defaults to "" — callers that omit it get a different cache slot from those that pass an empty string explicitly only if they use a different string value.
Prints an error and returns false when path is nil/false.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
path |
string |
The material path (e.g. "sprites/glow"). |
parameters |
string\|nil |
Optional parameter string forwarded to Material() (e.g. "nocull noclamp smooth"). |
Returns
IMaterial|false: The cached or newly created material, or false on invalid path.
Usage
local mat = ax.util:GetMaterial("sprites/glow", "nocull")
local icon = ax.util:GetMaterial("vgui/icon_item")
ax.util:GetPlayerFromAttachedRagdoll(entity)¶
Returns the player whose death ragdoll is the given entity.
Iterates all connected players and checks whether any has a ragdoll.index relay value matching the entity's index. This relay is set by the framework when a player's death ragdoll is created. Returns nil when the entity is not a prop_ragdoll, is invalid, or no player has that ragdoll index.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
entity |
Entity |
The entity to test, expected to be a prop_ragdoll. |
Returns
Player|nil: The player who owns this ragdoll, or nil if not found.
Usage
local owner = ax.util:GetPlayerFromAttachedRagdoll(ent)
if ( owner ) then print(owner:Nick() .. "'s ragdoll") end
ax.util:GetProjectName()¶
Returns the active gamemode's folder name, used as a data namespace.
Calls engine.ActiveGamemode() to read the folder name of the gamemode currently running (e.g. "parallax" or "parallax-militaryrp"). Falls back to the literal string "parallax" if the engine API is unavailable.
This value is used by functions like BuildDataPath to scope persisted data files per-gamemode so derived gamemodes don't collide with each other.
Realm: shared
Returns
string: The active gamemode folder name, or"parallax"as a safe fallback.
Usage
ax.util:GetServerAddress()¶
Returns the server's network address, IP, and port as separate values.
Calls game.GetIPAddress() first. On the server side, falls back to the sv_ip convar if the primary call returns an empty string. Parses the resulting "ip:port" string into its components; the port defaults to 0 when not present in the string. Returns three nils when no address can be determined, and logs a debug message.
Realm: shared
Returns
string|nil: The full"ip:port"address string, or nil on failure.string|nil: The IP portion only (may be"0.0.0.0"on listen servers before a map is fully loaded).number|nil: The port number, or 0 when absent from the address.
Usage
local full, ip, port = ax.util:GetServerAddress()
if ( full ) then print("Server running at " .. full) end
ax.util:GetSortedEntries(entries, comparator)¶
Converts a key/value map into a sorted array of entry objects.
Each entry in the returned array is a table { key = k, value = v }.
The default sort order is case-insensitive lexicographic by key; when two keys are equal after lowercasing, the original (case-sensitive) key string is used as a tiebreaker so the order is stable and predictable.
Provide a custom comparator(a, b) (where a and b are entry tables) to override the sort. Returns an empty table if entries is not a table.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
entries |
table |
The key/value map to convert and sort. |
comparator |
function\|nil |
Optional sort function receiving two entry tables. Should return true when a should come before b. |
Returns
table: Sorted array of{ key, value }entry tables.
Usage
local sorted = ax.util:GetSortedEntries(ax.faction:GetAll())
for _, entry in ipairs(sorted) do print(entry.key, entry.value.name) end
ax.util:GetSurfaceDataViaName(surfaceName)¶
Returns the surface data table for a named physics surface material.
Looks up the internal surface index with util.GetSurfaceIndex, then retrieves the data table via util.GetSurfaceData. Returns nil when the name is not registered (index 0) or when surfaceName is nil/false.
Surface names are defined in scripts/surfaceproperties.txt and its includes (e.g. "concrete", "metal", "wood").
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
surfaceName |
string |
The physics surface material name to look up. |
Returns
table|nil: The surface data table, or nil if the name is unknown.
Usage
ax.util:GetSurfaceDataViaTrace(tr)¶
Returns the surface data table for the surface hit by a trace result.
Reads tr.SurfaceProps (the internal physics surface index stored in every trace result) and forwards it to util.GetSurfaceData. Returns nil when the trace missed (tr.Hit is false), when tr is nil, or when SurfaceProps is 0 (no valid surface). Pair with util.TraceLine or util.TraceEntity to get the trace result.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
tr |
table |
A trace result table as returned by util.TraceLine or similar. Must have Hit and SurfaceProps fields. |
Returns
table|nil: The surface data table, or nil if the trace missed or has no valid surface properties.
Usage
local tr = util.TraceLine({ start = eyePos, endpos = eyePos + eyeDir * 256, filter = client })
local data = ax.util:GetSurfaceDataViaTrace(tr)
if ( data ) then print(data.material) end
ax.util:IsValidPlayer(client)¶
Returns true if client is a player entity.
Checks the Lua type string via type() rather than IsValid(), so it is safe to call on any value including nil, non-entity tables, or invalid entities (which would make IsValid() error). Use this instead of IsValid(client) and client:IsPlayer() when you don't yet know whether the value is even an entity.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
client |
any |
The value to test. |
Returns
boolean: True ifclienthas Lua type"Player".
Usage
ax.util:NameToUniqueID(name)¶
Converts a human-readable name into a lowercase, underscore-separated ID.
Applies three transformations in order:
- Spaces (including runs of whitespace) are replaced with underscores.
- CamelCase boundaries (lowercase letter followed by uppercase) get an underscore inserted between them, e.g. "MyModule" → "My_Module".
- Any character that is not a letter (A–Z, a–z) or underscore is stripped, so digits and punctuation are removed entirely.
- The result is lowercased.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
name |
string |
The human-readable name to convert. |
Returns
string: A sanitised lowercase unique ID safe for use as a table key or module identifier.
Usage
ax.util:NameToUniqueID("My Module") -- "my_module"
ax.util:NameToUniqueID("MyModule") -- "my_module"
ax.util:NameToUniqueID("Faction 01") -- "faction_" (digits stripped)
ax.util:NormalizeColor(value)¶
Normalizes a color value to a valid Color object.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
value |
any |
The value to normalize. |
Returns
Color: The normalized color.
ax.util:PadNumber(num, digits)¶
Pads a number with leading zeroes to a minimum digit count.
Uses string.format with %0Xd under the hood. The result is always a string. If the number already has more digits than digits, it is returned without truncation — digits is a minimum, not a fixed width.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
num |
number |
The integer to pad. |
digits |
number |
The minimum number of digits in the output string. |
Returns
string: The zero-padded number as a string.
Usage
ax.util:PadNumber(7, 3) -- "007"
ax.util:PadNumber(1234, 3) -- "1234" (already wider, not truncated)
ax.util:PadNumber(0, 2) -- "00"
ax.util:ResolveBodygroupIndex(entity, groupID)¶
Resolves a bodygroup ID to a valid index.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
entity |
Entity |
The entity to resolve the bodygroup for. |
groupID |
any |
The bodygroup ID to resolve. |
Returns
number|nil: The resolved bodygroup index, or nil if invalid.
ax.util:SafeCall(fn, ...)¶
Calls a function safely, capturing any Lua error without throwing.
NOTE: This definition is overwritten later in this file by a second, simpler SafeCall. See the authoritative definition below for the live behaviour.
This version prints the error via PrintError and unpacks all return values; the later version returns only the first return value.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
fn |
function |
The function to call. Returns false immediately if not a function. |
... |
any |
Arguments forwarded to fn. |
Returns
boolean: True if the call succeeded without error.any: All values returned byfnwhen successful.
Usage
ax.util:SafeParseTable(tInput, bToJson)¶
Utility helpers used across the Parallax framework (printing, file handling, text utilities, etc.).
Converts between a JSON string and a Lua table safely.
Two modes depending on the inputs:
- When
bToJsonis true andtInputis a table, serialises the table to a JSON string viautil.TableToJSONand returns it. - Otherwise, if
tInputis a string, parses it as JSON viautil.JSONToTable(wrapped in pcall) and returns the resulting table, or nil on parse failure. IftInputis already a table it is returned unchanged — useful for APIs that accept either form.
Errors are reported through PrintError and never thrown.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
tInput |
string\|table |
The JSON string to parse, or a table to pass through (or serialise when bToJson is true). |
bToJson |
boolean\|nil |
When true and tInput is a table, converts it to a JSON string instead of parsing. |
Returns
table|string|nil: The parsed table, the serialised JSON string, or nil on failure.
Usage
local tbl = ax.util:SafeParseTable('{"key":"value"}')
local json = ax.util:SafeParseTable({ key = "value" }, true)
ax.util:SanitizeKey(key)¶
Sanitises an arbitrary string so it is safe to use in file names and paths.
Any character that is not alphanumeric (A–Z, a–z, 0–9), a hyphen (-), underscore (_), or period (.) is replaced with an underscore.
The value is coerced to string via tostring before processing. Returns "" when key is nil or false.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
key |
any |
The value to sanitise (coerced to string). |
Returns
string: A filesystem-safe string.
Usage
ax.util:SanitizeKey("Player:Test") -- "Player_Test"
ax.util:SanitizeKey("config/sub dir/file") -- "config_sub_dir_file"
ax.util:SanitizeKey("my.setting_key-v2") -- "my.setting_key-v2"
ax.util:Scale(value)¶
Scales a pixel value by the player's UI scale preference.
Reads the interface.scale option (default 1.0) and multiplies value by it. Use this for any hardcoded pixel dimension that should respect the user's interface scale setting (panel sizes, font sizes, offsets, etc.).
Realm: client
Parameters
| Name | Type | Description |
|---|---|---|
value |
number |
The base pixel value to scale. |
Returns
number: The value multiplied by the current UI scale factor.
Usage
ax.util:ScreenScale(value)¶
Applies GMod's ScreenScale then multiplies by the player's UI scale.
ScreenScale converts a value designed for a 640-wide reference display to the current screen width. This function additionally applies the interface.scale option on top, so sizes remain consistent across both different resolutions and different user scale preferences.
Prefer this over raw ScreenScale for all UI element sizing.
Realm: client
Parameters
| Name | Type | Description |
|---|---|---|
value |
number |
The reference value (as if the screen were 640 px wide). |
Returns
number: The resolution- and scale-adjusted pixel value.
Usage
ax.util:ScreenScaleH(value)¶
Applies GMod's ScreenScaleH then multiplies by the player's UI scale.
The height-based equivalent of ScreenScale — scales a reference value relative to screen height (480 px reference) rather than width. Multiply by the interface.scale option afterward for consistent vertical sizing.
Realm: client
Parameters
| Name | Type | Description |
|---|---|---|
value |
number |
The reference value (as if the screen were 480 px tall). |
Returns
number: The resolution- and scale-adjusted pixel value.
Usage
ax.util:TokenizeString(str)¶
Splits a string into tokens, preserving quoted multi-word segments.
Iterates the string character-by-character. Space characters split tokens unless the parser is inside a quoted region ("). Backslash (\) escapes the next character, so \" includes a literal quote in the current token without ending or starting a quoted region. Empty tokens (consecutive spaces) are skipped. Useful for parsing console-style commands where arguments can contain spaces when wrapped in double quotes.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
str |
string |
The input string to tokenise. |
Returns
table: An ordered array of token strings.
Usage
ax.util:TokenizeString('kick "John Doe" "bad behaviour"')
-- { "kick", "John Doe", "bad behaviour" }
ax.util:TokenizeString('set volume 0.5')
-- { "set", "volume", "0.5" }
ax.util:UniqueIDToCamel(id)¶
Converts an underscore-separated unique ID to PascalCase.
Each underscore followed by a lowercase letter triggers capitalisation of that letter and removal of the underscore. The very first character is also capitalised. Any character that is not alphanumeric is then stripped from the final result. Returns an empty string when id is not a string.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
id |
string |
The unique ID to convert (e.g. produced by NameToUniqueID). |
Returns
string: The PascalCase equivalent with non-alphanumeric characters removed.
Usage
ax.util:UniqueIDToCamel("my_module") -- "MyModule"
ax.util:UniqueIDToCamel("item_type_id") -- "ItemTypeId"
ax.util:UniqueIDToName(id)¶
Converts an underscore-separated unique ID back into a human-readable name.
Applies three transformations in order:
- Underscores are replaced with spaces.
- Spaces are inserted at CamelCase boundaries (e.g. from an ID that was produced by merging camel-cased words).
- The first letter of each word is capitalised and the rest are lowercased.
Useful for displaying stored IDs in UI labels without extra formatting logic.
Realm: shared
Parameters
| Name | Type | Description |
|---|---|---|
id |
string |
The unique ID to convert. |
Returns
string: A title-cased, space-separated name.
Usage
ax.util:UniqueIDToName("my_module") -- "My Module"
ax.util:UniqueIDToName("player_health_max") -- "Player Health Max"