访问隐藏表 |
|
-- 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 进行访问可能是最合适的。