Lua – Guess My Number

I was messing around with Lua tonight, and as a basic exercise threw together a Guess My Number game. Unfortunately, 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

-- 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")

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 ="*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!")
-- 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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s