Access Hidden Tables

lua-users home
wiki

When one needs to add extra info to a table that shouldn't be seen, one can use metatables to access these tables. Here are some approaches to accessing these and a comparison to a normal indexing of a table.


-- Access inside table over __call
-- This is a very nice access since it only can be called over <this>()
function newT()
	-- create access to a table
	local _t = {}
	-- metatable
	local mt = {}
	mt.__call = function()
		-- hold access to the table over function call
		return _t
	end
	return setmetatable( {},mt )
end

-- Access inside table over commonly used variable self[self], inside __index
function newT2()
	local t = {}
	local mt = {}
	mt.__index = {
		[t] = {}
		}
	return setmetatable( t,mt )
end

-- Access inside table over nomal variable
-- disadvantage is that setting a key to _t will override
-- the access to the hidden table
function newT3()
	local mt = {}
	mt.__index = {
		_t = {}
		}
	return setmetatable( {},mt )
end

-- Access over nomal variable inside table
function newT4()
	local t = {}
	t._t = {}
	return t
end
-- CHILLCODE™
Testcode:
t = newT()
t1 = os.clock()
for i = 1, 1000000 do
	-- set var 
	t()[i] = i
	--access var
	assert( t()[i] == i )
end
print("TIME1:",os.clock()-t1)

t = newT2()
t1 = os.clock()
for i = 1, 1000000 do
	-- set var 
	t[t][i] = i
	--access var
	assert( t[t][i] == i )
end
print("TIME2:",os.clock()-t1)

t = newT3()
t1 = os.clock()
for i = 1, 1000000 do
	-- set var 
	t._t[i] = i
	--access var
	assert( t._t[i] == i )
end
print("TIME3:",os.clock()-t1)

t = newT4()
t1 = os.clock()
for i = 1, 1000000 do
	-- set var 
	t._t[i] = i
	--access var
	assert( t._t[i] == i )
end
print("TIME4:",os.clock()-t1)
Output:
TIME1:  0.67200000000003
TIME2:  0.86000000000001
TIME3:  0.60900000000004
TIME4:  0.56200000000001

So the indexing over a hidden variable is the second fastest, where as one should avoid tables as index to call a variable, and in certain cases access over __call could be the most appropriate


RecentChanges · preferences
edit · history
Last edited December 3, 2012 12:22 pm GMT (diff)