iambic
V2EX  ›  问与答

请问一个 lua 的问题

  •  
  •   iambic · Aug 25, 2015 · 2720 views
    This topic created in 3907 days ago, the information mentioned may be changed or developed.
    t = {1,nil,nil,2}
    print (#t )
    
    t = {1,2,nil,nil}
    print (#t )
    
    t = {nil,nil,1,2}
    print (#t )
    
    t = {1,nil,2,nil}
    print (#t )
    

    输出结果是

    4
    2
    4
    1

    我对 nil 的理解是, table 里边,只要出现 nil ,后边的就不会在计入长度了,之前的 key ,如果没有显示指定,默认从 1 开始,从而上边四个输出应该是 1,2,0,1

    不知道为什么结果和预期的不一样

    5 replies    2015-08-25 12:34:31 +08:00
    closeid
        1
    closeid  
       Aug 25, 2015
    mark 看结果。
    whahugao
        2
    whahugao  
       Aug 25, 2015
    貌似没什么规律可循。建议不要用#来获取 table 的长度哦,也不要设置元素为 nil 。还是自己写个 get_length 函数,循环获取长度吧。
    http://www.tuicool.com/articles/Jbyy6n
    clino
        3
    clino  
       Aug 25, 2015 via Android
    pil 记得有专门针对这个说过的 去找找
    34D
        4
    34D  
       Aug 25, 2015
    不要设置元素为 nil ,如果已定要设置,要自己设置长度。
    iambic
        5
    iambic  
    OP
       Aug 25, 2015
    @whahuzhihao 很有用,多谢了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1245 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 17:25 · PVG 01:25 · LAX 10:25 · JFK 13:25
    ♥ Do have faith in what you're doing.