lua-users home
lua-l archive

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


On Apr 24, 2010, at 8:33 AM, J.Jørgen von Bargen wrote:

> On 4/24/10 7:53 AM, "J.Jørgen von Bargen" wrote:
>> I'm looking for a better idiom for
>>        local data=lookup[item] or {}
>>        lookup[item]=data
> Am 24.04.2010 17:00, schrieb Peter Cawley:
>> The obvious approach is to effectively make your ta function the
>> __index metamethod for the lookup table:
>>   
> Am 24.04.2010 17:07, schrieb Daniel Stephens:
>> but I'm curious, is there a reason why you didn't consider:
>> local data = lookup[item]
>> if (data == nil) then data = {} lookup[item] = data; end
> Thanks for your replies, here's my benchmark for your submissions
> -----------------------------------
> -- MAX =    4.238 ms
> -- use_setmetatable     :    3.407 ms = 293 loops/s [ 80.40 %] 1.244 times faster
> -- function_ta          :    3.631 ms = 275 loops/s [ 85.68 %] 1.167 times faster
> -- use_if_nil           :    3.644 ms = 274 loops/s [ 85.99 %] 1.163 times faster
> -- uggly_code           :    4.238 ms = 235 loops/s [100.00 %] 1.000 times faster
> -----------------------------------
> 
> setmetatable takes the lead, but the competition is still open... :-)

setmetatable keeps more of the logic running in a single VM instruction.

Untested utility code...

local mt_fill_empty_table = { __index = function( t, k )
	local v = {}
	t[ k ] = v
	return v
end }

function make_auto_fill( fill_routine )

	local mt

	if fill_routine == nil then
		mt = mt_fill_empty_table
	else
		mt = { __index = function( t, k )
			local v = fill_routine( k )
			t[ k ] = v
			return v
		end }
	end

	return setmetatable( {}, mt )

end

An extended version would also provide support for things like setting the weak mode for the table.

Mark