lua-users home
lua-l archive

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


On Mon, Dec 13, 2010 at 11:15 PM, Miles Bader <miles@gnu.org> wrote:
> Keith Matthews <keith.l.matthews@gmail.com> writes:
>> To remove the last element, table.remove(t) must be called:
>
> That's a non-starter, I think.

but also makes it trivial to implement in Lua, and i guess without
significant overhead:

(very!) untested:

do
	local lens = {}
	
	function add (t, v)
		local l = (lens[t] or #t) + 1
		t[l] = v
		lens[t] = l
		return v,l
	end
	
	function remove(t)
		local l = lens[t] or #t
		local v = t[l]
		t[l] = nil
		lens[t] = l-1
		return v,l
	end
	
	function len(t)
		return lens[t]
	end
end


-- 
Javier