Why do people put local functions outside of a main function?

To further explain what I mean, sometimes in modules I see this:

local function generic_maths_function(x)
    -- do stuff
end

function module.doSomething()
    return generic_maths_function(math.pi * 2) --tau
end

Rather than:



function module.doSomething()
    local function generic_maths_function(x)
        -- do stuff
    end

    return generic_maths_function(math.pi * 2) --tau
end

Is this some random micro-optimisation or is this for aesthetics?

I would like to listen to your replies below, thanks for reading.

Generally this is done for re-usability inside of their code. If they only use this function once, then there was no purpose in creating it unless it is intended to be used again at a later date.

Basically, this is either a mistake on the creator – in that they shouldn’t have created this function at all, or it is intended for future re-usability.

This, of course, assumes that this function has only been used once. If it is used multiple times in the same script, it is for the purpose of re-usability and is done so that multiple functions can access the same block of code.

2 Likes

Even in modules with one method/constructor I sometimes see the author putting functions (in this case an arithmetic function) outside of the function like what was shown above.

Thanks for replying, I’ll mark it as a solution.

1 Like

It’s standard and proper practice to put your functions at the root scope if they don’t require some upvalue context to work. It tends to be more efficient and often more readable.

1 Like