函数多个返回值与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

 

posted @ 2018-06-28 10:06  ghostwu  阅读(607)  评论(0编辑  收藏  举报
Copyright ©2017 ghostwu