So first I want to say that I am creating a mini coding language, and It is meant for people just coming from Scratch to text based programming. Right now, it does basic command line functions like making a variable, and performing operations. I have written it all by myself in Python and it has a lexer and a parser. What I want to do is allow the user to make call an if() function inside of my language and then it will do the things inside the block. I am just confused on how I would define a function that does something that the user would want other then them making an lambda function, but since my language is for beginners, I don't want that. So esentially what I want to do is create an if function.
python code:
operators = ['+', '-', '*', '/']
var_assign = '='
variables = {}
def lex(line):
idx = 0
line = line.replace(" ", "")
num = ""
tok = ""
isNum = False
tokens = []
for char in line:
if char.isdigit():
isNum = True
num+=char
elif char in operators:
if isNum:
tokens.append(f"NUM:{num}")
num=""
isNum = False
tokens.append(f"OP:{char}")
elif char == "=":
try:
if line[:idx].isdigit():
return None
else:
tokens.append(f"VAR_ASSIGN:{line[:idx]}={line[idx+1:]}")
except:
return ""
elif char.isalpha() and "=" not in line:
try:
if '-' in line or '+' in line or '*' in line or '/' in line:
tokens.append(f"VAR_USE:{char}")
else:
tokens.append(f"VAR_CALL:{line}")
except:
return ""
idx+=1
if isNum:
tokens.append(f"NUM:{num}")
return tokens
def parse(tokens):
equation = ""
if not tokens:
return "Syntax error"
for tok in tokens:
if "NUM" in tok:
equation+=tok[4:]
elif "OP" in tok:
equation+=tok[3:]
elif "VAR_ASSIGN" in tok:
tok = tok[11:]
variables[tok[:tok.index('=')]] = tok[tok.index('=')+1:]
return variables[tok[:tok.index('=')]]
elif "VAR_CALL" in tok:
try:
return variables[tok[9:]]
except:
return "Variable not defined"
elif "VAR_USE" in tok:
try:
equation += variables[tok[8:]]
except:
return "Variable not defined"
try:
return eval(equation)
except:
return f"Invalid equation {equation}"
while True:
data = input("KPP>")
print(parse(lex(data)))