lua-users home
lua-l archive

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




On Tue, Jul 23, 2019 at 1:49 PM Hugo Musso Gualandi <hgualandi@inf.puc-rio.br> wrote:



>a benefit, as there is literally not a single place in Lua where an
>assignment _expression_ would save more than a single line of code.

One place where Lua has similar syntax to Pyhon is if-elseif statements. Assignment expressions let you avoid extra nesting here.

    if x := foo:match(p1) then
        -- A
    elseif x := foo:match(p2) then
        -- B
    elseif x := foo:match(p3) then
        -- C
    end

-- vs

    local x = foo:match(p1)
    if x then
        -- A
    else
        x = foo:match(p2)
        if x then
            -- B
        else
            x = foo:match(p3)
            if x then
                -- C
            end
        end
    end
end

That's a valid point. I hadn't considered that specific example, although I would write it differently anyway:

local x = foo:match(p1)
if x then
  -- A
  return
end

x = foo:match(p2)
if x then
  -- B
  return
end

x = foo:match(p3)
if x then
  -- C
  return
end

(Replace "return" with whatever other control structure is appropriate for the context, of course. break is another good choice.)

I suppose by a strict interpretation this saves two lines per assignment _expression_ instead of just the one that I had asserted, but there's a fairly good chance that the return statement would have been there anyway, if it returned a value.

Though it should be noted that in your example you still need a "local x" at the top to preserve the same semantics.

/s/ Adam