Class cli.Select
A single-choice interactive menu widget for CLI tools.
This module provides a simple way to create a menu with a list of choices,
allowing the user to navigate and select an option using keyboard input.
The menu is displayed in the terminal, and the user can use the arrow keys
to navigate through the options. The selected option is highlighted, and the
user can confirm their choice by pressing Enter. Optionally the menu can also be
cancelled by pressing <esc>
or <ctrl+c>
.
NOTE: you MUST call terminal.initialize before calling this widget's :run()
method.
Usage:
local menu = cli.Select{ prompt = "Select an option:", choices = { "Option 1", "Option 2", "Option 3" }, default = 1, cancellable = true } local selected_index, selected_value = menu() -- invokes the 'run' method print("Selected index: " .. selected_index) print("Selected value: " .. selected_value)
Functions
cli.Select (opts) | Create a new Select instance. |
Methods
cli.select:clear_widget () | Clears the widget. |
cli.select:height () | Returns the display height in rows. |
cli.select:run () | Executes the widget. |
Functions
- cli.Select (opts)
-
Create a new Select instance.
Parameters:
- opts Options for the Select menu.
- choices table List of choices (strings) to display.
- default number Default choice index (1-based). (default 1)
- prompt string Prompt message to display. (default "Select an option:")
- cancellable
boolean
Whether the menu can be cancelled (by pressing
<esc>
or<ctrl+c>
). (default false) - clear boolean Whether to clear the widget from screen after completion. (default false)
Returns:
-
Prompt
A new Select instance.
- opts Options for the Select menu.
Methods
- cli.select:clear_widget ()
- Clears the widget.
- cli.select:height ()
-
Returns the display height in rows.
Note: on a first call it will test character widths, see terminal.text.width.test.
So terminal must be initialized before calling this method.
Returns:
-
number
The height of the menu in rows.
- cli.select:run ()
-
Executes the widget.
If necessary it initializes the terminal first.
It also handles the cleanup of the terminal state after the menu is closed.
Returns:
- number or nil The index of the selected choice (1-based) or nil if cancelled.
-
string or err
The selected choice or
"cancelled"
if cancelled.