I'm trying to make an interpreter for a toy language for learning more about how they work and so on, I'm now stuck on retrieving stored variables.
At first I used a dictionary where both the key and value is a string
type. But after running in to the problem I made numerous attempts to solve it. I thought the Dictionary
was the problem and made my own class, which didn't work any better so I'm back to the dictionary.
I have a text file called "Test.txt"
where the code is written in and then read from by the lexer. The lexer makes tokens which then gets passed to the parser and so on.
// '%' for declaring a variable
// that can be either a string and a number
// Code form "Test.txt"
%var = 100
print %var
//the assignment works fine, but the printing doesn't.
the lexer makes a string
token out of the variable that looks like this: VAR:%var
which I then send to the parser.
Then we have the DoPRINT
method which will print a token that is given from the parser, This isn't stable. which I will work on after the variable retrieving works. Then we have the dictionary called Symbols
with corresponding methods for adding and retrieving
private void AssignVAR(String VarName, String VarValue)
{
Symbols[VarName] = VarValue;
}
private String GetVAR(String VarName)
{
if(Symbols.ContainsKey(VarName))
return Symbols[VarName];
else
return "Undefined Variable: " + VarName;
}
private void DoPRINT(String ToPrint)
{
if(ToPrint.Substring(0, 6) == "STRING")
// initially = 'STRING:"<text>"'
Console.WriteLine(ToPrint.Substring(8, ToPrint.Length - 9));
else if(ToPrint.Substring(0, 3) == "NUM")
// initially = 'NUM:<number>'
Console.WriteLine(ToPrint.Substring(4));
else if(ToPrint.Substring(0, 4) == "EXPR")
// initially = 'EXPR:<expression>'
Console.WriteLine(Core.EvaluateEXPR(ToPrint.Substring(5)).ToString());
else if(ToPrint.Substring(0, 3) == "VAR")
// initially = "VAR:%var"
// when the "Symbols" are printed out
// the name is "%var" which is the same
// as the substring below
Console.WriteLine(GetVAR(ToPrint.Substring(4)));
}
I want the output to be what I assigned the variable to, "100"
but when executing I only get "Undefined Variable: %var"
even though if I print out the content of Symbols I get %var
and if I print out what the GetVAR()
function gets as input, it is also %var
why is it then returning "Undefined Variable: %var"
It turned out that assigning using a method and the retrieving also using a method does something that sort of corrupts the accessible variable.
Changing so that the variable assignment happens in the main function of the parser rather than using a method for it worked fine, and getting the value with a function works perfectly. No idea if this has to do with movement of the data while the function is being executed. But it works, but i can't seem to figure out why.