Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions src/LuaTransformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3664,16 +3664,34 @@ export class LuaTransformer {
flags |= tstl.FunctionExpressionFlags.Inline;
}

const [transformedBody] = this.transformFunctionBody(node.parameters, body, spreadIdentifier);
const [transformedBody, scope] = this.transformFunctionBody(node.parameters, body, spreadIdentifier);

return tstl.createFunctionExpression(
const functionExpression = tstl.createFunctionExpression(
tstl.createBlock(transformedBody),
paramNames,
dotsLiteral,
spreadIdentifier,
flags,
node
);

//Handle named function expressions which reference themselves
if (ts.isFunctionExpression(node) && node.name && scope.referencedSymbols) {
Comment thread
Perryvw marked this conversation as resolved.
const symbol = this.checker.getSymbolAtLocation(node.name);
if (symbol) {
const symbolId = this.symbolIds.get(symbol);
//Only wrap if the name is actually referenced inside the function
if (symbolId !== undefined && scope.referencedSymbols.has(symbolId)) {
Comment thread
Perryvw marked this conversation as resolved.
const nameIdentifier = this.transformIdentifier(node.name);
return this.createImmediatelyInvokedFunctionExpression(
[tstl.createVariableDeclarationStatement(nameIdentifier, functionExpression)],
tstl.cloneIdentifier(nameIdentifier)
);
}
}
}

return functionExpression;
}

public transformNewExpression(node: ts.NewExpression): ExpressionVisitResult {
Expand Down Expand Up @@ -5111,7 +5129,7 @@ export class LuaTransformer {
protected createImmediatelyInvokedFunctionExpression(
statements: tstl.Statement[],
result: tstl.Expression | tstl.Expression[],
tsOriginal: ts.Node
tsOriginal?: ts.Node
): tstl.CallExpression {
const body = statements ? statements.slice(0) : [];
body.push(tstl.createReturnStatement(Array.isArray(result) ? result : [result]));
Expand Down
9 changes: 9 additions & 0 deletions test/unit/functions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -610,3 +610,12 @@ test.each([{}, { noHoisting: true }])("@vararg global", compilerOptions => {

expect(util.executeLua(lua)).toBe("ABCD");
});

test("named function expression reference", () => {
const code = `
const y = function x(inp: string) {
return inp + typeof x;
};
return y("foo-");`;
expect(util.transpileAndExecute(code)).toBe("foo-function");
});