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

Define sub-function before or inside its parent function? (Clarification Inside)

Started by Cainite, 03 August 2014 - 09:46 AM
Cainite #1
Posted 03 August 2014 - 11:46 AM
Sorry if the title is confusing, not sure how to phrase it exactly. Let me try to demonstrate what I mean in code.

Which of these two is better:


local function LittleFunction()
  blahblah
end

local function BigFunction
  LittleFunction()
end

OR


local function BigFunction()

  local function LittleFunction()
	blahblah
  end

  LittleFunction()
end

So is it better to:
Define LittleFunction() BEFORE BigFunction(), like in the first example…
OR
Define LittleFunction() INSIDE BigFunction(), like in the second example?

Is there other better options/methods I don't know about? And sorry if my format/layout isn't ideal, I am still very much a beginner.
Edited on 03 August 2014 - 09:57 AM
Lyqyd #2
Posted 03 August 2014 - 12:41 PM
Depends on what you're trying to do. If you only ever need to call the one function inside the other, you can define it inside the other without any issues. That does, of course, mean that it will be defined every time the outer function is called, as opposed to only being defined once, to put it simply.
theoriginalbit #3
Posted 03 August 2014 - 12:51 PM
A common thing that I do — especially if I know a function will be invoked often and don't want its anonymous functions to be defined every time — is to put it in a do block. This way it is only defined once and it is only accessible from the main function.


local bigFunc
do
  local function littleFunc()
    print("Hello world")
  end

  function bigFunc()
    littleFunc()
  end
end

bigFunc() --# works
littleFunc() --# error, 'attempt to call nil'
LeonTheMisfit #4
Posted 03 August 2014 - 06:10 PM
I was literally just reading about this because of another post and came across some performance testing information on StackOverflow. So, if you believe those performance test results and are concerned with performance, you'd be better off not using inner functions, but Lua does support it so it comes down to preference and need like so many things with programming.