Lua programming

Lua is a programming language like C, but it’s a lot easier to learn. Lua is one of the simplest programming languages and was made in 1993. Me and my dad have started to learn it and we’re really enjoying experimenting with it.

We made a simple ‘guess the number’ game. Even though Lua is a lot simpler than C, it was still quite hard to create it. Firstly, the random number function didn’t work so we had to call it twice and add a seed which was, in this case, the time in seconds. The reason for this was because the random number was only random once because its starting number (seed) stayed the same each round. Next, the random number stayed the same because the seed didn’t change much when it was the time. Therefore, we had to call the random number again to make it random enough (nothing is totally random).

It looked like this (I have included a screenshot from SciTe which is a Lua editor because WordPress cannot highlight Lua code properly):

guess the number lua code screenshot

--[[  Guess the number game, by Jeevan

computer thinks of a number between 1 and arg[1]
if no arg then 1 to 100
computer asks user "guess my number"
it then tells the user whether the computer's number is higher or lower (or equal) than the guess
once guessed computer tells user the number of guesses


-- variables
local maxNumber, theNumber, userGuess, numTries

numTries = 0

-- check arguments
if (#arg == 1)
maxNumber = tonumber(arg[1])
maxNumber = 100
-- check we actually got a number
if (maxNumber == nil or maxNumber <= 1 or maxNumber > 1000000)
print("That was not a valid number (for this game), using default of 100")
maxNumber = 100

theNumber = math.random()
theNumber = math.random(maxNumber) -- the first random() always comes back the same or is predictable even with randomseed, so we use the 2nd one
print("I thought of a number between 1 and " .. maxNumber .. "; can you guess it?")

userGuess = tonumber(
numTries = numTries + 1

if (userGuess == nil or userGuess < 1 or userGuess > maxNumber) -- check we actually got a number
print("That was not a valid number (but it does count as a go so be careful fat fingers).")
elseif (userGuess < theNumber)
elseif (userGuess > theNumber)

if (numTries == 5 or numTries >= 10)
print ("Come on, you're rubbish at this game.")

until userGuess == theNumber

print("You got it in " .. numTries .. " goes.")


1 Comment

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