lua-users home
lua-l archive

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


I would usually use a local function to clean up code that way in
non-performance critical code. It's still less efficient though, both
syntactically (adds another indentation level, requires a wrapping
function) and in terms of runtime / garbage created - particularly if a
tail call is not possible since (1) the function needs to be closed
again and (2) upvalues are less efficient than locals.

But in principle I agree, functions fully suffice. Take this one step
further and you're only using Scheme and lambdas everywhere, because in
fact tail calls already suffice for looping. It's a tradeoff between a
minimalistic language and comfortable control flow statements. Adding
loop naming like Java or Go isn't necessary though. FWIW, Go has proper
closure support and newer Java versions also have somewhat decent
support (both languages don't strive to be as minimalistic as Lua though).

I definitely prefer named loops / goto + label / function + return to
exit multiple loops over the proposed break with a level, which is
relative to the current loop nesting depth (ugh). Imagine somebody
adding another inner loop: Suddenly the break/continue would refer to
the wrong loop!

On 29.07.22 09:20, Francisco Olarte wrote:
Sean:

On Fri, 29 Jul 2022 at 04:10, Sean Conner <sean@conman.org> wrote:
   If I'm doing this, then I would restructure the code to be:
         -- existing code
         local function foo()
           for ...
             for ...
               for ...
                 if somecondition then
                   return
                 end
               end
             end
           end
         end

         foo()
That's a nice usage of local functions....

   I would do the same to make up for the lack of continue:

         local function foo()
           while somecondition do
             ...
             if somecondition then
               return foo() -- my "continue" is here
             end
             ..
           end
         end
         foo()
... and tail calls ( I use that a lot, but mainly as
structured-uber-gotos, to implement flow-diagram like things ). Color
me impressed, I'm too used to other languages to think of it, but I'm
gonna start calling it "the Connerian transform" and I know a couple
places where it would fit in my code.

   Remember, Lua can have nested functions.
Although I routinely use them, with their upvalue capturing ability,
as callbacks I have never thought of that, local functions can treat
locals as a kind of "globals for this one invocation". I assume it is
because when I do that refactoring in, say, C++, I have to pass in-out
all the local values and normally I only have needs for long
breaks/continues/gotos in functions with tons of state. Last one looks
Lispy.

Francisco Olarte.