Evaluate function?

Discuss using and improving Lua and the Lua Player specific to the PSP.

Moderators: Shine, Insert_witty_name

Post Reply
KcDan
Posts: 13
Joined: Tue Jan 24, 2006 7:58 am
Location: Delaware
Contact:

Evaluate function?

Post by KcDan »

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
youresam
Posts: 87
Joined: Sun Nov 06, 2005 1:43 am

Post by youresam »

somenumber = tonumber("5+6-2")

then, somenumber should equal 9, I think.
KcDan
Posts: 13
Joined: Tue Jan 24, 2006 7:58 am
Location: Delaware
Contact:

Post by KcDan »

I tried that earlier and it did not work, thanks though.
ema
Posts: 11
Joined: Wed Dec 07, 2005 3:02 am
Contact:

Post by ema »

hi,

Code: Select all

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.
KawaGeo
Posts: 191
Joined: Sat Aug 27, 2005 6:52 am
Location: Calif Mountains

Post by KawaGeo »

Also, the following will work:

Code: Select all

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
KcDan
Posts: 13
Joined: Tue Jan 24, 2006 7:58 am
Location: Delaware
Contact:

Post by KcDan »

Thanks a lot you two.
Post Reply