Lua Guessing Game
A guessing game is a program where the player tries to find a secret number from a clue after each guess. This project builds the full game with a hint function, a fixed list of guesses, and a loop that stops on the hit.
The hint function gives three clues
hint compares a guess with the target 67. The three calls print too low, too high, and correct, in that order.
local function hint(guess, target)
if guess < target then
return "too low"
elseif guess > target then
return "too high"
else
return "correct"
end
end
print(hint(50, 67))
print(hint(80, 67))
print(hint(67, 67))The program picks its secret
This short program picks the secret number and prints it with a label. The full game keeps the same pick and hides it from the player.
math.randomseed(1234)
local secret = math.random(100)
print("Secret picked: " .. secret)Example
local function hint(guess, target)
if guess < target then
return "too low"
elseif guess > target then
return "too high"
else
return "correct"
end
end
math.randomseed(1234)
local secret = math.random(100)
local guesses = {50, 75, 67}
local tries = 0
for i, guess in ipairs(guesses) do
tries = i
local result = hint(guess, secret)
print(string.format("Guess %d: %d - %s", i, guess, result))
if guess == secret then
break
end
end
print(string.format("Found %d in %d guesses", secret, tries))Key points
- Secret: the program picks one secret number at the start, and the guesses aim at that number.
- Hint: the hint function compares one guess with the secret and returns "too low", "too high", or "correct".
- Guesses: the guesses sit in a table, and ipairs walks them in order.
- Line: string.format builds one line that shows the guess number, the guess, and its hint.
- Break: break leaves the loop as soon as the correct guess is found.
- Result: the last line reports the secret and how many guesses it took.
In this example, hint is defined first, then the program picks the secret number 67. The loop walks the guesses table in order, prints one formatted line per guess with its hint, and breaks on the third guess because it matches the secret, so the final line reports 67 found in 3 guesses.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
The guesses table changes to {67}. What does the game print on its final line?