lua-users home
lua-l archive

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


On Dec 30, 2010, at 11:40 AM, Mark Hamburg wrote:

> 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.)

I'm going to amend that. Assume the introduction of a new additional module: types.

	types.test( array, a )
		-- returns a if a is an array. returns nil otherwise.

	types.check( array, a [ , msg ] )
		-- throws an error if a is not an array (using msg in some way if supplied). returns a otherwise.

	types.istypeerror( err )
		-- returns true if err is a message that could have been thrown by types.check

	types.register( key )
		-- throws if key has already been registered
		-- returns a weak table to hold values of the given type if it has not been registered

The implementation of array would therefore do the following:

	local types = require "types"

	local arraymt = { }
	local array = setmetatable( { }, arraymt )

	local types_array = types.register( array )

	function arraymt.__call( _, ... )
		local result
		-- construct result appropriately
		types_array[ result ] = true -- mark it as an array for the types module
		return result
	end

It might also be nice to allow types[ array ] to access a function or table that would do one of test or check though I'm not sure which one. Or there need to be ways to get the function versions so that one can optimize away the lookups if doing a lot of type-checking.

Mark