The Daily Click ::. Forums ::. Non-Klik Coding Help ::. Lua Question
 

Post Reply  Post Oekaki 
 

Posted By Message

Ruper



Registered
  11/02/2009
Points
  8
28th June, 2009 at 08:53:01 -

How can I convert a string equation such as "1+1" to a variable which is the answer, in this case: 2?

 
-Ruper

Muz



Registered
  14/02/2002
Points
  6499

VIP MemberI'm on a BoatI am an April FoolHonored Admin Alumnus
28th June, 2009 at 09:11:11 -

In Lua?
tonumber(1)+tonumber(1)


The + shouldn't be in a string at all

 
Disclaimer: Any sarcasm in my posts will not be mentioned as that would ruin the purpose. It is assumed that the reader is intelligent enough to tell the difference between what is sarcasm and what is not.

Image

Ruper



Registered
  11/02/2009
Points
  8
28th June, 2009 at 17:59:18 -

Thanks, although that wasn't the answer I'm looking for.

What I am trying to do is convert a damage calculating formula for an rpg into a number.
The formulas would read something like "STREGTH+(3*DEFENSE)".

What I was trying to do is replace the stats like STRENGTH and DEFENSE with the player's stats. I got that far, but then I just had an equation in the form of the string which I couldn't evaluate.

Maybe I'm going about this the wrong way, but would there be a way to substitute in values and then evaluate the equation in Lua?

 
-Ruper

Xgoff



Registered
  22/02/2009
Points
  135
28th June, 2009 at 21:21:10 -

there's probably a better way but this should work:

function eval(str)

return assert(loadstring("return " .. str))()
end


 
Image

Ruper



Registered
  11/02/2009
Points
  8
28th June, 2009 at 22:34:13 -

Thanks Xgoff! Exactly what I need.

 
-Ruper

Xgoff



Registered
  22/02/2009
Points
  135
28th June, 2009 at 22:50:47 -

btw you may or may not actually need the "return " (the one in loadstring) string in there depending on how you're using the function

if you're using if for something like 'a = eval("1+3")' then you will, but if you're doing variable assignments within the string you don't want it

Edited by Xgoff

 
Image
   

Post Reply



 



Advertisement

Worth A Click