Utilities

Table specific utilities are in the file Table Utilities.

Summary
UtilitiesTable specific utilities are in the file Table Utilities.
otlib
String Utilities
ExplodeSplit a string by a string.
TrimTrims leading and tailing whitespace from a string.
LTrimExactly like Trim except it only trims the left side.
RTrimExactly like Trim except it only trims the right side.
EscapeMakes a string safe for pattern usage, like in string.gsub().
StripCommentsStrips comments from a string.
ParseArgsThis is similar to Explode with ( str, “%s+” ) except that it will not split up words within quotation marks.
EditDistanceFinds the edit distance between two strings or tables.
SplitCommentHeaderSplits a comment header in a string.
Numeric Utilities
RoundRounds a number to a given decimal place.
Other UtilitiesThings that don’t fit in any other category.
ToBoolConverts a boolean, nil, string, or number to a boolean value.
StoredExpressionCreates an object that will store an expression.
DataEqualsAnyOfChecks to see if an argument equals any of the other arguments passed in.

otlib

Summary
String Utilities
ExplodeSplit a string by a string.
TrimTrims leading and tailing whitespace from a string.
LTrimExactly like Trim except it only trims the left side.
RTrimExactly like Trim except it only trims the right side.
EscapeMakes a string safe for pattern usage, like in string.gsub().
StripCommentsStrips comments from a string.
ParseArgsThis is similar to Explode with ( str, “%s+” ) except that it will not split up words within quotation marks.
EditDistanceFinds the edit distance between two strings or tables.
SplitCommentHeaderSplits a comment header in a string.
Numeric Utilities
RoundRounds a number to a given decimal place.
Other UtilitiesThings that don’t fit in any other category.
ToBoolConverts a boolean, nil, string, or number to a boolean value.
StoredExpressionCreates an object that will store an expression.
DataEqualsAnyOfChecks to see if an argument equals any of the other arguments passed in.

String Utilities

Explode

function Explode(str,
separator,
plain,
limit)

Split a string by a string.

Parameters

strThe input string to explode.
separatorAn optional string to specify what to split on.  Defaults to %s+.
plainAn optional boolean that turns off pattern matching facilities if true.  This should make it faster and allows you to specify strings that would otherwise need to be escaped.  Defaults to false.
limitAn optional number that if set, the returned table will contain a maximum of limit elements with the last element containing the rest of str.  Defaults to no limit.

Returns

A table containing the exploded str.

Example

Explode( "p1 p2 p3" )

returns...

{ "p1", "p2", "p3" }

Notes

  • If separator is the empty string (“”), this function throws an error.

Revisions

v1.00Initial.

Trim

function Trim(str)

Trims leading and tailing whitespace from a string.

Parameters

strThe string to trim.

Returns

The stripped string.

Notes

Revisions

v1.00Initial.

LTrim

function LTrim(str)

Exactly like Trim except it only trims the left side.  Taken from http://lua-users.org/wiki/CommonFunctions

Revisions

v1.00Initial.

RTrim

function RTrim(str)

Exactly like Trim except it only trims the right side.  Taken from http://lua-users.org/wiki/CommonFunctions

Revisions

v1.00Initial.

Escape

function Escape(str)

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

Parameters

strThe string to make pattern safe.

Returns

The pattern safe string.

StripComments

function StripComments(str,
line_comment)

Strips comments from a string.

Parameters

strThe input string to strip from.
line_commentThe string of the comment to remove from str.  Removes whenever it finds this text until the end of the line.

Returns

A string of str with the comments removed.

Example

StripComments( "Line 1 # My comment\n#Line with only a comment\nLine 2", "#" )

returns...

"Line 1 \n\nLine 2"

Notes

  • Only handles line comments, no block comments.
  • Does not parse the document, so it will remove even from inside quotation marks if it finds line_comment inside them.

Revisions

v1.00Initial.

ParseArgs

function ParseArgs(args)

This is similar to Explode with ( str, “%s+” ) except that it will not split up words within quotation marks.

Parameters

argsThe input string to split from.

Returns

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

Example

