PlutoLang/Pluto

Exports return at block end

XmiliaH opened this issue · 3 comments

Is it intended that exports in a block will cause a return when the block ends?

Looking at

local function f(extended)
    export function r1() end
    if extended then
        export function r2() end
    end
end

local t = f(true)
print(t.r1, t.r2)

I would expect a table with both, r1 and r2 to be returned but only r2 is in the table as the if block creates a new export scope and will return at the end of the if since there was an export in the body.

Yes, this is the documented behavior. The return statement is implied at the end of the block. It is mainly intended for top-level functions, but it's also useful in function bodies to push into package.preloaded.

The documentation only states

The return statement is automatically generated.

not if this happens at the end of the function or the end of a block (end of if, end of loop, end of switch).

So it does not state how my example is translated.

local function f(extended)
    local function r1() end
    if extended then
        local function r2() end
        return {r2=r2}
    end
    return {r1=r1}
end

or

local function f(extended)
    local function r1() end
    if extended then
        local function r2() end
        return {r1=r1, r2=r2}
    end
    return {r1=r1}
end

or

local function f(extended)
    local exports = {}
    local function r1() end
    exports.r1 = r1
    if extended then
        local function r2() end
        exports.r2 = r2
    end
    return exports
end

Well, it does have the example:

-- end of scope; 'return' is automatically generated

Maybe can be a bit more explicit.