Skip to content

Commit 452aab9

Browse files
committed
Fixed bug where constructor was called before initializing fields.
1 parent 0003996 commit 452aab9

File tree

2 files changed

+46
-3
lines changed

2 files changed

+46
-3
lines changed

src/Transpiler.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1384,8 +1384,6 @@ export abstract class LuaTranspiler {
13841384
}
13851385
result += this.indent + `function ${className}.new(construct, ...)\n`;
13861386
result += this.indent + ` local instance = setmetatable({}, ${className})\n`;
1387-
result += this.indent + ` if construct and ${className}.constructor then `
1388-
+ `${className}.constructor(instance, ...) end\n`;
13891387

13901388
for (const f of instanceFields) {
13911389
// Get identifier
@@ -1397,6 +1395,9 @@ export abstract class LuaTranspiler {
13971395
result += this.indent + ` instance.${fieldName} = ${value}\n`;
13981396
}
13991397

1398+
result += this.indent + ` if construct and ${className}.constructor then `
1399+
+ `${className}.constructor(instance, ...) end\n`;
1400+
14001401
result += this.indent + ` return instance\n`;
14011402
result += this.indent + `end\n`;
14021403

test/unit/class.spec.ts

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,29 @@ import * as util from "../src/util";
55

66
export class ClassTests {
77

8+
@Test("ClassFieldInitializer")
9+
public classFieldInitializer() {
10+
// Transpile
11+
const lua = util.transpileString(
12+
`class a {
13+
field: number = 4;
14+
}
15+
return new a().field;`
16+
);
17+
18+
// Execute
19+
const result = util.executeLua(lua);
20+
21+
// Assert
22+
Expect(result).toBe(4);
23+
}
24+
825
@Test("ClassConstructor")
926
public classConstructor() {
1027
// Transpile
1128
const lua = util.transpileString(
1229
`class a {
13-
field: number;
30+
field: number = 3;
1431
constructor(n: number) {
1532
this.field = n * 2;
1633
}
@@ -230,6 +247,31 @@ export class ClassTests {
230247
Expect(result).toBe(4);
231248
}
232249

250+
@Test("ClassMethodOverride")
251+
public classMethodOverride() {
252+
// Transpile
253+
const lua = util.transpileString(
254+
`class a {
255+
public method(): number {
256+
return 2;
257+
}
258+
}
259+
class b extends a {
260+
public method(): number {
261+
return 4;
262+
}
263+
}
264+
let inst = new b();
265+
return inst.method();`
266+
);
267+
268+
// Execute
269+
const result = util.executeLua(lua);
270+
271+
// Assert
272+
Expect(result).toBe(4);
273+
}
274+
233275
@Test("methodDefaultParameters")
234276
public methodInheritedParameters() {
235277
// Transpile

0 commit comments

Comments
 (0)