Skip to content

Commit

Permalink
Merge pull request #157 from Jason2605/feature/multiple_assignment
Browse files Browse the repository at this point in the history
Multiple assignment
  • Loading branch information
Jason2605 authored Mar 24, 2020
2 parents ce2a23d + 768f99b commit 79ad459
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 11 deletions.
23 changes: 13 additions & 10 deletions c/compiler.c
Original file line number Diff line number Diff line change
Expand Up @@ -1202,18 +1202,21 @@ static void funDeclaration(Compiler *compiler) {
}

static void varDeclaration(Compiler *compiler) {
uint8_t global = parseVariable(compiler, "Expect variable name.");
do {
uint8_t global = parseVariable(compiler, "Expect variable name.");

if (match(compiler, TOKEN_EQUAL)) {
// Compile the initializer.
expression(compiler);
} else {
// Default to nil.
emitByte(compiler, OP_NIL);
}
consume(compiler, TOKEN_SEMICOLON, "Expect ';' after variable declaration.");
if (match(compiler, TOKEN_EQUAL)) {
// Compile the initializer.
expression(compiler);
} else {
// Default to nil.
emitByte(compiler, OP_NIL);
}

defineVariable(compiler, global);
defineVariable(compiler, global);
} while (match(compiler, TOKEN_COMMA));

consume(compiler, TOKEN_SEMICOLON, "Expect ';' after variable declaration.");
}

static void expressionStatement(Compiler *compiler) {
Expand Down
7 changes: 7 additions & 0 deletions docs/docs/variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,10 @@ E.g
var someVariable = 10;
someVariable = "Some text"; // Is perfectly valid
```

You can also define multiple variables with a single statement.

```js
var a, b = 10, c = "hello!";
print(a, b, c); // nil, 10, 'hello!'
```
13 changes: 12 additions & 1 deletion tests/variables/assignment.du
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,15 @@ assert(test == 123);

// Test assignment of declared var
x = 100;
assert(x == 100);
assert(x == 100);

// Test multiple variable assignment in a single statement

var a, b = 10, c, d = "test", e = [1, 2], f = {"test": 10};

assert(a == nil);
assert(b == 10);
assert(c == nil);
assert(d == "test");
assert(e == [1, 2]);
assert(f == {"test": 10});

0 comments on commit 79ad459

Please sign in to comment.