GLBasic forum

Feature request => IDE/Syntax => Topic started by: bigtunacan on 2011-Sep-21

Title: EVAL function or equivalent
Post by: bigtunacan on 2011-Sep-21
I would really love to be able to execute code dynamically.  I'm thinking something along the lines of JavaScript's EVAL function.

EVAL(string$)

This has some very powerful implications for code simplification.

Just to throw out there as a quick idea of how we benefit from this.  Let's say I have a bunch of different levels and due to various differences I want each level to update under a different function.

Code (glbasic) Select

    SUB UPDATE_LEVEL1
        // update level 1
    ENDSUB

    SUB UPDATE_LEVEL2
        // update level 2
    ENDSUB

    ...

    SUB UPDATE_LEVELX
        // update level X
    ENDSUB


Currently I would need to do something like this.

Code (glbasic) Select

SELECT LEVEL
CASE 1
                                GOSUB UPDATE_LEVEL1
CASE 2
                                GOSUB UPDATE_LEVEL2
                        CASE X
                                GOSUB UPDATE_LEVELX
ENDSELECT
[code=glbasic]

With an Eval function the same code could be expressed as follows.

[code=glbasic]
     EVAL("GOSUB UPDATE_LEVEL" + LEVEL)


Obviously the above is just to show the benefits on a somewhat trivial example.
Title: Re: EVAL function or equivalent
Post by: bigsofty on 2011-Sep-21
You could use "CALLBYNAME( "UPDATE_LEVEL" + LEVEL )" I think, although it's not a command I've used yet.
Title: Re: EVAL function or equivalent
Post by: Slydog on 2011-Sep-21
Or, (not as tidy as CALLBYNAME!), you could use PROTOTYPEs.

They allow changing the function a prototype pointer points to dynamically.
But this doesn't seem to be useful in your example.
Title: Re: EVAL function or equivalent
Post by: bigtunacan on 2011-Sep-21
Now I'm embarrassed...  I looked through all of the commands in the documentation for something like this and totally missed it!  Thanks guys!
Title: Re: EVAL function or equivalent
Post by: Kitty Hello on 2011-Sep-22
whereas "eval" is kicking the interpreter and such can handle the full language. It's about totally impossible to do in C++. Unless you implement an C++ interpreter with function binding. Yikes.
Title: Re: EVAL function or equivalent
Post by: bigtunacan on 2011-Sep-23
Sure Javascript eval is more flexible, just the nature of an interpreted language. Are you just preprocessing in such a way as to unroll it to actual calls at build/compile time?