zoukankan      html  css  js  c++  java
  • lua中 table.getn(t) 、#t、 table.maxn(t) 这三个什么区别?

    lua中 table.getn(t) 、#t、 table.maxn(t) 这三个什么区别?

    RT
    local t = {1,888,x= 999,b=2,5,nil,6,7,[10]=1,8,{z = 1,y = 1},nil,nil}

    print(table.getn(t))
    print(#t)
    print(table.maxn(t))

    输出:8 8 8
    ------------如果把[10] =1 改成[11] =1 那么输出8 8 11 这又是为什么?
     
     
     
    1个回答
     
    ==1==

    table.getn(t)
    等价于 #t
    但是它计算的是数组元素。不包括hash 键值。
    而且数组是以第一个nil元素来判断数组结束。
    #只计算array的元素个数,它实际上调用了对象的metatable 的__len函数
    对于有__len 方法的函数返回函数返回值。不然就返回数组成员数目。
    ==2==

    a={1,3,a='b',[6]='six',['10']='ten'}
    a 和 [6] ['10']是作为hash保存的。#a => 2 他是不包括hash成员的计数。
    1 3 是 数组结构保存的。table.maxn(a) => 6
    因为a中所有元素最大的数值索引是6不是字符串10

    .你的代码返回11 是因为它是最大的数值索引。
    maxn lua 5.2 已经抛弃了,不过依然可以使用。
    更多追问追答
     
     
    追问
    但是它计算的是数组元素。不包括hash 键值。
    而且数组是以第一个nil元素来判断数组结束。

    =========这个意思不就是说get(n)只会计算到第一个nil就停止么,但是我上面的例子好像没有停止,
     
    追答
    a={1,3,a='b',[6]='six',['10']='ten'}
    a 和 [6] ['10']是作为hash保存的。#a => 2 他是不包括hash成员的计数。
    这句话我说的有点误会。其实数组的数据结构也是hash。lua中数组的意思是:table的元素拥有连续的数字索引。比如:{[1]=1,[2]=2,[3]=3}

    The length operator is denoted by the unary prefix operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).
    A program can modify the behavior of the length operator for any value but strings through the __len metamethod (see §2.4).
    Unless a __len metamethod is given, the length of a table t is only defined if the table is a sequence, that is, the set of its positive numeric keys is equal to {1..n} for some integer n. In that case, n is its length. Note that a table like
    {10, 20, nil, 40}
    is not a sequence, because it has the key 4 but does not have the key 3. (So, there is no n such that the set {1..n} is equal to the set of positive numeric keys of that table.) Note, however, that non-numeric keys do not interfere with whether a table is a sequence.
    上面这句话是手册里的内容。
    table的长度是 table为序列时的某个n 使得,{1..n} == table的所有数字索引。也就是说序列的数字索引必须连续。
    # 运算得到的length 只针对 序列有意义 。当table不是序列时length 没有明确含义。
    table中间包括nil,这个table就不是序列,例如:
    a={10, 20, nil, 40}

    它不是序列,因为他的数字索引是 1 2 4 不是连续的,所以它不是序列。
    所以 #a 得到的值并不能准确反映table的元素个数。
    手册的意思是说 针对非序列使用#,而那个table又没有__len 时它值无意义的。

    再给你个实例:
    a={1,2,3,4,5}
    print(#a)
    5
    a[2]=nil
    print(#a) --此时a已经不是序列,此时对数列使用# , 具体意义不明。
    5
    a[5]=nil --删除最后元素
    print(#a) --看看 结果。
    1
    ===
    对于你想删除某个序列的元素,必须使用 table.remove 而不是 a[n]=nil
  • 相关阅读:
    在Windows下Mysql如何重置root用户密码
    textrendering 详解
    修复IE6 PNG不透明问题的最佳解决方案
    机电传动控制第一周学习笔记
    WEB架构师成长之路之二大牛的法宝
    WEB架构师成长之路之一走正确的路
    WEB架构师成长之路之三架构师都要懂哪些知识
    hdu 1081 To The Max(最大子段和的升级版,二维)
    hdu 1080 (DP LCS最长公共子序列)
    添加\删除注册表项
  • 原文地址:https://www.cnblogs.com/lgj8/p/12454496.html
Copyright © 2011-2022 走看看