ParseArgs( '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 Trim), while what’s inside quotes is not trimmed at all.

Revisions

v1.00Initial.

EditDistance

function EditDistance(s,
t,
lim)

Finds the edit distance between two strings or tables.  Edit distance is the minimum number of edits needed to transform one string or table into the other.

Parameters

sA string or table.
tAnother string or table to compare against s.
limAn optional number to limit the function to a maximum edit distance.  If specified and the function detects that the edit distance is going to be larger than limit, limit is returned immediately.

Returns

A number specifying the minimum edits it takes to transform s into t or vice versa.  Will not return a higher number than lim, if specified.

Example

EditDistance( "Tuesday", "Teusday" ) -- One transposition.
EditDistance( "kitten", "sitting" ) -- Two substitutions and a deletion.

returns...

1
3

Notes

  • Complexity is O( (#t+1) * (#s+1) ) when lim isn’t specified.
  • This function can be used to compare array-like tables as easily as strings.
  • The algorithm used is Damerau-Levenshtein distance, which calculates edit distance based off number of subsitutions, additions, deletions, and transpositions.
  • Source code for this function is based off the Wikipedia article for the algorithm http://en.wikipedia.org/w/index.php?title=Damerau%E2%80%93Levenshtein_distance&oldid=351641537.
  • This function is case sensitive when comparing strings.
  • If this function is being used several times a second, you should be taking advantage of the lim parameter.
  • Using this function to compare against a dictionary of 250,000 words took about 0.6 seconds on my machine for the word “Teusday”, around 10 seconds for very poorly spelled words.  Both tests used lim.

Revisions

v1.00Initial.

SplitCommentHeader

function SplitCommentHeader(str,
comment_prefix)

Splits a comment header in a string.  A comment header is defined as a block in a string where every non-blank line starts with a certain prefix, until a non-blank line is reached that doesn’t start with the prefix.

Parameters

strThe string to split the comment from.
comment_prefixThe optional string comment prefix.  Defaults to _”;”_.

Returns

1The comment header.
2Everything after the comment header.

Example

SplitCommentHeader( ";Comment 1\n;Comment 2\nData 1\nData 2" )

returns...

";Comment 1\n;Comment 2", "Data 1\nData2"

Revisions

v1.00Initial.

Numeric Utilities

Round

function Round(num,
places)

Rounds a number to a given decimal place.

Parameters

numThe number to round.
placesThe optional number of places to round to.  0 rounds to the nearest whole number, 1 rounds to the nearest tenth, 2 rounds to the nearest thousandth, etc.  Negative numbers round into the non-fractional places; -1 rounds to the nearest tens, -2 rounds to the nearest hundreds, etc.  Defaults to 0.

Returns

The rounded number.

Notes

Revisions

v1.00Initial.

Other Utilities

Things that don’t fit in any other category.

ToBool

function ToBool(value)

Converts a boolean, nil, string, or number to a boolean value.

Parameters

valueThe boolean, nil, string, or number to convert.

Returns

The converted boolean value.

Notes

  • This function favors returning true if it’s not quite sure what to do.
  • 0, strings equating to 0, nil, false, “f”, “false”, “no”, and “n” will all return false.

Revisions

v1.00Initial.

StoredExpression

function StoredExpression()

Creates an object that will store an expression.

Returns

A table that can be called and accepts any number of arguments, then stores and returns the arguments as given.  You can access the arguments in the table by index, or retrieve the total number of aruments from field ‘n’.

A function ‘unpack’ is also defined for the returned table which returns each argument just like regular unpack does.

Example

ex = StoredExpression()
my_list = { "milk", "bread", "cookies", "eggs" }
if ex( HasValue( my_list, "cookies" ) ) then
   print( "cookies are item #" .. ex[ 2 ] .. " on my list" )
end
print( "there were " .. ex.n .. " variables passed back from HasValue" )

prints...

cookies are item #3 on my list
there were 2 variables passed back from HasValue

Notes

Revisions

v1.00Initial.

DataEqualsAnyOf

function DataEqualsAnyOf(data,
...)

Checks to see if an argument equals any of the other arguments passed in.

Parameters

dataThe data to test equality against.
...All the other arguments, which get tested against data in successive order until a match is found or until we run out of arguments.

Returns

A boolean stating whether or not any of the other arguments equaled the data argument.

Example

This is a conveinence function so that instead of writing this...

if a == b or a == c or a == d then ... end

You can write this...

if DataEqualsAnyOf( a, b, c, d ) then ... end

Revisions

v1.00Initial.
Utility functions that deal specifically with tables.
function Explode(str,
separator,
plain,
limit)
Split a string by a string.
function Trim(str)
Trims leading and tailing whitespace from a string.
function LTrim(str)
Exactly like Trim except it only trims the left side.
function RTrim(str)
Exactly like Trim except it only trims the right side.
function Escape(str)
Makes a string safe for pattern usage, like in string.gsub().
function StripComments(str,
line_comment)
Strips comments from a string.
function ParseArgs(args)
This is similar to Explode with ( str, “%s+” ) except that it will not split up words within quotation marks.
function EditDistance(s,
t,
lim)
Finds the edit distance between two strings or tables.
function SplitCommentHeader(str,
comment_prefix)
Splits a comment header in a string.
function Round(num,
places)
Rounds a number to a given decimal place.
function ToBool(value)
Converts a boolean, nil, string, or number to a boolean value.
function StoredExpression()
Creates an object that will store an expression.
function DataEqualsAnyOf(data,
...)
Checks to see if an argument equals any of the other arguments passed in.
Close