加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

lua – 当chunk函数返回nil时load()的行为

发布时间:2020-12-15 00:26:35 所属栏目:大数据 来源:网络整理
导读:从 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 th
从 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.

从我的测试来看,这实际上并非如此.或者说,文档至少具有误导性.

考虑这个示例脚本:

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)

输出是make_loader()返回的函数的连续调用次数,在load()放弃之前返回nil并返回一个不返回任何函数的函数.

如果要以面值取得文档,可以预期此处的输出为“1”.但是,输出为“3”.这意味着调用load()的参数,直到它在load()放弃之前返回nil三次.

另一方面,如果chunk函数立即返回一个字符串,然后在后续调用中返回nil,则只需要一个nil来停止加载:

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())

这正如我所期望的那样打印“2”.

所以我的问题是:文档错了吗?出于某种原因,这种行为是否可取?这只是load()中的一个错误吗? (看起来似乎有意,但我找不到任何解释原因的文件.)

解决方法

这是5.1中的错误.它已在5.2中得到纠正,但我们未能将修正纳入5.1.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读