| View previous topic :: View next topic |
| Author |
Message |
KcDan
Joined: 24 Jan 2006 Posts: 13 Location: Delaware
|
Posted: Thu Jan 26, 2006 12:57 pm Post subject: Evaluate function? |
|
|
I'm working on a calculator for my shell and I cant find anywhere if there is a function that evaulates a string and turns it into a number, for example
"5+6-2" -> 9 |
|
| Back to top |
|
 |
youresam
Joined: 06 Nov 2005 Posts: 87
|
Posted: Thu Jan 26, 2006 1:29 pm Post subject: |
|
|
somenumber = tonumber("5+6-2")
then, somenumber should equal 9, I think. |
|
| Back to top |
|
 |
KcDan
Joined: 24 Jan 2006 Posts: 13 Location: Delaware
|
Posted: Thu Jan 26, 2006 1:59 pm Post subject: |
|
|
| I tried that earlier and it did not work, thanks though. |
|
| Back to top |
|
 |
ema
Joined: 07 Dec 2005 Posts: 11
|
Posted: Fri Jan 27, 2006 12:17 am Post subject: |
|
|
hi,
| Code: | expression = "5+6-2"
script = "return " .. expression -- convert to LUA script
func, err = loadstring(script)
if err then
-- syntax error
else
result = func() -- now result == 9
end
|
will work. |
|
| Back to top |
|
 |
KawaGeo
Joined: 27 Aug 2005 Posts: 191 Location: Calif Mountains
|
Posted: Fri Jan 27, 2006 3:06 am Post subject: |
|
|
Also, the following will work:
| Code: | script = "return 5+6-2"
result = assert(loadstring(script))()
|
Ref: Lua 5 Ref, page 40
Ema, you must have read PIL book well. :)
Hey, guys out there .. hint, hint _________________ Geo Massar
Retired Engineer |
|
| Back to top |
|
 |
KcDan
Joined: 24 Jan 2006 Posts: 13 Location: Delaware
|
Posted: Fri Jan 27, 2006 11:37 am Post subject: |
|
|
| Thanks a lot you two. |
|
| Back to top |
|
 |
|