我有以下unpack()
功能:
function unpack(t, i)
i = i or 1
if t[i] then
return t[i], unpack(t, i + 1)
end
end
Run Code Online (Sandbox Code Playgroud)
我现在在以下测试代码中使用它:
t = {"one", "two", "three"}
print (unpack(t))
print (type(unpack(t)))
print (string.find(unpack(t), "one"))
print (string.find(unpack(t), "two"))
Run Code Online (Sandbox Code Playgroud)
哪个输出:
one two three
string
1 3
nil
Run Code Online (Sandbox Code Playgroud)
令我困惑的是最后一行,为什么会有结果nil
呢?
如果函数返回多个值,除非将其用作最后一个参数,否则仅采用第一个值.
在你的榜样,string.find(unpack(t), "one")
并且string.find(unpack(t), "two")
,"two"
和"three"
被丢弃,它们等同于:
string.find("one", "one") --3
Run Code Online (Sandbox Code Playgroud)
和
string.find("one", "two") --nil
Run Code Online (Sandbox Code Playgroud)