使用函数加载一个块
func来获取它的碎片.每次调用func必须返回一个与先前结果连接的字符串.返回空字符串,nil或no值表示块的结尾.
从我的测试来看,这实际上并非如此.或者说,文档至少具有误导性.
考虑这个示例脚本:
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)
Run Code Online (Sandbox Code Playgroud)
输出是连续调用返回的函数的数量make_loader()是返回nil之前load()放弃,并返回一个函数返回什么.
如果要以面值取得文档,可以预期此处的输出为"1".但是,输出为"3".这意味着调用to将load()被调用,直到它返回nil 三次才load()放弃.
另一方面,如果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())
Run Code Online (Sandbox Code Playgroud)
这正如我所期望的那样打印"2".
所以我的问题是:文档错了吗?出于某种原因,这种行为是否可取?这只是一个错误load()吗?(看起来似乎有意,但我找不到任何解释原因的文件.)
小智 6
This is a bug in 5.1. It has been corrected in 5.2, but we failed to incorporate the correction in 5.1.