Page 1 of 1

calculator failure

Posted: Fri Nov 22, 2013 7:16 pm
by Fatmat927
okay, so i'm trying to do a calculator and when I try to get the result of the operation it returns a nil and I would like to know how I could correct my problem

Re: calculator failure

Posted: Fri Nov 22, 2013 8:23 pm
by xordspar0
Ok, if I understand correctly, this is what's going on.
You have two variables that relate to the result. One is operation, which is a string basically containing all of the buttons the user has pushed. The other variable is result, which is tostring(operation). tostring() looks at the string operation and doesn't return a number because it's full of */+- symbols. Notice that if you just enter a number with no operations and press = tostring() is able to convert operation to a number since it just contains a number.

What you need to do is store the numbers and strings separately and then actually apply the operations that the user has pressed (not just store them in a string). I'm not sure of the best way to do this, but one way might be to store all of the numbers and operations in a table (or two separate tables) and inerate through them to find the result when the user presses =.
I suppose you could also write a function to parse the string for numbers and operations. That might make it easier to have a backspace feature, for example. It would certainly be more complicated, though.

Re: calculator failure

Posted: Sat Nov 23, 2013 4:39 pm
by bzSteve
If you're already storing all the keystrokes in a variable called operation, I think you can do something like this to get the answer simply:

Code: Select all

local f = loadstring("answer = " .. operation)
if f then 
  f()
else
  -- handle an illegal operation here...
end
That should put the answer in the global variable answer

Re: calculator failure

Posted: Sat Nov 23, 2013 6:26 pm
by Fatmat927
thank you very much now it works perfectly :)