lua里 table的长度#table 的计算方法

int luaH_getn (Table *t) {
  unsigned int j = t->sizearray;
  if (j > 0 && ttisnil(&t->array[j - 1])) {
    /* there is a boundary in the array part: (binary) search for it */
    unsigned int i = 0;
    while (j - i > 1) {
      unsigned int m = (i+j)/2;
      if (ttisnil(&t->array[m - 1])) j = m;
      else i = m;
    }
    return i;
  }
  /* else must find a boundary in hash part */
  else if (isdummy(t->node))  /* hash part is empty? */
    return j;  /* that is easy... */
  else return unbound_search(t, j);
}

先判断最后一个元素是不是nil, 若不是则直接返回, 否则用2分查找查到不是nil的元素,并返回当前个数

posted on 2013-03-14 16:36  快乐的大猪  阅读(459)  评论(0编辑  收藏  举报

导航