zoukankan      html  css  js  c++  java
  • 函数多个返回值与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, "	" ) -- a, 20
    end
    io.write( "
    " )
    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
  • 相关阅读:
    Spring注解驱动开发(二)--组件注入
    Spring注解驱动开发(一)--项目搭建
    Font "微软雅黑" is not available to the JVM. See the Javadoc for more details.
    idea下远程debug调试
    JasperReport生成PDF文件
    Java获取系统属性和环境变量
    oracle date change
    winform webbrowser flash显示
    uploadify参数
    对COM 组件的调用返回了错误 HRESULT E_FAIL
  • 原文地址:https://www.cnblogs.com/ghostwu/p/9237290.html
Copyright © 2011-2022 走看看