lua-users home
lua-l archive

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


2012/11/18 Kevin Martin <kev82@khn.org.uk>:
> Is this a good idea, or am I just looking at the problem the wrong way? How do other people deal with forward declarations?

My main objection against adding new keywords to solve your problem is
that the local variables that may or may not be shadowed are always in
the same chunk as the one you're currently editing. They're called
upvalues because you just have to look up a little. So IMHO it's not a
big deal, merely an inconvenience, and as such shouldn't require a
modification of the language.


2012/11/19 Kevin Martin <kev82@khn.org.uk>:
> On 18 Nov 2012, at 23:58, Rena wrote:
>
> local f
> local function g() print(f()) end
> f = function() return 42 end
>
> Yes, it's pretty trivial in cases like that, but my use case is a bit more
> complicated. That is actually what I have been doing, and what caught me out
> today, and prompted by to email was when I did this - admittedly without
> thinking:
>
> local f
> local function g()
> --calls f
> end
>
> local f
> local function h()
> --also calls f
> end
>
> function f()
> --does something
> end
>
>
> My thoughts were (roughly in order)
>
> 1) Get rid of the 'local f' above the definition of h
> Problem - things would break if I ever moved h above g.
>
> 2) Creating all required forward declarations at the top of the block
> Problem - No good if a function that doesn't require a forward declaration
> now, requires one later (in a couple of months when someone comes back to
> the code)
>
> 3) Create forward declarations for every function
> Minor Problem - at the function definition, don't know whether it's a local
> function or not
> Minor Problem - Have to modify two different code sites to create a function
>
> 4) Put all local functions in a local table
> Minor Problem - Speed
> Minor Problem - Many levels of nested scope would require well named tables
>
> 5) relocal command
> Problem - Requires parser modification
>
> I really don't like 1 and 2, especially as it may not be me coming back to
> the code. I didn't think there was much between 3 and 4, but I felt 4 was
> cleaner - which is what I've coded for now.

Note that the problem only arise in recursive code, where f needs to
call both g and h. Otherwise you can simply define f before the
functions needing it. In my (arguably limited) experience that is not
very common, not that many code needs recursion. And when you do need
it, you need to take special care anyway, so your solution 2 looks
perfectly acceptable to me.