Skip to content

Instantly share code, notes, and snippets.

@hanxi
Created June 5, 2014 14:06
Show Gist options
  • Save hanxi/c323a074dc0e7005f33a to your computer and use it in GitHub Desktop.
Save hanxi/c323a074dc0e7005f33a to your computer and use it in GitHub Desktop.
将lua配置表设置成只读
local rawnext = next
function next(t,k)
local m = getmetatable(t)
local n = m and m.__next or rawnext
return n(t,k)
end
function pairs(t) return next, t, nil end
function readonly(t)
local proxy = {}
local mt = {
__index = t,
__next = function(_, k) return next(t, k) end,
__newindex = function(t, k, v)
error("attempt to update a read-only table", 2)
end,
}
for k,v in pairs(t) do
if type(v)=="table" then
t[k] = readonly(v)
end
end
setmetatable(proxy, mt)
return proxy
end
function setconst()
for k,v in pairs(_G) do
if k~="naruto_assert" and (string.find(k,"naruto_") or k=="DropDB") then
_G[k] = readonly(v)
end
end
end
-------------test-------------
function read(t)
for k,v in pairs(t) do
if type(v)=="table" then
read(v)
end
end
end
function test()
local t1=os.time()
print("time:start1",t1)
for k,v in pairs(_G) do
if string.find(k,"naruto") or string.find(k,"Drop") then
read(v)
end
end
local t2=os.time()
print("time:end1",t2,t2-t1)
setconst()
local t3=os.time()
print("time:start2",t3)
for k,v in pairs(_G) do
if string.find(k,"naruto") or string.find(k,"Drop") then
read(v)
end
end
local t4=os.time()
print("time:end2",t4,t4-t3)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment