| 1 |
// name: eval-global.ck |
| 2 |
// desc: this example uses Machine.eval() to run generated code |
| 3 |
// to update a global variable; this also shows Machine.eval() |
| 4 |
// running the evaluatd code synchronously and immediately |
| 5 |
// |
| 6 |
// version: requires chuck-1.5.0.5 or higher |
| 7 |
// Machine.eval() was first introduced in 1.5.0.0; |
| 8 |
// the operation semantics was changed in 1.5.0.5 for |
| 9 |
// Machine eval to run immediately, and automatically |
| 10 |
// yielding the current shred to give the eval'ed code |
| 11 |
// a chance to run -- all this without advancing time |
| 12 |
// |
| 13 |
// uncomment this to print out info about Machine: |
| 14 |
// Machine.help(); |
| 15 |
// |
| 16 |
// date: Summer 2023 |
| 17 |
|
| 18 |
// a shared value among shreds |
| 19 |
global int g_value; |
| 20 |
|
| 21 |
// initial value |
| 22 |
100 => g_value; |
| 23 |
|
| 24 |
// code str |
| 25 |
"global int g_value; g_value++;" => string code; |
| 26 |
|
| 27 |
// do this a couple of times |
| 28 |
repeat( 3 ) |
| 29 |
{ |
| 30 |
// this shows the execution order of Machine.eval() within |
| 31 |
// a single line of code -- Machine.eval() runs the new code |
| 32 |
// immediately (and synchronously) before continuing the |
| 33 |
// current shred (even if it's in the middle of a statement) |
| 34 |
// as shown below |
| 35 |
cherr <= g_value <= " " |
| 36 |
<= (Machine.eval(code) ? "(eval)" : "(error)") <= " " |
| 37 |
<= g_value <= " " |
| 38 |
<= (Machine.eval(code) ? "(eval)" : "(error)") |
| 39 |
<= IO.nl(); |
| 40 |
} |