Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unpack function issue in Lua

Tags:

lua

lua-table

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?

like image 972
siikee Avatar asked Feb 23 '26 00:02

siikee


1 Answers

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
like image 110
Yu Hao Avatar answered Feb 26 '26 01:02

Yu Hao