Jump to content




Recursive function calling?


  • You cannot reply to this topic
7 replies to this topic

#1 H4X0RZ

  • Members
  • 1,315 posts
  • LocationGermany

Posted 19 June 2013 - 04: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-

#2 Sammich Lord

    IRC Addict

  • Members
  • 1,212 posts
  • LocationThe Sammich Kingdom

Posted 19 June 2013 - 04:35 PM

It will stack overflow if subAnswer1 is 'back' 256 times or so in a row.

#3 H4X0RZ

  • Members
  • 1,315 posts
  • LocationGermany

Posted 19 June 2013 - 04:44 PM

Is there a wayto "delete" the stack?

#4 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 19 June 2013 - 04:51 PM

Why don't you just use loops correctly instead?

#5 H4X0RZ

  • Members
  • 1,315 posts
  • LocationGermany

Posted 19 June 2013 - 04:55 PM

View PostLyqyd, on 19 June 2013 - 04:51 PM, said:

Why don't you just use loops correctly instead?
How?
I don't understand it yet :(

#6 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 19 June 2013 - 05: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()


#7 0099

  • Members
  • 52 posts

Posted 01 July 2013 - 09: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

#8 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 01 July 2013 - 11:39 AM

Tail calls are not an excuse to fail to structure your program properly.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users