Quirrel4.41.0

types.String.subst

Method on every string
pure string.subst(value, ...): any

Substitutes {0}, {1}, ... and {name} placeholders in str with the given values.

The binding carries no declaration string, so the VM cannot report parameter names. The names above are from this page; the types and attributes still come from the VM. The VM also cannot tell an optional parameter from a variadic tail here, so read the brackets and any trailing ... from the prose below, not from the signature.

Parameters

valueanythe first substitution value
...anyfurther substitution values repeats

Return value

str with each {N} replaced by tostring() of the N-th value (0-based, counting from value), and each {name} replaced by tostring() of name's entry in the first table among the values that has that key. A placeholder with no matching value or key is left in the result as written, including its braces.

Errors

Throws subst: Failed to convert value to string if a substituted value's tostring() fails. Every built-in type converts successfully.

Notes

Takes 1 or more arguments: at least one value is required, even if str has no placeholders - calling it with zero explicit arguments throws a wrong-number-of-parameters error. This is a real, unbounded vararg, unlike the fake ... the VM's dump adds to several other methods on this page for unrelated reasons.

Differs from string.format: subst looks up values by position or by table key inside {}, with no %-style conversion syntax and no fixed argument count, while format walks a C printf-style pattern and requires exactly as many arguments as it has conversions.

Example

examples/types/string/subst.nut
println("\"hi {0}, you are {1}\".subst(\"bob\", 42) =", "hi {0}, you are {1}".subst("bob", 42))
println("\"{n} plus one\".subst({n = 41}) =", "{n} plus one".subst({n = 41}))

// an unmatched placeholder is left as-is.
println("\"{5}\".subst(\"x\") =", "{5}".subst("x"))

try { "hi".subst() } catch (e) println("\"hi\".subst() throws:", e)
Output:
"hi {0}, you are {1}".subst("bob", 42) = hi bob, you are 42
"{n} plus one".subst({n = 41}) = 41 plus one
"{5}".subst("x") = {5}
"hi".subst() throws: wrong number of parameters passed to native closure 'subst' (1 passed, at least 2 required)

See also

formatFormats fmt with the following arguments, following the syntax of the C printf family, and returns the result as a new string.
replaceReturns str with every occurrence of from replaced by to.
stringclass index