Search code examples
functionkeypressexecution

How can I execute a function when key is pressed in Lua?


I just want to execute findSum() function when '+' key is pressed. so when I press '+' key, then the function findSum() must be called. This is my program so far:

numberOfInput = 0                                               
sum = 0                                                         


io.write('\t', "Welcome to My Calculator", '\n')
repeat
io.write("for addition, press '+' :", '\n')
findSumSection = io.read()
until
(string.match(findSumSection, '+'))

function findSum()                              
io.write("Enter the amount of feed(s):",'\n')                   
numberOfInput = io.read()
x = numberOfInput                                               
for i = 1, x, 1 do                                                  
io.write('\n',"enter the number: ")
inputs = io.read()                                              
sum = sum + inputs                                              
end
return sum
end

io.write('\n',"The Sum of your feeds is:", '\n' , findSum(), '\n')  

io.write("Do you want to continue? [Y/N]")  
inputYesorNo = io.read()  


if (string.match(inputYesorNo, 'yes')) then
    print("Starting the program again")
    
else if(string.match(inputYesorNo, 'no')) then
os.exit()                                               
else
print("The program can not understand the procedure")       
end
end

Solution

  • Mike67 Thank you for testing the program. I think I fixed the problem. what I wanted to do was when I pressed the '+' key I wanted to go to the function findSum() to make it execute. I approached the problem in another program. take a look

    function printMyName()
    name = io.read()
    return name
    end
    
    function findYourAge()
    io.write("enter the current year:")
    currentYear = io.read()
    io.write('\n',"enter the year you were born:")
    bornYear = io.read()
    age = currentYear - bornYear
    updatedAge = math.abs(age)
    return updatedAge
    end
    
    function ageLimitToVote()
    ageLimit = 18
    newAgeForVote = 0
    if(updatedAge < ageLimit) then
    repeat 
    updatedAge = updatedAge + 1
    until 
    updatedAge == ageLimit
    newAgeForVote = updatedAge
    return newAgeForVote
    end
    end
    
    io.write("What is your name ", '\n')
    io.write("your name is ", printMyName(), '\n')
    
    io.write("Do you want to find your age?", '\n')
    answer = io.read()
    if(string.match(answer, 'yes')) then
    findYourAge()
    elseif(string.match(answer, 'no')) then 
    os.exit()
    end
    
    if(updatedAge > 16) then
    io.write(name, " you are matured enough to vote", '\n')
    else
    io.write(name, " you are ", updatedAge, " years old. and you have to wait until                you are ", ageLimitToVote(), '\n')
    end
    

    *here is the solution I implemented as I think, as best so far.

    if(string.match(answer, 'yes')) then
    findYourAge()