New to LUA, i have question about my script

Viewed 77

Hello im new to LUA and in general new to scripting/coding This is script what im talking about

print("Type a Number!")
repeat
input = io.read()
if input == "10" then 
    print("Ten")
elseif input == "7" then
        print("Seven")

elseif input == "1" then
    print("One!")
elseif input == "exit" or input == "Exit" then
    print("Exiting...")  
else
     print("incorrect")  
end
until input == "Exit" or input == "exit"

I kinda feel like there is too much elseif but I didn't want to print "incorrect" when i type exit or Exit so my solution was to add another elseif before else command. Can be this be more simplified or i can't do nothing with it and its good

And one more question why this is not working

num = 10
input = io.read()
If input == num then 
     print("Ten")
end

Or this code

num = 10
input = io.read()
If input == 10 then 
     print("Ten")
end

Why code above where i have boolean with string after if, only works

2 Answers
  1. Define your behaviour
local actions = {
   [1] = function() print("One");
   -- Same for any other numbers you want
   ["exit"] = function() os.exit() end; -- Close the whole program
}
  1. Get your input
local input = io.read() -- This returns a string
  1. Normalize your input
input = input:lower() -- Make the whole string lowercase
input = tonumber(input) or input -- Try converting to number
  1. Get the action matching your input
local action = actions[input]
  1. Run the action if one was found
if action then
   action()
else
   print("Error! Could not handle input: ", input)
end
local inputs = {
     ['1'] = 'One!'
  ,  ['7'] = 'Seven'
  , ['10'] = 'Ten'
  , exit   = 'Exiting...'
  , Exit   = 'Exiting...'
}
local input
print 'Type a Number!'
repeat
    input = io.read ()
    print (inputs [input] or 'incorrect') -- Lua 'nullsafe' operator.
until input == 'Exit' or input == 'exit'
Related