File String.lua

Functions

String:appendWithSep (s1, sep, s2) Append one string to another with a separator in between, but only if the first string is not empty.
String:breakdownPath (path) Break down a path into an array of components.
String:checkIndices (start, stop) Determine whether start & stop indices, when applied to substring, have a chance of yielding a non-empty string.
String:child (s1, sep, s2) returns path with s2 as child of s1 - assures only 1 separator between them, whether s1 ends with a sep, or s2 begins with one.
String:compare (s1, s2) Compare two strings.
String:compareAll (s1, s2, count) Compare two strings in their entirety (or until one string runs out of characters).
String:consolidate (s, char, charCount) Remove redundent adjacent characters.
String:fmtx (s, ...) Format a string, ampersands are expected to be in && win-compatible format (if plugin runs on Windows too), but will be converted to mac compatible format on mac.
String:format (s, ...) Format a string using LOC formatter but without localization.
String:formatAmp (s, ...) Same as format plain except converts ampersands for mac compatibility.
String:formatAmps (s, ...) Same as format plain except converts ampersands for windows compatibility.
String:getAscii (binStr) Strip non-ascii characters from binary string.
String:getBaseName (fp) Get filename sans extension from path.
String:getChar (s, index) Convenience function for getting the n-th character of a string.
String:getDiff (s1, s2) Get the difference between two strings.
String:getDriveAndSubPath (path) Get root drive of specified path.
String:getFirstChar (s) Convenience function for getting the first character of a string.
String:getLastChar (s) Convenience function for getting the last character of a string.
String:getLastIndexOf (s, t, regexFlag) Return last index in source string, of target string.
String:getNonNegativeNumber (s) Extract a number from the front of a string.
String:getRoot (path) Get root drive of specified path.
String:getString (a, nameToThrow) Get 'a' as string if string else nil.
String:includedAndNotExcluded (t, incl, excl) Determine whether target string matches include/exclude criteria.
String:initPlurals () Initializes dictionaries for singular/plural support.
String:is (s, name) Determine if a string value is non-nil or empty.
String:isAllLowerCaseAlphaNum (s) Is all lower case.
String:isAllUpperCaseAlphaNum (s) Is all upper case.
String:isBeginningWith (s, t) Determine if one string begins with another - NOTE: plain text (always).
String:isCharLower (c) High performance tester for lower case char
String:isEndingWith (s, t) Determine if one string ends with another.
String:isEqual (s1, s2, ignoreCase) Determine if two strings are equal - case-sensitive by default.
String:isEqualIgnoringCase (s1, s2) Determine if two strings are equal other than case differences.
String:isFuzzyMatch (s1, s2, lenThreshold) "Fuzzy" logic for matching strings.
String:isLower (s) General purpose tester for lower case string.
String:isPlural (word) Determine if a word is singular or plural.
String:isStartingWith (s, t, ...) Determine if one string starts with another - BEWARE: regex by default.
String:isString (s) Determine if a value is nil, or if string whether its empty.
String:limit (s, n) Return lenth-limited version of s
String:lines (s, delim) Returns iterator over lines in a string.
String:loc (i18nKey, s, ...) Example: str:loc( "My/Thing", "In English, we say...^1", myvar ) In my opinion, this is just more readable than the LOC syntax.
String:makeFilenameCompliant (s) Return string that complies with filename requirements.
String:makeLuaVariableNameCompliant (s) Return string that complies with Lr preference key requirements.
String:makePathFromComponents (comps) Make path from component array.
String:makePlural (word) Makes a word presumed to be singular into its plural form.
String:makeSingular (word, exception) Make a plural form singular.
String:makeSpace (howMany) Makes a string of spaces - used for indentation and output formatting...
String:nItems (count, pluralPhrase, exception, plural, useWordForSingular) Return string with number of items in proper grammar.
String:new (t) Constructor for new instance.
String:newClass (t) Constructor for extending class.
String:padLeft (s, chr, wid) Synopsis: Pads a string on the left with specified character up to width.
String:padRight (s, chr, wid) Pads a string on the left with specified character up to width.
String:pathToPropForPluginKey (path) Convert path to key that can be used for "property for plugin" key: photo or catalog.
String:plural (count, singular, useNumberForSingular) Return singular or plural count of something.
String:replaceBackSlashesWithForwardSlashes (_path) Convert windows backslash format to mac/unix/ftp forward-slash notation.
String:searchAndReplace (s, search, replace, padChar, max) Global substitution of plain text.
String:split (s, delim, maxItems, regex) Split a string based on delimiter.
String:splitEscape (s, delim, prepFunc) Split at delimiter, but interpret consecutive delimiters as escaped data, and unescape it.
String:squeeze (s) Remove spaces from middle of a string (as well as ends).
String:squeezePath (_path, _width) Squeezes a path to fit into fixed width display field.
String:squeezeToFit (_str, _width) Squeezes a string to fit into fixed width display field.
String:to (var) Return string suitable primarily for short (synopsis-style) debug output and/or display when precise format is not critical.
String:tokenize (s, nTokensMax) Breaks a string into tokens by getting rid of the whitespace between them.
String:trimLeft (s) Trim whitespace from front (left) of string.


