lua-users home
lua-l archive

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


2018-07-21 9:51 GMT+02:00 Egor Skriptunoff <egor.skriptunoff@gmail.com>:
>

> Your favorite trick with "function(_ENV)" is quite dangerous.
> What would happen if some local in outer lexical scope has the same name as
> one of your globals?
>
>    local x
>    ...
>    local function fun(_ENV)
>      return x^2 + y^2 <= r^2
>    end
>
> Where "x" value would be actually read from: "_ENV.x" or upvalue "x"?
>
> This is a hard-to-find mistake.

Oh, I have three other favorite tricks.

I call it first one "semi-global variables". All upvalues that are intended to
have scope of the entire file are collected near the top of the program
with no initializer. They tend to have fairly long, descriptive names,
not just 'x'.

I call the second one "local closures". All my functions that use upvalues
needed only by themselves sit inside a do..end block in which those upvalues
are declared.

I call the third one "logical blocks". If half a page of code deserves a
comment describing what it does, one might as well put that comment
on the rest of a line starting with "do".

The result is that seeing 'local' at a place where I can't see the start of its
scope makes my eyes hurt as much as a backslash or other sigil will hurt
Marc's eyes.

I realize that these habits betray my Algol/Pascal programming past,
but at least they cost nothing.