函數多個返回值與unpack的用法

-- return the index of max number and himself
-- 函數能夠返回多個值
function get_max( T )
        local index = 1
        local max = T[1]
        for i, v in ipairs( T ) do
                if v > max then
                        max = v
                        index = i
                end
        end
        return index, max
end

-- 若是函數的參數爲表或者字符串 能夠省略小括號
-- index, value = get_max{ 10, 1, -1, 0, 3, 20, 9, 200, 8, 2, 4 }
-- print( index, value )


-- 返回一個子字符串的開始位置和結束位置

function get_pos( str, substr )
        s, e = string.find( str, substr )
        return s, e
end

s, e = get_pos( "Hello,ghostwu,how are you?", "ghostwu" )
print( '字符串的開始位置' .. s .. ', 結束位置爲:' .. e )

 

function foo() end
function foo1() return 'a' end
function foo2() return 'a', 'b' end

-- 按位置接收, 多餘的被丟棄
x, y = foo2()
print( x, y ) -- a, b
x, y = foo1()
print( x, y ) -- a, nil
x, y = foo()
print( x, y ) -- nil, nil

-- 函數調用表達式不是最後一個表達式, 只返回一個值
x, y = foo2(), 10
print( x, y ) -- a, 10

print( foo2(), 100 ) -- a 100

t = { foo2(), 20 } -- a, 20
for i, v in ipairs( t ) do
        io.write( v, "\t" ) -- a, 20
end
io.write( "\n" )
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> unpack( { 10, 20, 30 } )
> print( unpack{ 10, 20, 30 } )
10      20      30
> a, b = unpack{ 10, 20, 30 }
> print( a, b )
10      20
> s, e = string.find( "hello,ghostwu", "ghost" ); print( s, e )
7       11
> s, e = string.find( unpack{ "hello,ghostwu", "ghost" } ) ; print( s, e )
7       11
相關文章
相關標籤/搜索