Skip to content

Commit d1bf66a

Browse files
committed
style: factor out table length transpilation into common function
1 parent 28cc8cd commit d1bf66a

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/transformation/builtins/array.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,17 @@ export function transformArrayConstructorCall(
3030
}
3131
}
3232

33-
const lua50TableLength = lua.createTableIndexExpression(lua.createIdentifier("table"), lua.createStringLiteral("getn"));
33+
function createTableLengthExpression(context: TransformationContext, expression: lua.Expression, node?: ts.Expression) {
34+
if (context.luaTarget === LuaTarget.Lua50) {
35+
const tableGetn = lua.createTableIndexExpression(
36+
lua.createIdentifier("table"),
37+
lua.createStringLiteral("getn")
38+
);
39+
return lua.createCallExpression(tableGetn, [expression], node);
40+
} else {
41+
return lua.createUnaryExpression(expression, lua.SyntaxKind.LengthOperator, node);
42+
}
43+
}
3444

3545
/**
3646
* Optimized single element Array.push
@@ -50,9 +60,7 @@ function transformSingleElementArrayPush(
5060

5161
// #array + 1
5262
let lengthExpression: lua.Expression = lua.createBinaryExpression(
53-
context.luaTarget === LuaTarget.Lua50
54-
? lua.createCallExpression(lua50TableLength, [arrayIdentifier])
55-
: lua.createUnaryExpression(arrayIdentifier, lua.SyntaxKind.LengthOperator),
63+
createTableLengthExpression(context, arrayIdentifier),
5664
lua.createNumericLiteral(1),
5765
lua.SyntaxKind.AdditionOperator
5866
);
@@ -189,9 +197,7 @@ export function transformArrayProperty(
189197
switch (node.name.text) {
190198
case "length":
191199
const expression = context.transformExpression(node.expression);
192-
return context.luaTarget === LuaTarget.Lua50
193-
? lua.createCallExpression(lua50TableLength, [expression], node)
194-
: lua.createUnaryExpression(expression, lua.SyntaxKind.LengthOperator, node);
200+
return createTableLengthExpression(context, expression, node);
195201
default:
196202
return undefined;
197203
}

0 commit comments

Comments
 (0)