fix logical expression short-circuit evaluation (#27)

pull/28/head
Sodium-Aluminate 7 months ago
parent be4f0fa982
commit fb6158a1c0

@ -37,8 +37,15 @@ const binaryBooleanArithmetic = (
const bool = (value: LuaType): boolean => coerceToBoolean(value) const bool = (value: LuaType): boolean => coerceToBoolean(value)
// logical // logical
const and = (l: LuaType, r: LuaType): LuaType => coerceToBoolean(l) ? r : l const and = (l: () => LuaType, r: () => LuaType): LuaType => {
const or = (l: LuaType, r: LuaType): LuaType => coerceToBoolean(l) ? l : r const lv = l()
return coerceToBoolean(lv) ? r() : lv
}
const or = (l: () => LuaType, r: () => LuaType): LuaType => {
const lv = l()
return coerceToBoolean(lv) ? lv : r()
}
// unary // unary
const not = (value: LuaType): boolean => !bool(value) const not = (value: LuaType): boolean => !bool(value)

@ -303,10 +303,10 @@ const generate = (node: luaparse.Node): string | MemExpr => {
const operator = node.operator const operator = node.operator
if (operator === 'and') { if (operator === 'and') {
return `__lua.and(${left},${right})` return `__lua.and(() => ${left}, () => ${right})`
} }
if (operator === 'or') { if (operator === 'or') {
return `__lua.or(${left},${right})` return `__lua.or(() => ${left}, () => ${right})`
} }
throw new Error(`Unhandled logical operator: ${node.operator}`) throw new Error(`Unhandled logical operator: ${node.operator}`)
} }

Loading…
Cancel
Save