Functions

String:appendWithSep (s1, sep, s2)
Append one string to another with a separator in between, but only if the first string is not empty.

Parameters:

  • s1:
  • sep:
  • s2:
String:breakdownPath (path)
Break down a path into an array of components.

Parameters:

  • path:

Usage:

    Does not distinguish absolute from relative paths. 

Return value:

    array (1st component is root), usually not empty, never nil.
String:checkIndices (start, stop)
Determine whether start & stop indices, when applied to substring, have a chance of yielding a non-empty string.

Parameters:

  • start:
  • stop:

Usage:

    Note: checking is independent of string len. If len is to be considered, it must be done in calling context. 

Return value:

    0 iff yes. (-1 means both are negative and no-go, +1 means both are positive and no-go).
String:child (s1, sep, s2)
returns path with s2 as child of s1 - assures only 1 separator between them, whether s1 ends with a sep, or s2 begins with one.

Parameters:

  • s1: required
  • sep: required
  • s2: required

Usage:

    all 3 params are required, and sep is the middle one.. 
String:compare (s1, s2)
Compare two strings.

Parameters:

  • s1:
  • s2:

Usage:

    Returns immediately upon first difference. 

Return value:

    0 if same, else difference position.
String:compareAll (s1, s2, count)
Compare two strings in their entirety (or until one string runs out of characters).

Parameters:

  • s1:
  • s2:
  • count:

Usage:

  • Use when it is desired to know the character positions of all the differences.
  • Most appropriate when the files are same length, or at least start off the same, since there is no attempt to resynchronize... 

Return value:

    nil if same, else array of difference indexes.
String:consolidate (s, char, charCount)
Remove redundent adjacent characters.

Parameters:

  • s:
  • char:
  • charCount:

Usage:

    Initial motivation was to format value returned by table.concat( items, " " ) when some items may be empty strings. 

Return value:

    Consolidated string.
String:fmtx (s, ...)
Format a string, ampersands are expected to be in && win-compatible format (if plugin runs on Windows too), but will be converted to mac compatible format on mac.

Parameters:

  • s: format string in LOC format.
  • ...: substution variables - any format: nil OK.

Usage:

  • x in the name stands for cross-platform.
  • Will never throw an error, unless format string is not string type - don't use for critical program strings, just logging and UI display, when it's better to have a small aesthetic bug than a catastrophic error.
  • LOC will throw error when passed a boolean, string.format will throw an error when insufficient substitutions or incompatible data type. 
String:format (s, ...)
Format a string using LOC formatter but without localization.

Parameters:

  • s:
  • ...:

Usage:

    An alternative to lua string.format function (which uses ansi 'C' printf syntax). 
String:formatAmp (s, ...)
Same as format plain except converts ampersands for mac compatibility.

Parameters:

  • s:
  • ...:
String:formatAmps (s, ...)
Same as format plain except converts ampersands for windows compatibility.

Parameters:

  • s:
  • ...:
String:getAscii (binStr)
Strip non-ascii characters from binary string.

Parameters:

  • binStr:

Usage:

    Good for searching for text in binary files, otherwise string searcher stops upon first zero byte.
    could probably just strip zeros, but this gives a printable string that can be logged for debug...
String:getBaseName (fp)
Get filename sans extension from path.

Parameters:

  • fp:

Usage:

    *** this failed when I tried these ops in reverse, i.e. removing extension of leaf-name not sure why. Hmmm... 
