lua-users home
lua-l archive

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


On Aug 7, 2010, at 11:31 PM, Stuart P. Bentley wrote:

> A while back there was some discussion on making arrays that were pre-initialized to a certain size. I think a good way to handle this would be to add one simple function to the language:
> 
> table.repeat(size,[value])
> 
> This function would return an array of <size> values, with each of the indices from 1 to <size> initialized to <value>, or the index it is at (eg. [1]=1, [2]=2, [3]=3, etc) in the default case.
> 
> On top of being useful from a practical implementation standpoint, this would also be useful for situations like table sorting:
> 
> function sort_by_secondary_criteria(data,criteria)
>  local order=table.repeat(#data)
>  table.sort(order,function(m,n) criteria[data[m]] < criteria[data[n]] end)
> end
> 
> As well as other applications that don't immediately come to mind.

Hare are some other options along similar veins:

table.fill( count, fn )
	-- Fills each entry from 1 to count with fn( index ) or just index if fn is not supplied.

table.capture( [ count, ] iterator, state, var )
	-- Fills an array with count elements taken from the supplied iterator. Stops at count or if
	-- the iterator reaches an end. If the first parameter is not a number, it is assumed that
	-- count was not supplied and the function simply captures values from the iterator until
	-- it terminates.

In the end, what this seems to argue for is simply an ability to preallocate a table at a particular size since the range of things one might do after that is broad.

Mark