存取隱藏的資料表

lua-users home
wiki

當需要在資料表中加入一些不希望看到的額外資訊時,可以使用元資料表存取這些資料表。以下列出幾種存取方法以及與資料表正常索引的比較。

-- 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�
測試代碼
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)
輸出
TIME1:  0.67200000000003
TIME2:  0.86000000000001
TIME3:  0.60900000000004
TIME4:  0.56200000000001

因此索引隱藏變數是第二快的,應該避免使用資料表作為呼叫變數的索引,而在某些情況下,透過 __call 存取可能是最合適的


最新異動 · 偏好設定
編輯 · 歷史記錄
最後編輯時間:2012 年 12 月 3 日下午 12:22 GMT (比較)