Skip to content

Incorrect destructuring assignment order #1127

@tomblind

Description

@tomblind

This will produce different results in TSTL vs TS:

const a: string[] = [];
[a[0], a[0]] = ["A", "B"];
console.log(a[0]); // "A" in Lua, "B" in JS

Playground

This is because of a peculiar behavior of Lua where, even though expressions are evaluated in the same order as JS, the actual assignments happen in reverse order. This is demonstrated with this:

const a: string[] = setmetatable([], {__newindex(k, v) { console.log(v); }});
function first() { console.log("first"); return 0; }
function second() { console.log("second"); return 1; }
function third() { console.log("third"); return "A"; }
function fourth() { console.log("fourth"); return "B"; }
[a[first()], a[second()]] = [third(), fourth()]; // first, second, third, fourth, B, A

Playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions