types.String.subst
stringSubstitutes {0}, {1}, ... and {name} placeholders in str with the given values.
... from the prose below, not from the signature.Parameters
value | any | the first substitution value |
... | any | further 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
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)"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
format | Formats fmt with the following arguments, following the syntax of the C printf family, and returns the result as a new string. |
replace | Returns str with every occurrence of from replaced by to. |
| string | class index |