Re: Readability question.
Francisco Olarte <[email protected]> Fri, 5 Jun 2026 20:15:43 +0200
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <CA+bJJbz802E5Xva3XYqegTe5W6fye6yG+PDZs2gTpwj=DE+t2Q@mail.gmail.com> |
Hello Martin. On Fri, 5 Jun 2026 at 19:06, 'Martin Eden' via lua-l <[email protected]> wrote: > On 2026-06-05 16:11, Francisco Olarte wrote: > It still bad for me: "Para gustos los colores", we say around here. But I'll try to spain. > if a == nil then > return b > end > if b == nil then > return a > end > We're testing for one thing and returning other. Which is typical when testing for "badness", I read this as "if a is bad, use b, if b is bad, use a, if both are good, use both". It lacks an "if both are bad" at the start, which I could use too, but it is not relevant in this case. In fact every usage of 'return a and b', 'return a and b or c', even 'return a or b' depending on how yoou look at it, tests one thing and return ( or uses if you are doing a parameter pass or assignment ) other. For the full version I would use if (a==nil) then if (b==nil) then return --nothing. else return b end else -- elseif would avoid a nesting level, but spoil symmetry, as would collapsing elses above. if (b==nil) then return a else return f(a,b) --both end end Anyway, the way I code it reflects a bit my assembly origins, and my distate for too much nesting. For a C-style block delimiters I would probably code the first two ifs as one-liner, but with then-end style I nearly never use it. Now that I see it I may switch to if a==nil then if b==nil then return else return b end end I tested some, and liked how the byte code reflected the source style, this is why I used that. But I have to stop playing with byte code or I will write byte-assembler just to scratch the itch caused by the unsuppressed redundant function end returns. > I think I would settle at > > local function safe_calc(f, a, b) > return > function(a, b) > if not (a and b) then return (a or b) end > return f(a, b) > end > end Yep, classical else avoidance, one liner for simple guard conditions. I do it that a lot, for speed sometimes ( I have a hard time remembering I'm not on a 8080 anymore ), but, lacking an optimizer, this evaluates too much. Granted, lua seems to not have an opcode for ==nil and makes a constant and to hold it, but I like how my version compiles, and the nearly minimal set of ops. But they are all the same at the end. Francisco Olarte. -- You received this message because you are subscribed to the Google Groups "lua-l" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion visit https://groups.google.com/d/msgid/lua-l/CA%2BbJJbz802E5Xva3XYqegTe5W6fye6yG%2BPDZs2gTpwj%3DDE%2Bt2Q%40mail.gmail.com.