This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
H4X0RZ's profile picture

Recursive function calling?

Started by H4X0RZ, 19 June 2013 - 03:22 PM
H4X0RZ #1
Posted 19 June 2013 - 05:22 PM
I know this is recursive function calling and ends up with a stack overflow:

function a()
a()
end
a()

But is this recursive function calling too?

--Yes it's not a local function because this isn't my real code
function mainMenu()
term.clear()
term.setCursorPos(1,1)
print("1. Option\n2. Option\n")
write("select:")
answer = read()
if answer == "1" then
--Some kind like this ^
if subAnswer1 == "back" then
mainMenu()
end
end
end

I really need help, because I don't want a stack overflow in my program!

Thx for reading
-Freack100-
Sammich Lord #2
Posted 19 June 2013 - 05:35 PM
It will stack overflow if subAnswer1 is 'back' 256 times or so in a row.
H4X0RZ #3
Posted 19 June 2013 - 05:44 PM
Is there a wayto "delete" the stack?
Lyqyd #4
Posted 19 June 2013 - 05:51 PM
Why don't you just use loops correctly instead?
H4X0RZ #5
Posted 19 June 2013 - 05:55 PM
Why don't you just use loops correctly instead?
How?
I don't understand it yet :(/>
Lyqyd #6
Posted 19 June 2013 - 06:07 PM
Replace `function mainMenu()` with `while true do` and remove `mainMenu()` (and the whole if statement below, I suppose).

Really, menus should be structured thus:


function aMenu()
  --clear screen and draw menu
  while true do
    --event loop to handle menu navigation
    --if enter key
      --if current_selection is a submenu
        result = doASubMenu()
        if result ~= subMenusBackEntry then
          return current_selection .. ", " .. result
        end
      else
        return current_selection
      end
    end
  end
end

--submenus structured the exact same way, they should always return their results, never call the main menu.

menu_result = aMenu()
0099 #7
Posted 01 July 2013 - 10:37 AM
Proper tail calls! I always use it in menu system. Just write

return mainMenu()
instead of

mainMenu()
Lua will destroy previous part of stack if it can see it has nothing else to do (next action is return). More: http://www.lua.org/pil/6.3.html
Lyqyd #8
Posted 01 July 2013 - 12:39 PM
Tail calls are not an excuse to fail to structure your program properly.