解压缩功能问题在Lua

sii*_*kee 3 lua lua-table

我有以下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呢?

Yu *_*Hao 5

如果函数返回多个值,除非将其用作最后一个参数,否则仅采用第一个值.

在你的榜样,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)