calculator failure

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Fatmat927
Prole
Posts: 42
Joined: Wed Sep 18, 2013 1:15 am

calculator failure

Post 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
Attachments
calculator.love
(1.3 KiB) Downloaded 143 times
xordspar0
Prole
Posts: 10
Joined: Thu Nov 21, 2013 5:36 am

Re: calculator failure

Post 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.
User avatar
bzSteve
Prole
Posts: 34
Joined: Tue May 21, 2013 2:31 am

Re: calculator failure

Post 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
Fatmat927
Prole
Posts: 42
Joined: Wed Sep 18, 2013 1:15 am

Re: calculator failure

Post by Fatmat927 »

thank you very much now it works perfectly :)
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 139 guests