sannybuilder/dev

Scoped local variables in SCM scripts RFC

MiranDMC opened this issue · 4 comments

Please introduce scope block concept for named local variables.

Idea is to add new keyword scope which would be used in pair with end to create blocks (same as for example const).
Block like that would result in reset of used local variable counter value used to allocating named local variable indexes.
Scope should also make previously allocated local variable names not accessible.
It should not be possible to nest scope blocks. This will create two possible states: script global scope, or local scope.

int a // 0@
int b = 4 // 1@
int c = // 2@

scope
    int d // now 0@ instead of 3@
    int e = b // error, b is unknown identifier
    int a = 1 // 1@ - allowed 'a' is new identifier
end

Scope block should not affect global $ variables.
Scope block should not affect local @ variables with indexes <0 and >31 (future virtual variables: #270)

This feature would enable us to use named local variables within cleo_call [0AB1] functions, which actually implements concept of current scope in term of storing-restoring all local variables along with scope traversing via call-return opcodes.

scope
    float a, b, c // input arguments
    :FUNC
        float d
        d = a
        d += b
    cleo_return 1 d
end

If implemented this way it wil even work correctly with nested cleo calls.

This feature will be also reused in future functions feature #263, as function keyword will inherit (and extend?) behaviour of scope.

Scope block will be also useful for enclosing code of missions and script sub-threads (create script from label), as these two spawn their own set of local variables.

x87 commented

4.0.0-beta.5 allows declaration of custom variables in functions in main.scm