Re: eval() function
- Posted by Alex Chamberlain <alex.chamberlain at tiscali.co.uk> Nov 02, 2005
- 595 views
Thanks Juergen - amazing mind! I don't think I made it clear that I need the script to evaluate full Euphoria programs! I have adapted your script to run it my way. --eval.e
include misc.e global constant EVAL_PROG_NAME = "eval_prg.tmp", EVAL_RES_NAME = "eval_res.tmp", EVAL_ERR_RET = -1, EVAL_WRITE_ERR = 1, EVAL_READ_ERR = 2 global integer EVAL_ERROR EVAL_ERROR = 0 global function eval (sequence script) sequence plat, ret integer tmp_fn -- , sys object line -- write a temporary program for evaluating the expression and -- writing the result to another temporary file tmp_fn = open(EVAL_PROG_NAME, "w") if tmp_fn = -1 then EVAL_ERROR = EVAL_WRITE_ERR return EVAL_ERR_RET end if puts(tmp_fn, script) close(tmp_fn) -- run the temporary program if platform() = DOS32 then plat = "ex" elsif platform() = WIN32 then plat = "exw" elsif (platform() = LINUX) or (platform() = FREEBSD) then plat = "exu" end if system(plat & " " & EVAL_PROG_NAME & " > " & EVAL_RES_NAME, 0) -- read the content of the temporary result file, -- and convert it to a number tmp_fn = open(EVAL_RES_NAME, "r") if tmp_fn = -1 then EVAL_ERROR = EVAL_READ_ERR return EVAL_ERR_RET end if ret = {} while 1 do line = gets(tmp_fn) if atom(line) then exit end if ret &= line end while close(tmp_fn) -- delete temporary files system("DEL *.tmp", 0) return ret end function
--demo.ex
include eval.e include get.e sequence script object ret -- Define the script contents - any Euphoria code! script = "puts(1, \"This is this result of the demo eval script!\")" procedure handleReturn(object ret) puts(1, "The script output the following:\n" & ret) end procedure ret = eval(script) if atom(ret) then if EVAL_ERROR = 0 then handleReturn(ret) elsif EVAL_ERROR = EVAL_WRITE_ERR then puts(1, "Sorry, there was a write error whilst evaluating the script") elsif EVAL_ERROR = EVAL_READ_ERR then puts(1, "Sorry, there was a read error whilst evaluating the script") end if else handleReturn(ret) end if abort(wait_key()*0)
The only problem is that the Windows program doesn't like redirecting its input (can others please try it!) and it hasn't been run on Linux/FreeBSD yet. It work on DOS fine so there you go. On the web very soon, and is running up to my CGI interpretor. Thanks, Alex