函数多个返回值与unpack的用法

时间:2021-12-18 17:24:03
-- return the index of max number and himself
-- 函数可以返回多个值
function get_max( T )
local index =
local max = T[]
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(),
print( x, y ) -- a, 10 print( foo2(), ) -- a 100 t = { foo2(), } -- a, 20
for i, v in ipairs( t ) do
io.write( v, "\t" ) -- a, 20
end
io.write( "\n" )
Lua 5.1.  Copyright (C) - Lua.org, PUC-Rio
> unpack( { , , } )
> print( unpack{ , , } ) > a, b = unpack{ , , }
> print( a, b ) > s, e = string.find( "hello,ghostwu", "ghost" ); print( s, e ) > s, e = string.find( unpack{ "hello,ghostwu", "ghost" } ) ; print( s, e )