Made it possible to access variables down the stack

This commit is contained in:
Lukasz Baldyga committed 2020-12-03 14:20:01 +00:00
1 parent 07b7e86a63
commit c3f1c82395
1 file changed
+21 -14
@@ -16,8 +16,9 @@ namespace Advanced_Software_Engineering.Verbs.Value {
SetStack(0); SetStack(0);
} }
public void SetStack(int stack) { private void SetStack(int stack) {
currentStack = stack < 0 ? 0 : stack; if (stack < 0) throw new Exception("Stack cannot be less than 0");
if (!Variables.ContainsKey(stack)) Variables.Add(currentStack, new Dictionary<string, IValue>()); if (!Variables.ContainsKey(stack)) Variables.Add(currentStack, new Dictionary<string, IValue>());
} }
@@ -34,36 +35,42 @@ namespace Advanced_Software_Engineering.Verbs.Value {
} }
} }
public void SetVariable(string name, int stack, IValue value) { private void SetVariable(string name, int stack, IValue value) {
if (stack == 0) Variables[stack][name] = value; for (int internalStack = stack; internalStack >= 0; internalStack--) {
else { if (value == null || CheckVariableExists(name, internalStack)) {
if (CheckVariableExists(name, stack)) Variables[stack][name] = value; Variables[internalStack][name] = value;
else if (CheckVariableExists(name, 0)) Variables[0][name] = value; return;
else Variables[stack][name] = value; }
} }
Variables[stack][name] = value;
} }
public void SetVariable(string name, IValue value) { public void SetVariable(string name, IValue value) {
SetVariable(name, currentStack, value); SetVariable(name, currentStack, value);
} }
public IValue GetVariable(string name, int stack) { private IValue GetVariable(string name, int stack) {
return Variables[stack][name]; return Variables[stack][name];
} }
public IValue GetVariable(string name) { public IValue GetVariable(string name) {
if (currentStack > 0 && CheckVariableExists(name, currentStack)) return GetVariable(name, currentStack); for (int stack = currentStack; stack >= 0; stack--) {
else if (CheckVariableExists(name, 0)) return GetVariable(name, 0); if (CheckVariableExists(name, stack)) return GetVariable(name, stack);
else throw new Exception("Cannot find variable " + name); }
throw new Exception("Cannot find variable " + name);
} }
public bool CheckVariableExists(string name, int stack) { private bool CheckVariableExists(string name, int stack) {
if (name == null) return false; if (name == null) return false;
return Variables[stack].ContainsKey(name); return Variables[stack].ContainsKey(name);
} }
public bool CheckVariableExists(string name) { public bool CheckVariableExists(string name) {
return CheckVariableExists(name, currentStack) || CheckVariableExists(name, 0); if (name == null) return false;
for (int stack = currentStack; stack >= 0; stack--) {
if (CheckVariableExists(name, stack)) return true;
}
return false;
} }
} }
} }