From ca94a68d03c201c30b6da0fd05f376449bcba88d Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 8 Jan 2024 10:43:48 +0100 Subject: [PATCH] fix logical operators evaluating their LHS twice --- src/operators.ts | 8 +++++++- src/parser.ts | 4 ++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/operators.ts b/src/operators.ts index 95b441b..6556f00 100644 --- a/src/operators.ts +++ b/src/operators.ts @@ -36,6 +36,10 @@ const binaryBooleanArithmetic = ( // extra const bool = (value: LuaType): boolean => coerceToBoolean(value) +// logical +const and = (l: LuaType, r: LuaType): LuaType => coerceToBoolean(l) ? r : l +const or = (l: LuaType, r: LuaType): LuaType => coerceToBoolean(l) ? l : r + // unary const not = (value: LuaType): boolean => !bool(value) @@ -156,6 +160,8 @@ const ge = (left: LuaType, right: LuaType): boolean => !lt(left, right) const operators = { bool, + and, + or, not, unm, bnot, @@ -178,7 +184,7 @@ const operators = { lt, le, gt, - ge + ge, } export { operators } diff --git a/src/parser.ts b/src/parser.ts index a5dcac0..c3d5caf 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -303,10 +303,10 @@ const generate = (node: luaparse.Node): string | MemExpr => { const operator = node.operator if (operator === 'and') { - return `(!__lua.bool(${left})?${left}:${right})` + return `__lua.and(${left},${right})` } if (operator === 'or') { - return `(__lua.bool(${left})?${left}:${right})` + return `__lua.or(${left},${right})` } throw new Error(`Unhandled logical operator: ${node.operator}`) }