1 function SetReadOnlyVariables(tbTarget, tbVariablesInTable)
2 local proxy = {}
3 local mt = {
4 __index = tbTarget,
5 __newindex = function(_, k, v)
6 if tbVariablesInTable[k] then
7 error("attempt to update a read-only table", 2)
8 else
9 tbTarget[k] = v
10 end
11 end
12 }
13 setmetatable(proxy, mt)
14 return proxy
15 end
16
17 g_nReadOnly = 100
18 print(g_nReadOnly)
19
20 __G = SetReadOnlyVariables(_G, {g_nReadOnly = true})
21 setfenv(1, __G)
22
23 rawset(getfenv(1), "g_nReadOnly", 200) -- can not set g_nReadOnly = 100 directly
24 print(g_nReadOnly) -- equivalent to print(__G.g_nReadOnly), is 200
25 print(_G.g_nReadOnly) -- is 100
注解:
__G = SetReadOnlyVariables(_G, {g_nReadOnly = true}):设置_G table中的g_nReadOnly变量为只读。返回一个空表,通过其元表来访问元素。在__newindex方法中对访问权限进行检查。
setfenv(1, __G):切换当前函数(栈)环境。