Main Menu

Stack overflow problems

Started by Endermangue, Feb 14, 2023, 06:29 PM

Previous topic - Next topic
Hi, i'm trying to do a program that let me start a generator if the battery doesn't have energy, and that it's gonna stop it if the battery has energy, i used recursion to let the computer check the battery energy level, but it end always in stack overflow.

local cube = peripheral.wrap("left")
local flag=true                           //i use this flag because otherwise it spam to activate the generator

function Check()
      while cube.getEnergy() > 200000000 do
            Check()                        //if the generator has energy then recheck
      end
      if flag == true then                 //if it doesn't have energy activate the generator
            redstone.setOutput("right", true)
            sleep(5)
            redstone.setOutput("right", false)
            sleep(5)
            flag = false
      end
end

print((cube.getEnergy()*0.4)/1000000 .." MRF")            //this just print the enrgy
Check()
while true do
      if cube.getEnergy()>220000000 then                  /if it has energy then turn off the generator
            redstone.setOutput("right", true)
            sleep(5)
            redstone.setOutput("right"), false)
            flag = true
            Check()                                       //then check if it has energy
      else                                                //this else is pretty useless i think
            sleep(5)
      end
end


SuperNiceJohn

The reason that the Stack Overflow occurs is because there's a recursive function call that exceeds the number of recursive calls possible. That is to say, the function 'Check()' calls itself so many times that the 'computer' runs out of memory to keep track of all the function calls/state.
The cause in this particular case is:
function Check()
   while cube.getEnergy() > 200000000 do // it's not the while loop!
      Check() // the call which recurses infinitely
   end
which will continuously make a new call to Check() when 'cube.getEnergy()' is greater than 200000000.
While computers will happily do the same task over and over, the problem with recursion is that they have to keep track of all the previous function calls, which eventually becomes too much.

For this particular problem I think your while-loop will be plenty to check for energy levels, along with some variable to keep track of whether the generator is on or off, provided that it toggles on/off whenever it sees a redstone pulse.

Hope it helped, recursive functions are fun to use but can be tricky to run through in your head! :)
I have ComputerCraft to thank for my interest in programming :)