lua-users home
lua-l archive

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


Lorenzo Donati <lorenzodonatibz@interfree.it> wrote:
>
> The only drawback of Tony's approach is that it generates some garbage tables
> (as the inverse map approach). Not significant though, unless you have to
> generate many mappings in a tight loop.

If you are doing that and you care about performance, you can quite easily
lift the index tables out of the loop. To get rid of the last garbage
table you may want to break out an auxiliary function. Here's an
over-engineered version...

	function setkeys(tbl,keys,val)
		if type(keys) = 'thread' then
			keys = coroutine.wrap(keys)
		end
		if type(keys) == 'table' then
			for _,key in ipairs(keys) do
				tbl[key] = val
			end
		elseif type(keys) = 'function' then
			local key = keys()
			while key ~= nil do
				tbl[key] = val
				key = keys()
			end
		else
			tbl[keys] = val
		end
		return tbl
	end
	function setmulti(tbl,template)
		for keys,val in pairs(template) do
			setkeys(tbl,keys,val)
		end
		return tbl
	end
	function makemulti(template)
		return semulti({},template)
	end

	f = makemulti{	[{1,2,3,5,7,11,13,17,19,23}] = 1,
			[{4,6,8,10,12,14,16,18,20,22,24}] = 2,
			[{9,15,21}] = 3,
			[25] = 5 }

Tony.
-- 
f.anthony.n.finch  <dot@dotat.at>  http://dotat.at/
Biscay: Northerly or northeasterly backing northwesterly, but becoming
cyclonic in east for a time, 4 or 5, occasionally 6. Moderate or rough.
Thundery rain or showers. Moderate or good, occasionally poor.