nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.58k stars 1.47k forks source link

Copy by value does not work in JS #347

Closed reactormonk closed 8 years ago

reactormonk commented 11 years ago
var a = newSeq[proc():int]()
for i in [1,2,3,4]:
  var j = i
  var fun = proc():int = j
  a.add(fun)

for fun in a: echo(fun())

Produces in C:

1
2
3
4

Produces in JS:

4
4
4
4
reactormonk commented 11 years ago

Can be solved via https://gist.github.com/reactormonk/5225756. The annoying part is that you have to do scope analysis.

bogen commented 9 years ago

Reactormonk, do you still have that workaround? That gist is dead.

reactormonk commented 9 years ago

It's an explanation on how to do the JS generation. Not a nim WA.

bogen commented 9 years ago

Well, I might be looking into correcting this in the nim JS back end.

reactormonk commented 9 years ago

I corrected the link meanwhile.

yglukhov commented 8 years ago

Due to new-ll the results produced by c gen are the same as in js. Close? :)

reactormonk commented 8 years ago

No, I still get the incorrect results with 13c98222df26925938bdb8bb55d9af900cc5a228.

Or rather, it produces all "4"s in both cases. Intended?

vegansk commented 8 years ago

@reactormonk, read "Closure changes" section here: http://nim-lang.org/news.html#Z2016-01-18-version-0-13-0-released

The semantics of closures changed: Capturing variables that are in loops 
do not produce a new environment. Nim closures behave like JavaScript
closures now.
Xe commented 8 years ago
# cbv.nim
var a = newSeq[proc():int]()

for i in [1,2,3,4]:
  var j = i
  var fun = proc():int = j
  a.add(fun)

for fun in a: echo(fun())
xena@greedo (linux) ~/tmp/nim
➜  nim c -r cbv.nim
Hint: system [Processing]
Hint: cbv [Processing]
Hint:  [Link]
Hint: operation successful (9905 lines compiled; 0.166 sec total; 14.148MB; Debug Build) [SuccessX]
4
4
4
4
xena@greedo (linux) ~/tmp/nim
➜  nim js -d:nodejs cbv
Hint: system [Processing]
Hint: cbv [Processing]
Hint: operation successful (4637 lines compiled; 0.147 sec total; 3.358MB; Debug Build) [SuccessX]

xena@greedo (linux) ~/tmp/nim
➜  node nimcache/cbv.js
4
4
4
4

I don't know if this is intended or not, but it is consistent now.

Nim Compiler Version 0.13.0 (2016-01-18) [Linux: amd64]
Copyright (c) 2006-2015 by Andreas Rumpf

git hash: a121c3f9eb2a348b9d6ae03ffd01aab26a238c30
active boot switches: -d:release