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)
then
maxNumber = tonumber(arg[1])
else
maxNumber = 100
end
-- check we actually got a number
if (maxNumber == nil or maxNumber <= 1 or maxNumber > 1000000)
then
print("That was not a valid number (for this game), using default of 100")
maxNumber = 100
end

math.randomseed(os.time())
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?")

repeat
userGuess = tonumber(io.read())
numTries = numTries + 1

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

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

until userGuess == theNumber

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

 
Advertisements

1 Comment

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s