lua-users home
lua-l archive

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


On 2012-11-18 6:53 PM, "Kevin Martin" <kev82@khn.org.uk> wrote:
>
> I've just discovered that because of the way local variables work, that the below code prints nil instead of function. It works as desired if the 'local' is removed from line 6.
>
> >      1        local f1
> >      2        local function f2()
> >      3                print(type(f1))
> >      4        end
> >      5
> >      6        local function f1()
> >      7                f2()
> >      8        end
> >      9
> >     10 f1()
>
> Now, I've got into the habit of declaring all functions as local, and I think it's messy to declare some functions local, and some with forward declarations. I've thought of a couple of solutions to this, but I don't really like any of them. (Currently putting all functions that I would declare local, in a local table instead)
>
> My best thought is that a relocal command that creates local variables only if they aren't local in the same scope level. So an attempt to relocal a variable which is an upvalue would create a new local variable e.g.
>
> > local a = 1
> > do
> >       relocal a = 2  --this creates a new variable a
> >       print(a)
> > end
> > relocal a --this does nothing as there is already an a at the current scope level
> > print(a)
>
> Would print 2 and then 1.
>
> Is this a good idea, or am I just looking at the problem the wrong way? How do other people deal with forward declarations?
>
> Thanks,
> Kevin

local f
local function g() print(f()) end
f = function() return 42 end