Quirrel4.41.0

types.String.slice

Method on every string
pure string.slice([start: number, end: number], ...): any

Returns the bytes of str from start up to, but not including, end.

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

startnumberindex of the first byte to keep; defaults to 0 optional
endnumberindex one past the last byte to keep; defaults to str.len() optional
...anynot a real parameter; see Notes repeats

Return value

A new string holding str[start:end]. A negative start or end counts from the end of str, the same as a negative index anywhere else in Quirrel: -1 means the last byte.

Both indices are then clamped into [0, str.len()]; an end at or before start after clamping gives "". No combination of arguments throws: an index far past either end of str, or an inverted range, silently clamps instead. Contrast types.String.tolower and types.String.toupper, which take the same kind of range but throw instead of clamping.

str is a byte buffer, so a start or end that falls inside a multi-byte character splits it; the two halves are no longer valid UTF-8 on their own.

Notes

Takes 0, 1 or 2 arguments, not the variadic tail the VM's dump implies (it shows slice([arg1: number, arg2: number], ...) because this binding carries no declaration string). A third or later argument is silently ignored.

Example

examples/types/string/slice.nut
println("\"hello\".slice(1, 3) =", "hello".slice(1, 3))
println("\"hello\".slice(-3) =", "hello".slice(-3))       // negative index counts from the end

// out-of-range and inverted ranges clamp instead of throwing.
println("\"hello\".slice(10) =", $"[{"hello".slice(10)}]")
println("\"hello\".slice(3, 1) =", $"[{"hello".slice(3, 1)}]")
Output:
"hello".slice(1, 3) = el
"hello".slice(-3) = llo
"hello".slice(10) = []
"hello".slice(3, 1) = []

See also

indexofReturns the byte index of the first occurrence of substr in str.
tolowerReturns a copy of str with the ASCII letters in [start, end) lowercased.
sliceCopies the elements from start up to, but not including, end.
stringclass index