From e059953c352a7fda0191ec4abd129ab3832753f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ozan=20Hac=C4=B1bekiro=C4=9Flu?= Date: Fri, 22 May 2020 21:38:29 +0300 Subject: [PATCH] fix for in loop symbols (#290) * fix for in loop symbols * fix comments --- compiler.go | 6 ++++-- vm_test.go | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/compiler.go b/compiler.go index 1e2a494..757a810 100644 --- a/compiler.go +++ b/compiler.go @@ -847,8 +847,8 @@ func (c *Compiler) compileForInStmt(stmt *parser.ForInStmt) error { // ... body ... // } // - // ":it" is a local variable but will be conflict with other user variables - // because character ":" is not allowed. + // ":it" is a local variable but it will not conflict with other user variables + // because character ":" is not allowed in the variable names. // init // :it = iterator(iterable) @@ -893,6 +893,7 @@ func (c *Compiler) compileForInStmt(stmt *parser.ForInStmt) error { if keySymbol.Scope == ScopeGlobal { c.emit(stmt, parser.OpSetGlobal, keySymbol.Index) } else { + keySymbol.LocalAssigned = true c.emit(stmt, parser.OpDefineLocal, keySymbol.Index) } } @@ -909,6 +910,7 @@ func (c *Compiler) compileForInStmt(stmt *parser.ForInStmt) error { if valueSymbol.Scope == ScopeGlobal { c.emit(stmt, parser.OpSetGlobal, valueSymbol.Index) } else { + valueSymbol.LocalAssigned = true c.emit(stmt, parser.OpDefineLocal, valueSymbol.Index) } } diff --git a/vm_test.go b/vm_test.go index 4ffaed7..d451726 100644 --- a/vm_test.go +++ b/vm_test.go @@ -1531,7 +1531,23 @@ func TestFunction(t *testing.T) { add2 := newAdder(2); out = add2(5); `, nil, 7) + expectRun(t, ` + m := {a: 1} + for k,v in m { + func(){ + out = k + }() + } + `, nil, "a") + expectRun(t, ` + m := {a: 1} + for k,v in m { + func(){ + out = v + }() + } + `, nil, 1) // function as a argument expectRun(t, ` add := func(a, b) { return a + b };