22 — Terminal menu — a small TUI
A TUI (text user interface) is a menu you drive with the keyboard. The example
examples/terminal-menu.nme shows three choices, waits for an answer, does
what you picked, and then shows the menu again. It is a learning project, not
advice.
Run it and feed it two answers — 1 greets you, then 3 quits. Because the
loop goes back to the menu after the first answer, the menu appears twice:
printf '1\n3\n' | nme r examples/terminal-menu
1) greet
2) dice
3) quit
choose: hello!
1) greet
2) dice
3) quit
choose: bye
Steps
The
use random latestline loads the dice function, and a text value holds the menu.\nmeans "new line" — it is how one string becomes three rows:
run it →# part of examples/terminal-menu.nme use random latest menu = "1) greet\n2) dice\n3) quit"while True:makes an endless loop;show menuprints the choices andask choice, "choose: "stores your answer:
run it →# part of examples/terminal-menu.nme while True: show menu ask choice, "choose: "The block starts at the indentation, exactly like Python.
The
if/elif/elsefrom guide 06 runs one branch per answer. The plain Python headersif choice == "1":mix freely with the NME linesshow/breakinside the same block:
run it →# part of examples/terminal-menu.nme while True: show menu ask choice, "choose: " if choice == "1": show "hello!" elif choice == "2": show random_number(1, 6) else: show "bye" breakshow random_number(1, 6)rolls the die from guide 10 on the spot; any other answer falls intoelse, printsbye, and leaves the loop withbreak— the one way out ofwhile True:.nme checkverifies the syntax without running the loop:nme check examples/terminal-menuThe Korean twin
examples/terminal-menu.ko.nmeuses the samewhile True:loop withask 선택, "고르세요: ";nme r examples/terminal-menu.kopicks the same numbers and gets the same flow in Korean.
Try it yourself
Add a fourth row 4) coin to menu, then a new elif choice == "4": branch
that shows a random pick between two sides — guide 10 shows
how. break still works; the extra number just adds another branch.
What you learned
while True:loops forever;breakis the way out.- A menu is show, ask, branch, then loop back.
show/askNME lines mix with plain Pythonif choice == "1":headers.\ninside a string makes a new line.