Skip to content

Commit

Permalink
Add array destructuring
Browse files Browse the repository at this point in the history
  • Loading branch information
Sainan committed Apr 10, 2023
1 parent 7f0aa45 commit b5e740a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/lparser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3668,7 +3668,6 @@ static void checktoclose (FuncState *fs, int level) {


static void restdestructuring (LexState *ls, int line, std::vector<std::pair<TString*, expdesc>>& pairs) {
check_match(ls, '}', '{', line);
checknext(ls, '=');

/* begin scope of the locals we want to create */
Expand Down Expand Up @@ -3721,14 +3720,30 @@ static void destructuring (LexState *ls) {
std::vector<std::pair<TString*, expdesc>> pairs{};
luaX_next(ls); /* skip '{' */
do {
TString* var = str_checkname(ls);
TString* var = str_checkname(ls, true);
TString* prop = var;
if (testnext(ls, '='))
prop = str_checkname(ls);
expdesc propexp;
codestring(&propexp, prop);
pairs.emplace_back(var, std::move(propexp));
} while (testnext(ls, ','));
check_match(ls, '}', '{', line);
restdestructuring(ls, line, pairs);
}

static void arraydestructuring (LexState *ls) {
auto line = ls->getLineNumber();
std::vector<std::pair<TString*, expdesc>> pairs{};
luaX_next(ls); /* skip '[' */
expdesc prop;
init_exp(&prop, VKINT, 0);
prop.u.ival = 1;
do {
pairs.emplace_back(str_checkname(ls, true), prop);
prop.u.ival++;
} while (testnext(ls, ','));
check_match(ls, ']', '[', line);
restdestructuring(ls, line, pairs);
}

Expand All @@ -3738,6 +3753,10 @@ static void localstat (LexState *ls) {
destructuring(ls);
return;
}
if (ls->t.token == '[') {
arraydestructuring(ls);
return;
}
/* stat -> LOCAL NAME ATTRIB { ',' NAME ATTRIB } ['=' explist] */
FuncState *fs = ls->fs;
int toclose = -1; /* index of to-be-closed variable (if any) */
Expand Down
14 changes: 14 additions & 0 deletions tests/basic.pluto
Original file line number Diff line number Diff line change
Expand Up @@ -1016,6 +1016,20 @@ do
}
assert(i == 69)
end
-- Array destructuring
do
local [a, b, c] = { 1, 2, 3 }
assert(a == 1)
assert(b == 2)
assert(c == 3)
end
do
local t = { 1, 2, 3 }
local [a, b, c] = t
assert(a == 1)
assert(b == 2)
assert(c == 3)
end

print "Testing compatibility."
do
Expand Down

0 comments on commit b5e740a

Please sign in to comment.