Skip to content

Feature Request: Support for Local Variable Scoping in Functions #123

@hientrung

Description

@hientrung

Subject: Request to allow local variable declarations within functions to avoid "Illegal variable re-declaration" errors.


1. Description

Currently, cgscript triggers an "Illegal variable re-declaration" error when the same variable name is used in different scopes. The engine seems to treat all variable declarations as if they share a single global namespace, even when they are defined inside independent function blocks.

2. Current Behavior (Failure Scenarios)

The compiler/interpreter fails in the following scenarios, which are standard practices in most modern programming languages:

Scenario 1: Conflict between Local and Global scope

The following code triggers an error because the variable a is declared both inside the function and in the global scope.

Function test = function() {
    string a; // Local declaration
};

string a; // Global declaration - triggers "Illegal variable re-declaration"
test.Call();

Scenario 2: Conflict between two different Function scopes

The following code triggers an error even though the variables are isolated within two independent functions.

Function test = function() {
    string a; // Local to 'test' function
};

Function hi = function() {
    string a; // Local to 'hi' function - also triggers "Illegal variable re-declaration"
};

test.Call();
hi.Call();

3. Requested Change

I would like to request an update to the scoping logic to support Local/Lexical Scoping:

  • Scope Isolation: Variables declared inside a function block should be private to that function's execution context.
  • Namespace Reusability: Multiple functions should be able to declare variables with the same name (e.g., string a) without interference.
  • Variable Shadowing: Local variables should be allowed to have the same name as global variables without triggering re-declaration errors.

4. Why this is needed

Proper variable scoping is essential for modularity. Currently, the lack of this feature leads to:

  • Namespace Pollution: Developers must use unique names for every variable across the entire script.
  • High Maintenance: Harder to manage large projects and increases the risk of naming collisions.
  • Code Fragility: Difficult to write reusable libraries or modules without constant naming conflicts.

Thank you for considering this improvement to cgscript!

Metadata

Metadata

Labels

bugSomething isn't working

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions