函式多個返回值與unpack的用法
阿新 • • 發佈:2019-01-17
-- 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 endreturn 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 )