LUA read only table
-----------------------------------------------
-- file DIR.lua
function readOnly (table)
local proxy = {}
local mt = { -- create metatable
__index = table
,__newindex = function (x,k,v)
error("read-only "..k, 2)
end
,__metatable = false
}
setmetatable(proxy, mt)
return proxy
end
local t = { LEFT = 7, RIGHT = 8 }
DIR = readOnly(t)
---------------------------------------------
-- file test.lua
dofile("DIR.lua")
print("t="..tostring(t))
print("LEFT="..DIR.LEFT)
-- DIR.LEFT = 9 -- : read-only LEFT
print("LEFT="..DIR.LEFT)
mt = getmetatable(DIR)
print("mt="..tostring(mt))
---------------------------------------------
-- output
t=nil
LEFT=7
LEFT=7
mt=false
-- file DIR.lua
function readOnly (table)
local proxy = {}
local mt = { -- create metatable
__index = table
,__newindex = function (x,k,v)
error("read-only "..k, 2)
end
,__metatable = false
}
setmetatable(proxy, mt)
return proxy
end
local t = { LEFT = 7, RIGHT = 8 }
DIR = readOnly(t)
---------------------------------------------
-- file test.lua
dofile("DIR.lua")
print("t="..tostring(t))
print("LEFT="..DIR.LEFT)
-- DIR.LEFT = 9 -- : read-only LEFT
print("LEFT="..DIR.LEFT)
mt = getmetatable(DIR)
print("mt="..tostring(mt))
---------------------------------------------
-- output
t=nil
LEFT=7
LEFT=7
mt=false
0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