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

[partly Solved] just a quick question - Functions

Started by Dustmuz, 08 January 2015 - 11:58 AM
Dustmuz #1
Posted 08 January 2015 - 12:58 PM
hello :)/>

can i run a function inside of another function?

example

local function button(bool)
  if bool then
	automatic()
  elseif not bool then
	manual()
  end
end
Edited on 08 January 2015 - 12:30 PM
MKlegoman357 #2
Posted 08 January 2015 - 01:04 PM
Of course you can! Given that those other functions are declared then yes, you can.
Dustmuz #3
Posted 08 January 2015 - 01:07 PM
they will be :D/>

was just asking, as im making a power controller, and as you can "tell" from the function, im using a button to control it between auto and manual mode :D/>

but thanks for the quick answer :)/>
Bomb Bloke #4
Posted 08 January 2015 - 01:13 PM
Just be wary against having your automatic() / manual() functions turn around and call your button() function again.

When a function is called, the script remembers the point where the call was made from. The new function gets added to the function stack, and gets removed when it's done, at which point the script continues from where the original call was made.

But if a function doesn't end - instead calling more copies of other functions that're already in the stack, eg the function that called it or even itself - then eventually the RAM reserved for storing the stack runs out, you get a stack overflow, and as a result your script will crash!

Functions can call themselves, but the technique is not a replacement for proper while/for/repeat loops!
Edited on 08 January 2015 - 12:13 PM
Dustmuz #5
Posted 08 January 2015 - 01:26 PM
arh yeah.. forgot about that part :(/> :(/>

can i use break(automatic) or break(manual) just before i call the other function, to stop the other function from running??
or would i be better off, learning to use coroutines for this?
KingofGamesYami #6
Posted 08 January 2015 - 01:34 PM
This works:


function foo()
  return bar()
end

function bar()
  return foo()
end

…except it'll get a too long without yielding error. But you get the idea, you can use return to end the function that is running.
Bomb Bloke #7
Posted 08 January 2015 - 01:46 PM
The above method is called "tail calling" - but you're better off figuring out how to use a while loop and maybe some return statements. These threads should give you some insight.
Edited on 08 January 2015 - 12:46 PM
Dustmuz #8
Posted 08 January 2015 - 01:49 PM
will have a look at these,

Thanks Bomb :)/>
Edited on 08 January 2015 - 07:20 PM