user3838351
user3838351

Reputation: 61

Lua: is a function closure a local function?

Suppose I have the following Lua code:

function f(v)
    function g()
        return v * v
    end
    return g
end

Obviously, 'g' in the above Lua code forms a closure. What I am wondering is: is 'g' a "local" function by default?

Do I have to explicitly add the 'local' keyword before 'function g()' to make 'g' truly local? If without explicit 'local', and if 'g' thus is a "global", how would anyone access 'g' from an outer scope? I am suspicious that I could do "f.g" in order to access 'g' in this context.

If 'g' is "local" by default, then what's the point of allowing "local" to be prefixing the function definition (closure) inside a function?

Upvotes: 2

Views: 780

Answers (1)

user3838351
user3838351

Reputation: 61

Alrighty, I think I've got an answer by myself:

Without prefixing the closure 'g' with the 'local' keyword, 'g' is actually a global! Because function declaration essentially an assignment of an anonymous function to a named variable in Lua! So the closure definition in the above code is equivalent to:

function f(v)
    g = function()
        return v * v
    end
    return g
end

And according to Lua variable scoping rule, any variable not explicitly tagged with 'local' is a global, so basically 'g' becomes a global function, and I believe anyone can just call module.g() without any problems!

Prefixing 'local' to 'g' makes it a true local variable that there is no way to access it accidentally outside 'f'.

Upvotes: 4

Related Questions