String addon

From SolarStrike wiki
Jump to: navigation, search

string.alternate

string string.alternate(...)

This function will cycle through each value passed to it and return the values in order. That is, the first time this function is called, it will return the first value while the second time it is called it will return the second value and so on. This mainly is only useful in loops.

You should call this function with no parameters to reset the internal counter.

Example

for i =1,10 do
  print( string.alternate("apple", "banana", "pineapple") );
end
string.alternate(); -- Reset it
-- This should print:
-- apple
-- banana
-- pineapple
-- apple
-- banana
-- pineapple
-- apple
-- banana
-- pineapple
-- apple


string.reduceMultiples

string string.reduceMultiples(str, token)

Reduces multiple concurrent instances of 'token' with only one instance. This can be used, for example, to strip unnecessary slashes from filenames.

Example

local str = "one/two//three///";
local str2 = string.reduceMultiples(str, "/");
-- str2 is now "one/two/three/";


string.fixSlashes

string string.fixSlashes(str) string string.fixSlashes(str, posix

Converts the slashes to backslashes or vice-versa. If 'posix' is true (the default), backslashes are converted to slashes, otherwise, slashes are converted to backslashes.

Example

local fullpath = "C:/Test/test.txt";
local fullpath_fixed = string.fixSlashes(fullpath, false);
-- fullpath_fixed is now: C:\Test\test.txt

string.fixPath

string string.fixPath(path, posix)

Works like string.fixSlashes, except that it will also remove unnecessary garbage from file paths such as './' and '../'.

Example

local fullpath = "C:/Test/./folder/../test.txt";
local fullpath_fixed = string.fixPath(fullpath, true);
-- fullpath_fixed is now: C:/Test/test.txt


string.trim

string string.trim(str)

Removes additional whitespace that is leading or trailing actual content.

Example

local str = "  this is a test\t";
local str_trimmed = string.trim(str);
-- str_trimmed is now: "this is a test";


string.randomhash

string string.randomhash(len, _type)

Creates a randomized hash of length 'len' with a specific type. By default, the length is 32 and type is "alnum".

Accepted types are:

alnum Alpha-numeric, upper and lowercase
letters Letters only, upper and lowercase
numeric Numbers only
nozero Numbers, no zero
special Alpa-numeric plus special characters

Additionally, _type can be a table containing the characters you want to create a hash from.

Example

local hash = string.randomhash(); -- 32-character alpha-numeric hash
local hash2 = string.randomhash(16, "numeric"); -- 16-character numeric hash
local hash3 = string.randomhash(16, {"A", "B", "C"}); -- 16-character hash of As, Bs, and Cs.