lua-users home
lua-l archive

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


It was thus said that the Great Tim Hill once stated:
> 
> Now let's amend this very slightly:
> 
> "We use the term sequence to denote a table where, at all times for the
> life of the table, the set of all positive numeric keys is equal to {1..n}
> for some integer n, which is called the length of the sequence."
> 
> This is of course a stricter definition, since it means that a sequence
> must be constructed in ascending order (it doesn't prevent you from
> constructing a table out of order, it just means such a table is not a
> sequence from the above definition). It also means a table with no numeric
> keys at all *is* a sequence, if you allow the set of positive numeric keys
> to be empty.
> 
> We now define # as: "The # operator returns the length of a sequence, or
> nil if the table does not contain a sequence." This makes # completely
> predictable, and avoids any confusion over "tables with holes". It also
> makes # the *test* for a sequence ("if #t then … end").
> 
> Is this hard to implement? I think not. Essentially each new empty table
> starts off life as a sequence (with # returning 0). As each element is
> added, it is trivial to check for the "sequence-ness" of the table:
> 
> if type(new_key) == "number") and bSequence then
> 	bSequence = (new_key == #t +1)
> end

  Given:

	t_seq = {}
	for i = 1 , 99 do
	  t_seq[i] = nil
	end
	t_seq[100] = "Boom"

	t_hole = {}
	t_hole[100] = "Boom"

  What should the following print?

	print(#t_seq)
	print(#t_hole)

  Now, given that both tables have indicies 1 through 99 as nil, and 100 as
"Boom", should the two be treated differently?  Why?  They are "equal" to
each other:

	for i = 1 , 100 do
	  if t_seq[i] ~= t_hole[i] then
	    print("they are different")
	  end
	end

  I contend that this is just as confusing as the current behavior.

  How about "The # operator returns the highest integer key of the table"?

  -spc