Quirrel4.41.0

string.format

Defined in module "string"
from "string" import format
pure format(fmt: string, ...): string

Formats fmt with the following arguments, following the syntax of the C printf family, and returns the result as a new string.

Parameters

fmtstringthe format string
...anyone value per conversion in fmt repeats

Return value

The formatted string.

Errors

Throws invalid format for a conversion this engine does not recognize, including a * width or precision (taken from an argument, as C allows) - that is never supported here.

Throws not enough parameters for the given format string when fmt needs more arguments than were given. The check happens one conversion at a time as fmt is scanned, not once for the whole call; an extra, unused argument is never an error.

Throws string expected for the specified format when %s gets a non-string argument. Throws integer expected for the specified format for %d, %i, %o, %u, %x, %X or %c when the argument is neither an integer nor a float (a float argument is truncated, not rejected). Throws float expected for the specified format for %f, %g, %G, %e or %E when the argument is neither a float nor an integer.

Notes

The supported conversions are s, i, d, o, u, x, X, c, f, g, G, e, E, and %% for a literal %. Flags (-+ #0) and up to two width digits and two precision digits are read the same way printf reads them; a width or precision of three digits or more throws width format too long or precision format too long instead of being accepted.

A %f/%g/%G/%e/%E conversion always prints . as the decimal separator, whatever the C locale of the process says.

Example

examples/string/format.nut
from "string" import format

println("format(\"%s = %d (0x%02X)\", \"answer\", 42, 42) =", format("%s = %d (0x%02X)", "answer", 42, 42))

// a float argument to an integer conversion truncates, it does not error
println("format(\"%d\", 3.9) =", format("%d", 3.9))

// extra arguments are ignored, a missing one is not
println("format(\"%d %d\", 1, 2, 3) =", format("%d %d", 1, 2, 3))
try {
  format("%d %d", 1)
} catch (e) {
  println("format(\"%d %d\", 1) throws:", e)
}

// "*" (width taken from an argument, as in C's printf) is not supported
try {
  format("%*d", 5, 1)
} catch (e) {
  println("format(\"%*d\", 5, 1) throws:", e)
}
Output:
format("%s = %d (0x%02X)", "answer", 42, 42) = answer = 42 (0x2A)
format("%d", 3.9) = 3
format("%d %d", 1, 2, 3) = 1 2
format("%d %d", 1) throws: not enough parameters for the given format string
format("%*d", 5, 1) throws: invalid format

See also

printfFormats fmt with the following arguments and writes the result to the same output as print, without building and returning a throwaway string.
escapeReturns str with backslash, the two quote characters, and every byte that is not printable ASCII replaced by an escape sequence.
stringmodule index