stdlib 41.2.3 Reference

# Module `std.string`

Additions to the core string module.

The module table returned by `std.string` also contains all of the entries from the core string table. An hygienic way to import this module, then, is simply to override the core `string` locally:

local string = require "std.string"

## Functions

caps (s) | Capitalise each word in a string.
chomp (s) | Remove any final newline from a string.
escape_pattern (s) | Escape a string to be used as a pattern.
escape_shell (s) | Escape a string to be used as a shell token.
finds (s, pattern[, init=1[, plain]]) | Repeatedly `string.find` until target string is exhausted.
format (f[, ...]) | Extend to work better with one argument.
ltrim (s[, r="%s+"]) | Remove leading matter from a string.
monkey_patch ([namespace=_G]) | Overwrite core `string` methods with `std` enhanced versions.
numbertosi (n) | Write a number using SI suffixes.
ordinal_suffix (n) | Return the English suffix for an ordinal.
pad (s, w[, p=" "]) | Justify a string.
prettytostring (x[, indent="\t"[, spacing=""]]) | Pretty-print a table, or other object.
render (x, open, close, elem, pair, sep[, roots]) | Turn tables into strings with recursion detection.
rtrim (s[, r="%s+"]) | Remove trailing matter from a string.
split (s[, sep="%s+"]) | Split a string at a given separator.
tfind (s, pattern[, init=1[, plain]]) | Do `string.find`, returning a table of captures.
trim (s[, r="%s+"]) | Remove leading and trailing matter from a string.
wrap (s[, w=78[, ind=0[, ind1=ind]]]) | Wrap a string into a paragraph.

## Fields

__concat | String concatenation operation.
__index | String subscript operation.
pickle | Convert a value to a string.

## Types

closetablecb (t) | Signature of render close table callback.
elementcb (x) | Signature of render element callback.
opentablecb (t) | Signature of render open table callback.
paircb (t, key, value, keystr, valuestr) | Signature of render pair callback.
separatorcb (t, pk, pv, fk, fv) | Signature of render separator callback.

## Functions

Methods

caps (s)
  Capitalise each word in a string.

  ### Parameters:

  - s string any string

  ### Returns:

  string *s* with each word capitalized

  ### Usage:

      userfullname = caps (input_string)

chomp (s)
  Remove any final newline from a string.

  ### Parameters:

  - s string any string

  ### Returns:

  string *s* with any single trailing newline removed

  ### Usage:

      line = chomp (line)

escape_pattern (s)
  Escape a string to be used as a pattern.

  ### Parameters:

  - s string any string

  ### Returns:

  string *s* with active pattern characters escaped

  ### Usage:

      substr = inputstr:match (escape_pattern (literal))

escape_shell (s)
  Escape a string to be used as a shell token. Quotes spaces, parentheses, brackets, quotes, apostrophes and whitespace.

  ### Parameters:

  - s string any string

  ### Returns:

  string *s* with active shell characters escaped

  ### Usage:

      os.execute ("echo " .. escape_shell (outputstr))

finds (s, pattern[, init=1[, plain]])
  Repeatedly `string.find` until target string is exhausted.

  ### Parameters:

  - s string target string
  - pattern string pattern to match in *s*
  - init string start position (default 1)
  - plain string inhibit magic characters (optional)

  ### Returns:

  list of `{from, to; capt = {captures}}`

  ### See also:

  std.string.tfind

  ### Usage:

      for t in std.elems (finds ("the target string", "%S+")) do
        print (tostring (t.capt))
      end

format (f[, ...])
  Extend to work better with one argument. If only one argument is passed, no formatting is attempted.

  ### Parameters:

  - f string format string
  - ... arguments to format (optional)

  ### Returns:

  formatted string

  ### Usage:

      print (format "100% stdlib!")

ltrim (s[, r="%s+"])
  Remove leading matter from a string.

  ### Parameters:

  - s string any string
  - r string leading pattern (default "%s+")

  ### Returns:

  string *s* with leading *r* stripped

  ### Usage:

      print ("got: " .. ltrim (userinput))

monkey_patch ([namespace=_G])
  Overwrite core `string` methods with `std` enhanced versions.

  Also adds auto-stringification to `..` operator on core strings, and integer indexing of strings with `[]` dereferencing.

  ### Parameters:

  - namespace table where to install global functions (default _G)

  ### Returns:

  table the module table

  ### Usage:

      local string = require "std.string".monkey_patch ()

numbertosi (n)
  Write a number using SI suffixes. The number is always written to 3 s.f.

  ### Parameters:

  - n table or string any numeric value

  ### Returns:

  string *n* simplifed using largest available SI suffix.

  ### Usage:

      print (numbertosi (bitspersecond) .. "bps")

ordinal_suffix (n)
  Return the English suffix for an ordinal.

  ### Parameters:

  - n string or string any integer value

  ### Returns:

  string English suffix for *n*

  ### Usage:

      local now = os.date "*t"
      print ("%d%s day of the week", now.day, ordinal_suffix (now.day))

pad (s, w[, p=" "])
  Justify a string. When the string is longer than w, it is truncated (left or right according to the sign of w).

  ### Parameters:

  - s string a string to justify
  - w string width to justify to (-ve means right-justify; +ve means left-justify)
  - p string string to pad with (default " ")

  ### Returns:

  string *s* justified to *w* characters wide

  ### Usage:

      print (pad (trim (outputstr, 78)) .. "\n")

