Share via

Empty stack error

78005650 1 Reputation point
2022-02-20T13:30:25.68+00:00

Hi everyone, I'm having trouble understanding an odd behavior in my small basic code.

So i would like to share 3 examples of code and ask why does the last one produces an error.

Case 1:

Stack.PushValue("a",1)
Stack.PushValue("a",2)
Stack.PushValue("a","result")

v1 = Stack.PopValue("a")
v2 = Stack.PopValue("a")
v3 = Stack.PopValue("a")

test[v3][v2] = v1

TextWindow.WriteLine(test[1][2]) ' -> "result". Works fine

Case 2:

Stack.PushValue("a",1)
Stack.PushValue("a","result")

test[Stack.PopValue("a")] = Stack.PopValue("a")
TextWindow.WriteLine(test[1]) ' -> "result". Works fine

Case 3:

Stack.PushValue("a",1)
Stack.PushValue("a",2)
Stack.PushValue("a","result")

test[Stack.PopValue("a")][Stack.PopValue("a")] = Stack.PopValue("a") ' -> Throws an error: Stack is empty
TextWindow.WriteLine(test[1][2])

Thanks,

Developer technologies | Small BASIC
Developer technologies | Small BASIC

A programming language created by Microsoft that serves a stepping stone for beginners from block-based coding languages to more complex text-based languages.


2 answers

Sort by: Most helpful
  1. Scout 541 Reputation points
    2022-02-20T18:33:42.123+00:00

    It seems that the interpreter is working from right to left and the "=" is grabbing an element.

     case4:
        Stack.PushValue("n",1)
        Stack.PushValue("n",2)
        Stack.PushValue("n",3)
        Stack.PushValue("n",4)
        Stack.PushValue("n","result4")
        testn[Stack.PopValue("n")][Stack.PopValue("n")] = Stack.PopValue("n")     
        TextWindow.WriteLine(testn[2][3]) ' -> Prints "result" '
        TextWindow.WriteLine("Stackcount: " + Stack.GetCount("n")) 
        TextWindow.WriteLine("and the element is: " + Stack.PopValue("n")) ' ->
        TextWindow.WriteLine("Stackcount: " + Stack.GetCount("n")) ' -> 
    

    Conclusion:
    When writing to a multidimensional array and using at least one STACK.PopValue() in the index, the stack counter is erroneously decremented before use.


  2. WhTurner 1,616 Reputation points
    2022-02-20T14:30:29.133+00:00

    It has something to do with the use of the Pop in an array index. See the output of:
    Stack.PushValue("a",1)
    Stack.PushValue("a",2)
    Stack.PushValue("a",3)
    Stack.PushValue("a","result")
    TextWindow.WriteLine(Stack.GetCount("a"))
    res = Stack.PopValue("a")
    two=Stack.PopValue("a")
    TextWindow.WriteLine(Stack.GetCount("a"))
    test[Stack.PopValue("a")][two] = res
    TextWindow.WriteLine(Stack.GetCount("a"))
    TextWindow.WriteLine(test[1][2]) ' -> Prints nothing (empty)
    TextWindow.WriteLine(test[1][3]) ' -> Prints "result" '
    TextWindow.WriteLine(Stack.GetCount("a")) ' -> Prints 0. What happend to value 3 :)

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.