String:getChar (s, index)
Convenience function for getting the n-th character of a string.

Parameters:

  • s: The string.
  • index: First char is index 1.

Usage:

    @2010-11-23: *** Will throw error if index is out of bounds, so check before calling if unsure. 

Return value:

    character in string.
String:getDiff (s1, s2)
Get the difference between two strings.

Parameters:

  • s1:
  • s2:

Usage:

    Use to see the difference between two strings. 

Return values:

  1. diff-len
  2. s1-remainder
  3. s2-remainder
String:getDriveAndSubPath (path)
Get root drive of specified path.

Parameters:

  • path:
String:getFirstChar (s)
Convenience function for getting the first character of a string.

Parameters:

  • s:

Usage:

    throws error if string does not have a first character, so check before calling if necessary. 
String:getLastChar (s)
Convenience function for getting the last character of a string.

Parameters:

  • s:

Usage:

    throws error if string does not have a last character, so check before calling if necessary. 
String:getLastIndexOf (s, t, regexFlag)
Return last index in source string, of target string.

Parameters:

  • s:
  • t:
  • regexFlag:

Return values:

  1. startIndex or 0 if not found - never returns nil.
  2. stopIndex or 0 if not found - never returns nil.
String:getNonNegativeNumber (s)
Extract a number from the front of a string.

Initial application for ordering strings that start with a number.

Parameters:

  • s:

Usage:

    *** Warning: Does NOT check incoming string or parse position. 

Return value:

    Next parse position.
String:getRoot (path)
Get root drive of specified path.

Parameters:

  • path: (string, required) absolute path to folder or file.
String:getString (a, nameToThrow)
Get 'a' as string if string else nil.

Parameters:

  • a:
  • nameToThrow:
String:includedAndNotExcluded (t, incl, excl)
Determine whether target string matches include/exclude criteria.

Parameters:

  • t: string required.
  • incl: (optional) - include criteria (substr (required), start, stop, regex) - or array of same.
  • excl: (optional) - exclude criteria (substr (required), start, stop, regex) - or array of same.

Return value:

    true iff target string should be included and not excluded according to specified criteria.
String:initPlurals ()
Initializes dictionaries for singular/plural support.

May never be called if plugin does not call at least one plural function.

Usage:

    Could be called in plugin-init, or in string constructor - but isn't. - will be called on first demand. 
String:is (s, name)
Determine if a string value is non-nil or empty.

Convenience function to avoid checking both aspects, or getting a "expected string, got nil" error.

Parameters:

  • s:
  • name:

Usage:

  • If value type is not known to be string if not nil, then use 'is-string' instead.
  • Throws error if type is not string or nil. 

Return value:

    true iff non-empty string.
String:isAllLowerCaseAlphaNum (s)
Is all lower case.

Parameters:

  • s:
String:isAllUpperCaseAlphaNum (s)
Is all upper case.

Parameters:

  • s:
String:isBeginningWith (s, t)
Determine if one string begins with another - NOTE: plain text (always).

Does not use 'find'.

Parameters:

  • s:
  • t:

Usage:

  • Does not check incoming strings.
  • Does not ignore whitespace. 

Return value:

    true iff s begins with t.
String:isCharLower (c)
High performance tester for lower case char

Parameters:

  • c:
String:isEndingWith (s, t)
Determine if one string ends with another.

Avoids the problem of using the nil returned by string.find in a context that does not like it.

Parameters:

  • s:
  • t:

Usage:

  • Does not check incoming strings.
  • Does not ignore whitespace. 

Return value:

    true iff s begins with t in character position 1.
String:isEqual (s1, s2, ignoreCase)
Determine if two strings are equal - case-sensitive by default.

Parameters:

  • s1:
  • s2:
  • ignoreCase:
String:isEqualIgnoringCase (s1, s2)
Determine if two strings are equal other than case differences.

Parameters:

  • s1:
  • s2:
String:isFuzzyMatch (s1, s2, lenThreshold)
"Fuzzy" logic for matching strings.

