From fb55875e3c587db993ae76543f44115066334460 Mon Sep 17 00:00:00 2001 From: Tzur Soffer <103438808+TzurSoffer@users.noreply.github.com> Date: Sat, 10 Jan 2026 20:00:15 +0200 Subject: [PATCH] Variable and expression bugfixes (#325) * Fix evaluating with Booleans * replaced re with a function (this feature of re is not supported on circutpython) * Fixed internalVar in expression + allows for +=, *=, etc in variable math * Removed added +=, *=, etc operations as they are not in the official language Removed added +=, *=, etc operations as they are not in the official language. I added them in a previous commit and removed them in this one. * Fix duplicate lines --- duckyinpython.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/duckyinpython.py b/duckyinpython.py index 01e2cd0..37a975c 100644 --- a/duckyinpython.py +++ b/duckyinpython.py @@ -189,10 +189,18 @@ def _getCodeBlock(linesIter): code.append(line) return code +def replaceBooleans(text): #< fix capitalization mistakes in true and false (for evaluating with booleans) + # Replace any letter-by-letter match for "true" with the proper "True" + text = re.sub(r'[Tt][Rr][Uu][Ee]', 'True', text) + # Replace any letter-by-letter match for "false" with the proper "False" + text = re.sub(r'[Ff][Aa][Ll][Ss][Ee]', 'False', text) + return text + def evaluateExpression(expression): """Evaluates an expression with variables and returns the result.""" - # Replace variables (e.g., $FOO) in the expression with their values - expression = re.sub(r"\$(\w+)", lambda m: str(variables.get(f"${m.group(1)}", 0)), expression) + expression = replaceVariables(expression) + expression = replaceBooleans(expression) #< Cant use re due its limitation in circutpython + print(expression) expression = expression.replace("^", "**") #< Replace ^ with ** for exponentiation expression = expression.replace("&&", "and") @@ -368,6 +376,7 @@ async def parseLine(line, script_lines): expression = match.group(2) value = evaluateExpression(expression) variables[varName] = value + else: raise SyntaxError(f"Invalid variable update, declare variable first: {line}") elif line.startswith("DEFINE"): @@ -390,13 +399,12 @@ async def parseLine(line, script_lines): loopCode = list(_getCodeBlock(script_lines)) while evaluateExpression(condition) == True: currentIterCode = deepcopy(loopCode) - print(loopCode) + # print(loopCode) while currentIterCode: loopLine = currentIterCode.pop(0) currentIterCode = list(parseLine(loopLine, iter(currentIterCode))) #< very inefficient, should be replaced later. elif line.upper().startswith("IF"): - # print("ENTER IF") script_lines, ret = IF(_getIfCondition(line), script_lines).runIf() print(f"IF returned {ret} code") elif line.upper().startswith("END_IF"):