lua-users home
lua-l archive

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



On 11-Nov-05, at 12:04 PM, Mike Pall wrote:

- table.maxn(t) should be documented as 'expensive' and only
  to be used if #t does not work (for arrays with holes or
  tables with non-integer keys).


I'm not sure whether table.maxn(t) is "the right thing" either. Suppose you were using it like this:

function foo(...)
  local args = {...}
  local nargs = table.getn(args)
  -- ...
end

Then it would effectively count interior nils but not count final nils, which is possibly odd (or possibly what was expected). Of course, in this case, one could use select("#", ...).

Another possible use for maxn might be to append one (sparse) array to another one, but again this will fail if the sparseness were at the end of the first array.

So it seems to me that if you want to use sparse arrays reliably, you need to remember the length of the array somewhere in the array object. At one time, Lua suggested the use of the key "n" for this purpose; the history of this feature does not need to be recounted (no pun intended -- well, perhaps it was intended.)

It seems clear that the Lua standard libraries no longer support sparse arrays in a meaningful fashion. They should probably simply be documented as not supporting sparse arrays, with the suggestion that people who want to use sparse arrays as a data structure implement their own mechanism for recording the length of the array.

However, it would be nice if it were possible to override the # operator for tables in order to support a user-implemented explicit length. It seems like that would not be too difficult; I believe that patches have been submitted to do so.