Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of load() when chunk function returns nil

Tags:

lua

lua-5.1

From the Lua 5.1 documentation for load():

Loads a chunk using function func to get its pieces. Each call to func must return a string that concatenates with previous results. A return of an empty string, nil, or no value signals the end of the chunk.

From my testing, this is not actually true. Or, rather, the documentation is at a minimum misleading.

Consider this example script:

function make_loader(return_at)
    local x = 0

    return function()
        x = x + 1

        if x == return_at then return 'return true' end

        return nil
    end
end

x = 0
repeat
    x = x + 1
until not load(make_loader(x))()

print(x)

The output is the number of successive calls to the function returned by make_loader() that returned nil before load() gives up and returns a function returning nothing.

One would expect the output here to be "1" if the documentation is to be taken at face value. However, the output is "3". This implies that the argument to load() is called until it returns nil three times before load() gives up.

On the other hand, if the chunk function returns a string immediately and then nil on subsequent calls, it only takes one nil to stop loading:

function make_loader()
    local x = 0

    return {
        fn=function()
            x = x + 1

            if x == 1 then return 'return true' end

            return nil
        end,
        get_x=function() return x end
    }
end

loader = make_loader()
load(loader.fn)
print(loader.get_x())

This prints "2" as I would expect.

So my question is: is the documentation wrong? Is this behavior desirable for some reason? Is this simply a bug in load()? (It seems to appear intentional, but I cannot find any documentation explaining why.)

like image 978
cdhowie Avatar asked Jun 05 '13 20:06

cdhowie


1 Answers

This is a bug in 5.1. It has been corrected in 5.2, but we failed to incorporate the correction in 5.1.

like image 109
Roberto Ierusalimschy Avatar answered Sep 23 '22 13:09

Roberto Ierusalimschy