prettytostring (x[, indent="\t"[, spacing=""]])
  Pretty-print a table, or other object.

  ### Parameters:

  - x object to convert to string
  - indent string indent between levels (default "\t")
  - spacing string space before every line (default "")

  ### Returns:

  string pretty string rendering of *x*

  ### Usage:

      print (prettytostring (std, "  "))

render (x, open, close, elem, pair, sep[, roots])
  Turn tables into strings with recursion detection. N.B. Functions calling render should not recurse, or recursion detection will not work.

  ### Parameters:

  - x object to convert to string
  - open opentablecb open table rendering function
  - close closetablecb close table rendering function
  - elem elementcb element rendering function
  - pair paircb pair rendering function
  - sep separatorcb separator rendering function
  - roots table accumulates table references to detect recursion (optional)

  ### Returns:

  string representation of *x*

  ### Usage:

      function tostring (x)
        return render (x, lambda '="{"', lambda '="}"', tostring,
                       lambda '=_4.."=".._5', lambda '= _4 and "," or ""',
                       lambda '=","')
      end

rtrim (s[, r="%s+"])
  Remove trailing matter from a string.

  ### Parameters:

  - s string any string
  - r string trailing pattern (default "%s+")

  ### Returns:

  string *s* with trailing *r* stripped

  ### Usage:

      print ("got: " .. rtrim (userinput))

split (s[, sep="%s+"])
  Split a string at a given separator. Separator is a Lua pattern, so you have to escape active characters, `^$()%.[]*+-?` with a `%` prefix to match a literal character in *s*.

  ### Parameters:

  - s string to split
  - sep string separator pattern (default "%s+")

  ### Returns:

  list of strings

  ### Usage:

      words = split "a very short sentence"

tfind (s, pattern[, init=1[, plain]])
  Do `string.find`, returning a table of captures.

  ### Parameters:

  - s string target string
  - pattern string pattern to match in *s*
  - init string start position (default 1)
  - plain string inhibit magic characters (optional)

  ### Returns:

  1. string start of match
  2. string end of match
  3. table list of captured strings

  ### See also:

  std.string.finds

  ### Usage:

      b, e, captures = tfind ("the target string", "%s", 10)

trim (s[, r="%s+"])
  Remove leading and trailing matter from a string.

  ### Parameters:

  - s string any string
  - r string trailing pattern (default "%s+")

  ### Returns:

  string *s* with leading and trailing *r* stripped

  ### Usage:

      print ("got: " .. trim (userinput))

wrap (s[, w=78[, ind=0[, ind1=ind]]])
  Wrap a string into a paragraph.

  ### Parameters:

  - s string a paragraph of text
  - w string width to wrap to (default 78)
  - ind string indent (default 0)
  - ind1 string indent of first line (default ind)

  ### Returns:

  string *s* wrapped to *w* columns

  ### Usage:

      print (wrap (copyright, 72, 4))

## Fields

__concat
  String concatenation operation.
  - s string initial string
  - o object to stringify and concatenate

  ### Usage:

      local string = require "std.string".monkey_patch ()
      concatenated = "foo" .. {"bar"}

__index
  String subscript operation.
  - s string string
  - i string or string index or method name

  ### Usage:

      getmetatable ("").__index = require "std.string".__index
      third = ("12345")[3]

pickle
  Convert a value to a string. The string can be passed to `functional.eval` to retrieve the value.
  - x object to pickle

  ### See also:

  std.eval

  ### Usage:

      function slow_identity (x) return functional.eval (pickle (x)) end

## Types

closetablecb (t)
  Signature of render close table callback.

  ### Parameters:

  - t table table just rendered

  ### Returns:

  string close table rendering

  ### See also:

  render

  ### Usage:

      function close (t) return "}" end

elementcb (x)
  Signature of render element callback.

  ### Parameters:

  - x element to render

  ### Returns:

  string element rendering

  ### See also:

  render

  ### Usage:

      function element (e) return require "std".tostring (e) end

opentablecb (t)
  Signature of render open table callback.

  ### Parameters:

  - t table table about to be rendered

  ### Returns:

  string open table rendering

  ### See also:

  render

  ### Usage:

      function open (t) return "{" end

paircb (t, key, value, keystr, valuestr)
  Signature of render pair callback. Trying to re-render *key* or *value* here will break recursion detection, use *strkey* and *strvalue* pre-rendered values instead.

  ### Parameters:

  - t table table containing pair being rendered
  - key key part of key being rendered
  - value value part of key being rendered
  - keystr string prerendered *key*
  - valuestr string prerendered *value*

  ### Returns:

  string pair rendering

  ### See also:

  render

  ### Usage:

      function pair (_, _, _, key, value) return key .. "=" .. value end

separatorcb (t, pk, pv, fk, fv)
  Signature of render separator callback.

  ### Parameters:

  - t table table currently being rendered
  - pk *t* key preceding separator, or `nil` for first key
  - pv *t* value preceding separator, or `nil` for first value
  - fk *t* key following separator, or `nil` for last key
  - fv *t* value following separator, or `nil` for last value

  ### Returns:

  string separator rendering

  ### Usage:

      function separator (_, _, _, fk) return fk and "," or "" end

generated by LDoc 1.5.0 Last updated 2026-07-25 13:31:42