解压缩 Lua 中的功能问题



我有以下unpack()函数:

function unpack(t, i)  
    i = i or 1  
    if t[i] then  
        return t[i], unpack(t, i + 1)  
    end  
end  

我现在在以下测试代码中使用它:

t = {"one", "two", "three"}  
print (unpack(t))  
print (type(unpack(t)))  
print (string.find(unpack(t), "one"))  
print (string.find(unpack(t), "two"))

其中输出:

one two three  
string  
1   3  
nil  

让我困惑的是最后一行,为什么结果nil

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

在您的示例中,string.find(unpack(t), "one")string.find(unpack(t), "two")"two""three"被丢弃,它们等效于:

string.find("one", "one")  --3

string.find("one", "two")  --nil

Lua Pil 在 5.1 下有这样的说法 - 多个结果

Lua 总是根据调用的情况调整函数的结果数。当我们调用一个函数作为语句时,Lua 会丢弃它的所有结果。当我们使用调用作为表达式时,Lua 只保留第一个结果。仅当调用是表达式列表中的最后一个(或唯一)表达式时,我们才会获得所有结果。这些列表在 Lua 中以四种结构出现:多重赋值、函数调用的参数、表构造函数和返回语句。

它给出了以下示例来帮助说明:

function foo0 () end                  -- returns no results
function foo1 () return 'a' end       -- returns 1 result
function foo2 () return 'a','b' end   -- returns 2 results
x, y = foo2(), 20      -- x='a', y=20
x, y = foo0(), 20, 30  -- x='nil', y=20, 30 is discarded

余浩的回答表明这如何具体适用于您的示例。

函数 unpack 返回乘法参数,string.find 只接受第一个参数(其余的被丢弃)。

此函数将解压缩并连接所有字符串,因此函数输出将是单个参数。

function _unpack(t,char)
    return table.concat(t,(char or " "));
end
t = {"one", "two", "three"}  
print (_unpack(t))  
print (type(_unpack(t)))  
print (string.find(_unpack(t), "one"))  
print (string.find(_unpack(t), "two"))

输出

one two three 
string 
1 3 
5 7 

最新更新