Miscellaneous

Some utility functions.  Unlike the functions in util.lua, this file only holds non-HL2 specific functions.

Summary
MiscellaneousSome utility functions.
Functions
explodeSplit a string by a separator.
stripCommentsStrips comments from a string
makePatternSafeMakes a string safe for pattern usage, like in string.gsub().
stripQuotesTrims leading and tailing quotes from a string
unescapeBackslashConverts ‘\\’ to ‘\’
splitPort
splitArgsThis is similar to string.Explode( “ “, str ) except that it will also obey quotation marks.
parseKeyValuesParses a keyvalue formatted string into a table.
makeKeyValuesMakes a key values string from a table.
toBoolConverts a bool, nil, string, or number to a bool
findVarGiven a string, find a var starting from the global namespace.
setVarGiven a string, find and set a var starting from the global namespace.
throwBadArgThrows an error similar to the lua “bad argument #x to <fn_name> (<type> expected, got <type>).
checkArgChecks to see if an arg matches what is expected, if not, calls throwBadArg().
isValidSteamIDChecks to see if a given string is a valid steamid.
isValidIPChecks to see if a given string is a valid IPv4 address.
removeCommentHeaderRemoves a comment header.
stringTimeToMinutesConverts a string containing time information to minutes.
secondsToStringTimeConverts a number of seconds to a string describing the time span.
Inheritance
Functions
inheritsFromCreates a psudeo-inheritance for lua.
Tables
root_classThis is a local table that holds our functions that we want all classes to have.
Functions
root_class:callThis is a utility function used by the metatable __call to resolve Class( ...
root_class:createThis is used to create new ‘class instances’.

Functions

explode

function ULib.explode(separator,
str,
limit)

Split a string by a separator.

Parameters

separatorThe separator string.
strA string.
limit(Optional) Max number of elements in the table

Returns

A table of str split by separator, nil and error message otherwise.

Revisions

v2.10Initial (dragged over from a GM9 archive though)

stripComments

function ULib.stripComments(str,
comment,
blockcommentbeg,
blockcommentend)

Strips comments from a string

Parameters

strThe string to stip comments from
commentThe comment string.  If it’s found, whatever comes after it on that line is ignored.  ( IE: “//” )
blockcommentbeg(Optional) The block comment begin string.  ( IE: “/<star>” )
blockcommentend(Optional, must be specified if above parameter is) The block comment end string.  ( IE: “<star>/” )

Returns

The string with the comments stripped, nil and error otherwise.

Revisions

v2.02Fixed block comments in more complicated files.

makePatternSafe

function ULib.makePatternSafe(str)

Makes a string safe for pattern usage, like in string.gsub().  Basically replaces all keywords with % and keyword.

Parameters

strThe string to make pattern safe

Returns

The pattern safe string

stripQuotes

function ULib.stripQuotes(s)

Trims leading and tailing quotes from a string

Parameters

sThe string to strip

Returns

The stripped string

unescapeBackslash

function ULib.unescapeBackslash(s)

Converts ‘\\’ to ‘\’

Parameters

sThe string to convert

Returns

The converted string

splitPort

function ULib.splitPort(ipAndPort)

Parameters

ipAndPortAn IP address in the form xxx.xxx.xxx.xxx:xxxx

Returns

The IP as the first return value, the port as the second return value

Revisions

v2.40Initial.

splitArgs

function ULib.splitArgs(args,
start_token,
end_token)

This is similar to string.Explode( “ “, str ) except that it will also obey quotation marks.

Parameters

argsThe string to split from
start_tokenThe string character to start a string with.
end_tokenThe string character to end a string with.

Returns

A table containing the individual arguments and a boolean stating whether or not mismatched quotes were found.

Example

ULib.splitArgs( "This is a \"Cool sentence to\" make \"split up\"" )

returns...

{ "This", "is", "a", "Cool sentence to", "make", "split up" }

Notes

  • Mismatched quotes will result in having the last quote grouping the remaining input into one argument.
  • Arguments outside of quotes are trimmed (via string.Trim), while what’s inside quotes is not trimmed at all.

Revisions

v2.10Can now handle tabs and trims strings before returning.
v2.30Rewrite.  Can now properly handle escaped quotes.  New param, ignore_mismatch.
v2.40Rewrite.  Much more stable and predictable now.  Removed ignore_mismatch param.  As far as I can tell, it now matches the source engine’s split arg behavior exactly.  Also accepts tokens to consider a string.

parseKeyValues

function ULib.parseKeyValues(str,
convert)

Parses a keyvalue formatted string into a table.

Parameters

strThe string to parse.
convert(Optional, defaults to false) Setting this to true will convert garry’s keyvalues to a better form.  This has two effects.  First, it will remove the “Out”{} wrapper.  Second, it will convert any keys that equate to a number to a number.

Returns

The table, nil and error otherwise.  If you find you’re missing information from the table, the file format might be incorrect.

Example format

test
{
   "howdy"   "bbq"

   foo
   {
       "bar"   "false"
   }

}

Revisions

v2.10Initial (but tastefully stolen from a GM9 version)
v2.30Rewrite.  Much more robust and properly unescapes backslashes now.
v2.40Properly handles escaped quotes now.

makeKeyValues

function ULib.makeKeyValues(t,
tab,
completed)

Makes a key values string from a table.

Parameters

tThe table to make the keyvalues from.  This can only contain tables, numbers, and strings.
tabOnly for internal use, this helps make inline tables look better.
completedA list of table values that have already been parsed, this is only for internal use to make sure we don’t hit an infinite loop.

Returns

The string, nil and error otherwise.

Notes

If you use numbers as keys in the table, just the values will be used.

Example table format

{ test = { howdy = "bbq", foo = { bar = "false" } } }

Example return format

test
{
   "howdy"   "bbq"

   foo
   {
       "bar"   "false"
   }

}

Revisions

v2.10Initial (but tastefully stolen from a GM9 version)
v2.40Increased performance for insanely high table counts.

toBool

function ULib.toBool(x)

Converts a bool, nil, string, or number to a bool

Parameters

xThe string or number

Returns

The bool

Revisions

v2.10Initial.
v2.40Added ability to convert nils and bools.

findVar

function ULib.findVar(varLocation,
rootTable)

Given a string, find a var starting from the global namespace.  This will correctly parse tables.  IE, “ULib.serialize”.

Parameters

varLocationThe string location of the variable you wish to find or set (E.G., “ULib.myTable.MyVariable”).
rootTableThe optional root table to search.  Defaults to _G, the global environment.

Returns

Two values as follows...

StatusA boolean indicating whether or not it was found.
ValueThe value of the variable.

Revisions

v2.40Removed dependency on gmod functions.
v2.60Now returns two values to indicate success and value.  Added second parameter for root table and added better handling for nil values.

setVar

function ULib.setVar(varLocation,
varValue,
rootTable)

Given a string, find and set a var starting from the global namespace.  This will correctly parse tables.  IE, “ULib.serialize”.

Parameters

varLocationThe string location of the variable you wish to find or set (E.G., “ULib.myTable.MyVariable”).
varValueThe value to set it to.
rootTableThe optional root table to search.  Defaults to _G, the global environment.

Returns

Two values as follows...

StatusA boolean indicating whether or not it was found and set.
ValueThe PREVIOUS value of the variable.

Revisions

v2.60Initial.

throwBadArg

function ULib.throwBadArg(argnum,
fnName,
expected,
data,
throwLevel)

Throws an error similar to the lua “bad argument #x to <fn_name> (<type> expected, got <type>).

Parameters

argnum(Optional) The argument number that was bad.
fnName(Optional) The name of the function being called.
expected(Optional) The string of the type you expected.
data(Optional) The actual data you got.
throwLevel(Optional, defaults to 3) How many levels up to throw the error.

Returns

Never returns, throws an error

Revisions

v2.40Initial.

checkArg

function ULib.checkArg(argnum,
fnName,
expected,
data,
throwLevel)

Checks to see if an arg matches what is expected, if not, calls throwBadArg().

Parameters

argnum(Optional) The argument number you’re.
fnName(Optional) The name of the function being called.
expectedThe string of the type you expect or a table of types you expect.
dataThe actual data you got.
throwLevel(Optional, defaults to 4) How many levels up to throw the error.

Returns

Never returns if the data is bad, throws an error.  Otherwise returns nil.

Revisions

v2.40Initial.

isValidSteamID

function ULib.isValidSteamID(steamid)

Checks to see if a given string is a valid steamid.

Parameters

steamidThe string of the supposed steamid.

Returns

True if it’s valid, false if not.

Revisions

v2.40Initial.

isValidIP

function ULib.isValidIP(ip)

Checks to see if a given string is a valid IPv4 address.

Parameters

ipThe string of the supposed ip.

Returns

True if it’s valid, false if not.

Revisions

v2.40Initial.

removeCommentHeader

function ULib.removeCommentHeader(data,
comment_char)

Removes a comment header.

Parameters

dataThe string to remove the comment from.
comment_charThe comment char.

Returns

Data without the comment header.

Revisions

v2.40Initial.

stringTimeToMinutes

function ULib.stringTimeToMinutes(str)

Converts a string containing time information to minutes.

Parameters

strThe time string.  Defaults to minutes, “h” is for hours, “d” is for days, “w” is for weeks.

Returns

The number of minutes represented by the string or nil if it’s unable to parse the string.

Revisions

v2.41Initial
v2.43Added year parameter
v2.60Renamed function from “stringTimeToSeconds” to “stringTimeToMinutes”, because I am dumb

secondsToStringTime

function ULib.secondsToStringTime(secs)

Converts a number of seconds to a string describing the time span.  Note that it rounds up to the minute level (ten seconds will be one minute).

Parameters

secsThe number of seconds.

Returns

A string representing the length of the span.

Revisions

v2.60Initial

Inheritance

Summary
Functions
inheritsFromCreates a psudeo-inheritance for lua.
Tables
root_classThis is a local table that holds our functions that we want all classes to have.
Functions
root_class:callThis is a utility function used by the metatable __call to resolve Class( ...
root_class:createThis is used to create new ‘class instances’.

Functions

inheritsFrom

function inheritsFrom(base_class)

Creates a psudeo-inheritance for lua.  It will search for variables that do not exist in derived ‘classes’ in the parent ‘classes’, among other things explained below.

Parameters

baseClassThe class to derive from.  This value must either be nil or a class created using inheritsFrom().

Returns

The table of the derived class.

Revisions

v2.40Initial.

Notes

  • Adapted with improvements from a lua-users inheritance tutorial http://lua-users.org/wiki/InheritanceTutorial.
  • Create using Class:create( ...  ) or Class( ...  ) (equivalent).
  • Whatever’s passed in the ‘...’, above, is passed to derived_class:instantiate().  This allows for a ‘constructor’.

See Also

Example

b = inherits_from( nil )
function b:instantiate( ... )
   print( "base", unpack( arg ) )
end

d = inherits_from( b )
function d:instantiate( ... )
   print( "derived", unpack( arg ) )
end

b1 = b( "should be base" )
d1 = d( "should be derived" )
print( "d1 is d?", d1:isa( d ), "is b?", d1:isa( b ) )
print( "b1 is d?", b1:isa( d ), "is b?", b1:isa( b ) )

Output

base    should be base
derived should be derived
d1 is d?        true    is b?   true
b1 is d?        false   is b?   true

Tables

root_class

This is a local table that holds our functions that we want all classes to have.

Functions

root_class:call

This is a utility function used by the metatable __call to resolve Class( ...  ) to Class:create( ...  ).

Parameters

parent_tableThe table of the caller.
...Extra construction parameters, passed to Class:instantiate.

Returns

The ‘class instance’.

Revisions

v2.40Initial.

root_class:create

function root_class:create(...)

This is used to create new ‘class instances’.

Parameters

...Extra construction parameters, passed to Class:instantiate.

Revisions

v2.40Initial.
function ULib.explode(separator,
str,
limit)
Split a string by a separator.
function ULib.stripComments(str,
comment,
blockcommentbeg,
blockcommentend)
Strips comments from a string
function ULib.makePatternSafe(str)
Makes a string safe for pattern usage, like in string.gsub().
function ULib.stripQuotes(s)
Trims leading and tailing quotes from a string
function ULib.unescapeBackslash(s)
Converts ‘\\’ to ‘\’
function ULib.splitPort(ipAndPort)
function ULib.splitArgs(args,
start_token,
end_token)
This is similar to string.Explode( “ “, str ) except that it will also obey quotation marks.
function ULib.parseKeyValues(str,
convert)
Parses a keyvalue formatted string into a table.
function ULib.makeKeyValues(t,
tab,
completed)
Makes a key values string from a table.
function ULib.toBool(x)
Converts a bool, nil, string, or number to a bool
function ULib.findVar(varLocation,
rootTable)
Given a string, find a var starting from the global namespace.
function ULib.setVar(varLocation,
varValue,
rootTable)
Given a string, find and set a var starting from the global namespace.
function ULib.throwBadArg(argnum,
fnName,
expected,
data,
throwLevel)
Throws an error similar to the lua “bad argument #x to fn_name (type expected, got type).
function ULib.checkArg(argnum,
fnName,
expected,
data,
throwLevel)
Checks to see if an arg matches what is expected, if not, calls throwBadArg().
function ULib.isValidSteamID(steamid)
Checks to see if a given string is a valid steamid.
function ULib.isValidIP(ip)
Checks to see if a given string is a valid IPv4 address.
function ULib.removeCommentHeader(data,
comment_char)
Removes a comment header.
function ULib.stringTimeToMinutes(str)
Converts a string containing time information to minutes.
function ULib.secondsToStringTime(secs)
Converts a number of seconds to a string describing the time span.
function inheritsFrom(base_class)
Creates a psudeo-inheritance for lua.
function root_class:create(...)
This is used to create new ‘class instances’.
This is a local table that holds our functions that we want all classes to have.
Close