forum-msg-id-136290-edit

Original date:2021-07-23 21:28:18 Edited by: petelomax Subject: Re: eval()

katsmeow said...
string cmd = `puts(1,"Hello World\n")` 
x = eval(cmd) 

That is fine.

Let me try some more examples.
This will not work:

include eval.e 
integer x = 2, y = 2, z 
?eval("z = x + y") 

Output (and yes, it has designated/invented a filename of "", given it a fairly meaningless line number, and not quite sure why it picks the builtins directory):

C:\Program Files (x86)\Phix\builtins\:1 
z = x + y 
^ undefined identifier z 
 
Press Enter, or d for diagnostics... 

This however will:

include eval.e 
?eval("integer x, y, z = x + y",{"z"},{{"x",2},{"y",2}}) -- outputs {4} 

If however we did this:

include eval.e 
{} = eval("integer x, y, z = x + y ?z",{},{{"x",2},{"y",2}}) -- outputs 4 

Then, since we did not ask for z to be returned, it (along with x and y) is gone, for good.
The standard compiler/interpreter wilfully and regularly just "throws stuff away" when execution terminates,
and of course that same effect happens (for now at least) when you embed eval() in another application.
Precisely when than happens is officially "undefined": it would be fair to say that C-based languages have a
"whenever the GC decides to trigger" policy whereas Phix has a "no continuous bleed" policy, and neither have
an "asap" policy, for obvious performance reasons both, though Phix moved about 12 steps closer to the latter
with the the 1.0.0 release, not that 100% asap will ever be an actual target.

Obviously you can do things in loops, eg (noting we have two entirely separate x and y here)

include eval.e 
string cmd = `integer x, y printf(1,"%d + %d = %d\n",{x,y,x+y})` 
for x=1 to 2 do 
    for y=1 to 2 do 
        {} = eval(cmd,{},{{"x",x},{"y",y}}) 
    end for 
end for 

Output:

1 + 1 = 2 
1 + 2 = 3 
2 + 1 = 3 
2 + 2 = 4 

However as mentioned in "the lifetime/persistency of generated code" there may be some performance hitches with recompiling/reinitialising/extracting/restoring values that may or may not need to be addressed, especially when it comes to longer code snippets. It may all be fine, just could possibly deserve some improvement when/if someone starts to repeatedly eval 10,000+ lines.

In contrast, shunting humongous tables into and out of such "eval contexts" should not have any significant overheads, barring perhaps the odd careless and hopefully fairly easily fixable refcount slipup.

There isn't any special syntax here, the code string passed has to be complete enough to run standalone, although we do get the chance to "poke" and "peek" a few variables.

Not Categorized, Please Help

Search



Quick Links

User menu

Not signed in.

Misc Menu