EVAL function or equivalent

Previous topic - Next topic

bigtunacan

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.

bigsofty

You could use "CALLBYNAME( "UPDATE_LEVEL" + LEVEL )" I think, although it's not a command I've used yet.
Cheers,

Ian.

"It is practically impossible to teach good programming style to students that have had prior exposure to BASIC.  As potential programmers, they are mentally mutilated beyond hope of regeneration."
(E. W. Dijkstra)

Slydog

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.
My current project (WIP) :: TwistedMaze <<  [Updated: 2015-11-25]

bigtunacan

Now I'm embarrassed...  I looked through all of the commands in the documentation for something like this and totally missed it!  Thanks guys!

Kitty Hello

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.

bigtunacan

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?