Skip to content

inner scopes don't shadow variables; large potential for bugs #238

@onnlucky

Description

@onnlucky

There is a slight conflict when there is no explicit variable introduction and variables are mutable (in any language). You might accidently re-use a more outer variable in a inner function, while you wanted to shadow it instead.

trivial example:

foo: "hello"

testing: ->
  foo: "unrelated"
  alert foo

testing()
alert foo

This example is trivial; but in the real world this happens easily with only local meaningful variables like an n, or prev or what have you ...

The trouble is: foo: "hello" stands for assign "hello" to foo variable and introduce foo as a variable (in the current scope) if it doesn't exist already.

But there are two distict uses: (1) you need a new (local) variable; (2) you want to assign a new value to a (more) global variable. Trouble is with (1): you need to keep in your head a list of all more global variables.


Using var x: "value" prevents this. And you could make the var optional or use something like local to make this explicit. Or you can use x: "value" as introduction and assignment, and use x = "newvalue" as variable change (but not introduction). Or just document the behavior and its shortcomings clearly and learn to live with them. (Or you can do what python does, if the first reference is a read, it is a more global variable, otherwise it is a local variable; but please don't.)

I'm willing to bet this will cause someone to waste a day of debugging, which turns out to be a unexpected sharing of a more outer variable.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions