Lua – Guess My Number
January 26, 2011 Leave a comment
I was messing around with Lua tonight, and as a basic exercise threw together a Guess My Number game. Unfortunately, WordPress.com doesn’t have syntax highlighting for Lua. C’est la vie!
I also learned that the first number you grab from math.random() may not be properly randomized after seeding. Running my code in the interpreter generated 36 five times in a row as the answer, which clued me in to this
Calling math.random() once after seeding seems to fix it, though.
-- Guess My Number
-- Author: Zachary Hoefler
--INITIALIZATION
-- Generate a random number
math.randomseed( os.time() )
math.random(); -- make sure first number is actually randomized (some implementations
-- require this, but it doesn't break ones that don't)
local THE_NUMBER = math.random(1,100) -- generates a number from 1 to 100, inclusive
-- Welcome the user
print("Guess My Number, by Zach Hoefler")
-- MAIN GAME LOOP
local guess = nil -- explicitly declared to make it local
while (guess ~= THE_NUMBER) do
-- prompt for a guess; use io.write() so there's no newline after the prompt
io.write("Please enter a guess from 1-100: ");
guess = io.read("*number")
-- Compare to the correct number
if guess > THE_NUMBER then
print("You guessed too high!")
elseif guess < THE_NUMBER then
print("You guessed too low!")
end
end
-- Number was guessed correctly
assert(guess == THE_NUMBER)
-- Congratulate the user
print("Congratulations, you guessed correctly!")
Strictly speaking, I could’ve used repeat-until instead of while, but the while loop felt a bit more readable.
