Input & Output
Let’s start exploring Lune’s capabilities with the stdio
library, which handles standard input and output. This is one of the most useful libraries for creating interactive scripts.
Getting User Input
Section titled “Getting User Input”The stdio
library makes it easy to interact with users. Let’s create our first interactive script called hello.luau
:
local stdio = require("@lune/stdio")
local name = stdio.prompt("text", "What's your name?")
print(`Hello, {name}!`)
Save this file in your current directory, then run it using the Lune CLI:
lune run hello
When you run this script, it will wait for you to type your name and press Enter, then greet you!
Different Types of Prompts
Section titled “Different Types of Prompts”The stdio
library can prompt for more than just text. Let’s expand our script to ask a yes/no question:
local stdio = require("@lune/stdio")
local name = stdio.prompt("text", "What's your name?")print(`Hello, {name}!`)
local confirmed = stdio.prompt("confirm", "Is that really your name?")if confirmed then print(`Nice to meet you, {name}!`) print("Have a great day!")else print("Hmm, well whoever you are, welcome!")end
The confirm
prompt type shows a yes/no question and returns true
or false
based on the user’s choice.
These two prompt types - text
and confirm
- will cover most of your interactive script needs. There are more advanced options available in the stdio API reference when you need them.
Extra: Number Guessing Game
Building a Simple Game
Section titled “Building a Simple Game”Here’s a fun example that combines what we’ve learned with some basic Luau programming. Don’t worry if you don’t understand every line yet - focus on how stdio.prompt
is used to create an interactive experience:
local stdio = require("@lune/stdio")
print("Welcome to the number guessing game!")print("I'm thinking of a number between 1 and 10.")print()
local answer = tostring(math.random(1, 10))local attempts = 0
local guess = stdio.prompt("text", "What's your guess?")attempts += 1
while guess ~= answer do if tonumber(guess) and tonumber(guess) < tonumber(answer) then print("Too low! Try again.") elseif tonumber(guess) and tonumber(guess) > tonumber(answer) then print("Too high! Try again.") else print("That's not a valid number.") end
guess = stdio.prompt("text", "What's your guess?") attempts += 1end
print()print(`Correct! You got it in {attempts} attempts!`)
Try running this game and see if you can guess the number! This example shows how stdio.prompt
can be used in a loop to create ongoing interaction.
lune run guessing-game
What’s Next?
Section titled “What’s Next?”Now that you know how to get input from users, let’s learn about handling input that comes from the command line when someone runs your script. This is covered in the next chapter on Arguments.