Search code examples
luascope

In Lua, is there a difference between local functions declared with and without the "local" keyword?


Preface: As far as I can see, the docs on the website don't really speak to this, and I haven't found anyone else even asking the question, so I'm pretty sure these two forms are identical, but I want know if anyone knows for certain.

Given this Lua code:

function f()
    function a() ... end
    local function b() ... end
    ...
end

Is there any functional difference between a() and b()? I'm speaking in terms of performance, access, caveats, anything at all. Like, in the end, do they both have exactly the same underlying representation at runtime?

I suspect there isn't any difference, but I'm not sure, and that bugs me. I know a() is scoped to the enclosing function f(), but I'm not sure if that truly makes it a local variable in terms of how things function under the hood. With b(), I can be certain.

We know from the official docs that my definition of b() above is syntactic sugar for this:

    local b
    b = function() ... end

I'm tempted to believe that, even without the local keyword in my definition, the final, de-sugared definition of a() would also follow exactly that format, including the local a part.

I just feel like I can't assume this.


Solution

  • function a() end in your code block assigns global a when the function is ran*, while b remains local to the function.

    Perhaps this code segment will illustrate things better:

    function f()
        function a() end
        local function b() end
    end
    print(a, b) -- nil, nil
    f()
    print(a, b) -- function: 0xdeadbeef, nil
    

    So to avoid polluting the global environment, you should still use local inside of a function.


    * Unless you declared a local at some other scope above f, in which case a will keep its scoping.