Charles Pegge
15-04-2009, 17:57
An Oxygen program can now compile strings of source code and run them without stopping. This allows EVAL functions to be implemented.
This is also a feature of Functional languages - being able to pass a function as a parameter of another function.
In our case, the function or expression is simply passed inside a string.
The compile() function is essentially a recursive operation and supports the full O2H Basic.
http://community.thinbasic.com/index.php?topic=2517
Compilefun3.tbasic
'RUNTIME COMPILING FROM STRINGS
'
uses "oxygen"
dim src as string
src = "
'
global as double x,y,z
function evaluate (s as string, b as long, e as long) as string
dim a,p=1 as long
dim v,u,cr as string
cr=chr(13) chr(10)
v=nuls 4000
mid v,p,s+cr+cr
p+=4+len s
a=compile `o2h `+s
if len (error) then print `runtime error: ` error : frees a : exit function
for x=b to e
call a
u=str(x)+chr(9)+str(y)+chr(13)+chr(10)
mid v,p,u : p+=len u
next
function=left v,p-1
frees a
end function
print evaluate `y=x*x*x`,1,10
print evaluate `y=sqrt x`,1,9
"
o2_basic src
'msgbox 0, o2_prep "o2h "+src
if len(o2_error) then
msgbox 0, o2_error : stop
end if
o2_exec
This is also a feature of Functional languages - being able to pass a function as a parameter of another function.
In our case, the function or expression is simply passed inside a string.
The compile() function is essentially a recursive operation and supports the full O2H Basic.
http://community.thinbasic.com/index.php?topic=2517
Compilefun3.tbasic
'RUNTIME COMPILING FROM STRINGS
'
uses "oxygen"
dim src as string
src = "
'
global as double x,y,z
function evaluate (s as string, b as long, e as long) as string
dim a,p=1 as long
dim v,u,cr as string
cr=chr(13) chr(10)
v=nuls 4000
mid v,p,s+cr+cr
p+=4+len s
a=compile `o2h `+s
if len (error) then print `runtime error: ` error : frees a : exit function
for x=b to e
call a
u=str(x)+chr(9)+str(y)+chr(13)+chr(10)
mid v,p,u : p+=len u
next
function=left v,p-1
frees a
end function
print evaluate `y=x*x*x`,1,10
print evaluate `y=sqrt x`,1,9
"
o2_basic src
'msgbox 0, o2_prep "o2h "+src
if len(o2_error) then
msgbox 0, o2_error : stop
end if
o2_exec