[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Standard libraries (was Re: Virgin tables)
- From: Mark Hamburg <mark@...>
- Date: Thu, 30 Dec 2010 11:40:24 -0800
So, here is my rough proposal for an array type. No implementation provided at this time (because I tend to work from APIs to implementations rather than the other way arround).
a = array( ... )
-- constructs an array with the provided var args elements
-- the length of the array is equal to the length of the varargs
#a -- the length of the array
a[ idx ] = value
-- idx must be a positive integer
-- stores value at the given index
-- adjusts the length to max( #a, idx )
a[ idx ]
-- returns the value at the given index
-- idx should be a positive integer.
-- Q: Signal errors if idx is invalid or simply return nil? I'm inclined toward signaling errors.
a:insert( [ idx, ] value )
-- inserts value at idx shifting values after idx rightward
-- the length is adjusted to be equal to max( idx, #a + 1 )
-- if idx is not supplied, it is taken to be #a + 1
-- returns a
a:remove( [ idx ] )
-- idx must be a positive integer
-- returns a[ idx ] before adjustment
-- if idx is less than or equal to #a, then the elements to the right of idx are shifted down and #a is decremented
-- Note: This definition says it is acceptable to remove elements from off the end of the array. Should this instead throw an error?
a:sort( [ comp ] )
-- Sort the elements in the array using the comparison function comp if supplied
a:ipairs()
-- Returns an iterator for the array that returns elements of the form idx, value where the index values are increasing.
a:unpack()
-- Evaluates to the contents of the array
array.test( a )
-- Returns true if a is an array and false otherwise
array.check( a [, msg ] )
-- Check that a is an array throwing an error (using msg in some way) if not
The array methods are stored in the table array -- the constructor is based on a __call metamethod -- and can be extended by extending this table. (I am not really fond of intermixing "class methods" likes array.test and array.check with instance methods, but I don't have a better proposal at this time.)
Net result:
arrays are just like tables except that they can have holes and those holes are accounted for in the length and they disallow non-array-like indices.
Mark