Skip to content
Kavachकवच

The Terminal: Prompts

● Intermediate3 min

term.prompt, prompt_int, confirm and choose ask the user a question and give a typed answer.

use std.term

fn main() {
    const size = term.choose("Which size?", ["Small", "Medium", "Large"]) ?? 1
    if term.confirm("Order a {["Small", "Medium", "Large"][size]} tea?", default: false) {
        print("one tea coming up")
    } else {
        print("maybe later")
    }
}

The program ran and printed:

kavach run confirm.kav

Which size?  1. Small  2. Medium  3. LargeChoose 1-3: Order a Large tea? [y/N] one tea coming up
confirm.kav: Kavach code, then what running it prints
FunctionGives
term.prompt(question) -> String?Prints question and a space, and gives the line typed, or none at the end of input
term.prompt_int(question) -> Int?Asks for a whole number: an answer that isn't one gets Please type a whole number. and the question again; none at the end of input
term.prompt_float(question) -> Float?The same for a number (2.5, 3), with Please type a number.
term.prompt_secret(question) -> Secret?Asks for a password or a token, the typing not shown (io.read_hidden), and gives Secret(text: …); none at the end of input
term.confirm(question, default: Bool) -> BoolAsks a yes-or-no question, shown with [y/N] (or [Y/n] when default is true): y or yes gives true, n or no gives false, anything else, an empty line or the end of input gives default
term.choose(question, options: [String]) -> Int?Prints question and the options, numbered from 1, and asks for a number: gives the index (from 0) of the option chosen, or none when the answer is not one of them

Prompts read standard input whether or not it is a terminal, so a script can answer them through a pipe, as this page did. See User Input for names, numbers and passwords.