DEV Community

sma
sma

Posted on • Updated on

Lets build a simple interpreter from scratch in python, pt.05: Defining variables

In this post we are defining variables and using them:

class Interpreter:

    # Modified constructor: scope is list of dicts
    # First dict holds global variables, 
    # Last dict holds called function's scope variables

    def __init__(self):
        self.scope=[{}]

    # ....(previous code).... 

    # When we call Set we always create or update variable
    # in last scope: 

    def Set(self,xs):
        _, key, val = xs
        self.scope[-1][key] = self.eval(val)

    # When we call Get we first look into last scope(function scope),
    # if variable is not found then we look into first scope(globals)    
    def Get(self,xs):
        _, var = xs
        if var in self.scope[-1]:
            return self.scope[-1][var]
        elif var in self.scope[0]:
            return self.scope[0][var]
        raise Exception("error: variable not found: "+var)


code=[

    ["Set","answer",  ["Mul",6, 7],  ],
    ["Print", "Answer is: ", ["Get", "answer"] ]
]

interpreter=Interpreter()

interpreter.run(code)
Enter fullscreen mode Exit fullscreen mode

Output:

Answer is: 42
Enter fullscreen mode Exit fullscreen mode

Part 6: While loop

Top comments (0)