简体   繁体   中英

unpack function issue in Lua

I have the following unpack() function:

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

I now use it in the following test code:

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

which outputs:

one two three  
string  
1   3  
nil  

What puzzles me is the last line, why is the result nil ?

If a function returns multiple values, unless it's used as the last parameter, only the first value is taken.

In your example, string.find(unpack(t), "one") and string.find(unpack(t), "two") , "two" and "three" are thrown away, they are equivalent to:

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

and

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

Lua Pil has this to say under 5.1 - Multiple Results :

Lua always adjusts the number of results from a function to the circumstances of the call. When we call a function as a statement, Lua discards all of its results. When we use a call as an expression, Lua keeps only the first result. We get all results only when the call is the last (or the only) expression in a list of expressions . These lists appear in four constructions in Lua: multiple assignment, arguments to function calls, table constructors, and return statements.

It gives the following example to help illustrate:

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

Yu Hao's answer shows how this applies specifically to your example.

The function unpack returns multiply parameters, string.find takes the first parameters only (the rest are discarded).

This function will unpack and concatenate all strings, so the function output will be a single parameter.

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

output

one two three 
string 
1 3 
5 7 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM