[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Forward function declarations - relocal command
- From: Xavier Wang <weasley.wx@...>
- Date: Mon, 19 Nov 2012 09:44:36 +0800
I'm prefer using this idiom:
local f
local function g() ... end
--[[local]] function f() ... end
to tell you f is a local above.
2012/11/19 Kevin Martin <kev82@khn.org.uk>:
> 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
--
regards,
Xavier Wang.