Parameters:

  • s1: string one (required).
  • s2: string two (required).
  • lenThreshold: (default=5) strings must be at least this long or substring match not considered. [[ *** on hold

Usage:

  • Matches exact strings (case insensitive), but also matches one being a substring of the other, if length greater or equal to len-threshold.
  • Good for matching things like camera model, where D300 or Nikon D300 is close enough to NIKON D300. 
String:isLower (s)
General purpose tester for lower case string.

Parameters:

  • s:
String:isPlural (word)
Determine if a word is singular or plural.

Note: It is possible for some plurals to escape detection. Not to be used when ascertainment is critical - intention is more for aesthetics...

Parameters:

  • word:

Usage:

    trim beforehand if necessary. 

Return value:

    true iff word is plural.
String:isStartingWith (s, t, ...)
Determine if one string starts with another - BEWARE: regex by default.

Avoids the problem of using the nil returned by string.find in a context that does not like it.

Parameters:

  • s:
  • t:
  • ...:

Usage:

  • Does not check incoming strings.
  • Does not ignore whitespace.
  • If string is not expected to be there at the start, and the source string is very long, it will be more efficient to pass a substring instead, for example:
    local isThere = str:isStartingWith( longstr:sub( 1, t:len() ), t )
  • you must also pass parameters "1, true" for plain text (index must be one, followed by boolean true). 

Return value:

    true iff s begins with t in character position 1.
String:isString (s)
Determine if a value is nil, or if string whether its empty.

Avoids checking aspects individually, or getting a "expected string, got nil or boolean" error.

Parameters:

  • s:

Usage:

    Also weathers the case when s is a table (or number?) 
String:limit (s, n)
Return lenth-limited version of s

Parameters:

  • s:
  • n:
String:lines (s, delim)
Returns iterator over lines in a string.

For those times when you already have a file's contents as a string and you want to iterate its lines. This essential does the same thing as Lua's io.lines function.

Parameters:

  • s:
  • delim:

Usage:

  • Handles \n or \r\n dynamically as EOL sequence.
  • Does not handle Mac legacy (\r alone) EOL sequence.
  • Works as well on binary as text file - no need to read as text file unless the lines must be zero-byte free. 
String:loc (i18nKey, s, ...)
Example: str:loc( "My/Thing", "In English, we say...^1", myvar ) In my opinion, this is just more readable than the LOC syntax.

Parameters:

  • i18nKey:
  • s:
  • ...:
String:makeFilenameCompliant (s)
Return string that complies with filename requirements.

Parameters:

  • s:
String:makeLuaVariableNameCompliant (s)
Return string that complies with Lr preference key requirements.

Parameters:

  • s:

Usage:

  • initial motivation is for lr pref key.
  • reminder: photo metadata properties can not begin with an underscore, dunno 'bout catalog properties for plugin. prefs are OK with leading underscore.  
String:makePathFromComponents (comps)
Make path from component array.

Parameters:

  • comps: The array of path components: 1st element is root, last element is child.
String:makePlural (word)
Makes a word presumed to be singular into its plural form.

Parameters:

  • word:

Usage:

    Call is-plural and trim beforehand if necessary. 
String:makeSingular (word, exception)
Make a plural form singular.

Parameters:

  • word:
  • exception:

Usage:

    If unsure whether already singular, call is-plural before-hand, and trim if necessary. 
String:makeSpace (howMany)
Makes a string of spaces - used for indentation and output formatting...

Parameters:

  • howMany:

Usage:

    *** Deprecated - use Lua's string-rep function instead. 
String:nItems (count, pluralPhrase, exception, plural, useWordForSingular)
Return string with number of items in proper grammar.

Parameters:

  • count: number of items
  • pluralPhrase:
  • exception:
  • plural: correct grammer for items if 0 or >1 item.
  • useWordForSingular: pass true iff One or one is to be displayed when 1 item. Case is adaptive.

Usage:

    not so sure this was a good idea. Seems making plural is more often correct than making singular. ###2 
String:new (t)
Constructor for new instance.

Parameters:

  • t:
String:newClass (t)
Constructor for extending class.

Parameters:

  • t:
String:padLeft (s, chr, wid)
Synopsis: Pads a string on the left with specified character up to width. Motivation: Typically used with spaces for tabular display, or 0s when string represents a number.

Parameters:

  • s:
  • chr:
  • wid:
String:padRight (s, chr, wid)
Pads a string on the left with specified character up to width.

Parameters:

  • s:
  • chr:
  • wid:

Usage:

  • Typically used with spaces for tabular display, or 0s when string represents a number.
  • only works right if fixed-width font. 
String:pathToPropForPluginKey (path)
Convert path to key that can be used for "property for plugin" key: photo or catalog.

Parameters:

  • path:
String:plural (count, singular, useNumberForSingular)
Return singular or plural count of something.

Could be enhanced to force case of singular explicitly, instead of just adaptive.

Parameters:

  • count: Actual number of things.
  • singular: The singular form to be used if count is 1.
  • useNumberForSingular: may be boolean or string
    boolean true => use numeric form of singular for better aesthetics.
    string 'u' or 'upper' => use upper case of singular (first char only).
    string 'l' or 'lower' => use lower case of singular (first char only).
    default is adaptive case.

Usage:

  • Example: str:format( "^1 rendered.", str:plural( nRendered, "photo" ) ) - "one photo" or "2 photos"
  • Case is adaptive when word form of singular is used. For example: str:plural( nRendered, "Photo" ) - yields "One Photo". 
String:replaceBackSlashesWithForwardSlashes (_path)
Convert windows backslash format to mac/unix/ftp forward-slash notation.

Parameters:

  • _path:

Usage:

  • Prefer lr-path-utils - standardize-path to assure path to disk file is in proper format for localhost.
  • This function is primarily used for converting windows sub-paths for use in FTP. 
    Lightroom is pretty good about allowing mixtures of forward and backward slashes in ftp functions,
    but still - I find it more pleasing to handle explicitly.
String:searchAndReplace (s, search, replace, padChar, max)
Global substitution of plain text.

Parameters:

  • s:
  • search:
  • replace:
  • padChar:
  • max:
String:split (s, delim, maxItems, regex)
Split a string based on delimiter.

Parameters:

  • s: (string, required) The string to be split.
  • delim: (string, required) The delimiter string (plain text). Often something like ','.
  • maxItems: (number, optional) if passed, final element will contain entire remainder of string. Often is 2, to get first element then remainder.
  • regex:

Usage:

  • Seems like there should be a lua or lr function to do this, but I haven't seen it.
  • Components may be empty strings - if repeating delimiters exist. 

Return value:

    Array of trimmed components - never nil nor empty table unless input is nil or empty string, respectively.
String:splitEscape (s, delim, prepFunc)
Split at delimiter, but interpret consecutive delimiters as escaped data, and unescape it.

Parameters:

  • s:
  • delim:
  • prepFunc:

Usage:

    does not support max components, but does allow custom preparation function - defaulting to whitespace trimmer. 
String:squeeze (s)
Remove spaces from middle of a string (as well as ends).

Parameters:

  • s:

Usage:

    Convenience function to make more readable than testing for nil followed by gsub. 

Return value:

    Squeezed string, nil -> empty.
String:squeezePath (_path, _width)
Squeezes a path to fit into fixed width display field.

One could argue for another parameter that selects a balance between first part of path, and second part of path
i.e. balance = 0 => select first part only, balance = 1 => prefer trailing path, .5 => split equally between first and last part of path.

Although its conceivable that some pathing may be preferred over long filename, that solution is waiting for a problem...

Parameters:

  • _path:
  • _width:

Usage:

  • Guaranteed to get entire filename, and as much of first part of path as possible.
  • Lightroom does something similar for progress caption, but algorithm is different. 

Return value:

    first-part-of-path.../filename.
String:squeezeToFit (_str, _width)
Squeezes a string to fit into fixed width display field.

Parameters:

  • _str:
  • _width:

Return value:

    first half ... last half
String:to (var)
Return string suitable primarily for short (synopsis-style) debug output and/or display when precise format is not critical. Feel free to pass a nil value and let 'nil' be returned. If object has an explicit to-string method, then it will be called, otherwise the lua global function. Use dump methods for objects and/or log-table..., if more verbose output is desired.

Parameters:

  • var:
String:tokenize (s, nTokensMax)
Breaks a string into tokens by getting rid of the whitespace between them.

Parameters:

  • s: - string to tokenize.
  • nTokensMax: - remainder of string returned as single token once this many tokens found in the first part of the string.

Usage:

    Does similar thing as "split", except delimiter is any whitespace, not just true spaces. 
String:trimLeft (s)
Trim whitespace from front (left) of string.

Parameters:

  • s:

Usage:

    Reminder: Lr's trimmer is not binary compatible, this method is. 

Valid XHTML 1.0!