lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Thank you. When #1 becomes not good to use? For example if I have N elements and can delete any of elements with equal probability, starting which N #1 becomes not recommended?

There is also #4 fourth pattern is just to use *pairs()* iterator which works on both vector and hash parts, so for completely sparse arrays, say { [3] = "abc", [105] = "def", [1032] = "ghi" }, which are stored in hash part it is not smart to use numeric *for*.



2013/9/27 Sean Conner <sean@conman.org>
It was thus said that the Great Rafis Ganeyev once stated:
> Tables can't be used so easily as array() in PHP. All Lua developers should
> know their peculiarities to use them properly: distinctions between vector
> and hash parts, no count() function, maybe vector and hash parts grew
> strategy, etc.
>
> My question is simple. If I have some collection of objects in vector part
> and I create holes by setting nil to middle elements, length operator and
> ipairs begin work improperly, how to I traverse this collection? Only with
> pairs() or should I use table.getn(), which seems have been removed in Lua
> 5.2? Or should I create element called "n" in hash part and create
> add/remove functions for collection? What are best practices for that case?

  1) Don't set an element to nil.  Use table.remove() instead.  That way, #
     will alway work:

        t = { 1 , 2 , 3 , 4 }
        print(#t)
        table.remove(t,2)
        print(#t)

  2) Use a sentinel value to mark removal.

        empty = {}
        t = { 1 , 2 , 3 , 4 }
        print(#t)
        t[2] = empty
        print(#t)

        for i = 1 , #t do
          if t[i] ~= empty then
            print(t[i])
          end
        end

  3) Keep track of both the size and the maximum index.

        m = { __newindex = function(t,i,v)
                             if v == nil then
                               print(">>>")
                               t.N = t.N - 1
                               t.P[i] = v
                               return
                             end

                             if i > t.MAX then
                               t.MAX = i
                             end

                             t.N = t.N + 1
                             t.P[i] = v
                           end
        }
        t = { P = { 1 , 2 , 3 , 4 } , N = 4 , MAX = 4 }
        setmetatable(t,m)
        print(t.N)
        t[2] = nil
        print(t.N)

  In my opintion, the best practice is #1.

  -spc





--
С уважением,
инженер-программист ООО "СТ-ПРЕМИУМ"
Рафис Ганеев
+79257371586
rafisganeyev@gmail.com