lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 2012-09-29 3:43 PM, "Mark Gabby" <mwgabby@gmail.com> wrote:
>
> Currently, it's possible to forward-declare a local function in Lua like so:
>
> local forward_declared_function
>
> local function calling_function()
>     print "calling function"
>     forward_declared_function()
> end
>
> forward_declared_function = function()
>     print "forward declared function"
> end
>
> This looks kinda ugly, though. I'd like it better if Lua supported this:
>
> local forward_declared_function
>
> local function calling_function()
>     print "calling function"
>     forward_declared_function()
> end
>
> local function forward_declared_function()
>     print "forward declared function"
> end
>
> With Lua 5.2.1, if you call calling_function() after defining the first, it prints:
> calling function
> forward declared function
>
> but if you call it after the second, it prints, then fails:
>
> calling function
> lua: debug.lua:26: attempt to call upvalue 'forward_declared_function' (a nil value)
> stack traceback:
>     debug.lua:26: in function 'calling_function'
>     debug.lua:33: in main chunk
>     [C]: in ?
>
> Why does the first work, but not the second?

I believe it's because the "local function" statement declares a new local variable, shadowing the old one. Code before it is still referring to the old one which never gets set.