Readonly = function(table) local empty = {} local mt = { __index = table, __newindex = function() print("Can not modify a readonly table") end } setmetatable(empty, mt) return empty end
local student = { name = "Alice", age = 18 } student = Readonly(student)
再尝试一下修改 student,已经不能修改字段的值了。
1 2
student.age = 20-- Can not modify a readonly table print(student.age) -- 18
Readonly = function(table) -- 遍历每个字段 for key, value inpairs(table) do -- 有嵌套表 iftype(value) == "table"then -- 递归设置只读 table[key] = Readonly(value) end end -- 设置只读的步骤 local empty = {} local mt = { __index = table, __newindex = function() print("Can not modify a readonly table") end } setmetatable(empty, mt) return empty end
在 student 表里新增一个 score 表,包含 math 和 english 字段。
经过只读函数递归处理之后,score 表也是只读的。
1 2 3 4 5 6 7 8 9 10 11 12
local student = { name = "Alice", age = 18, score = { math = 100, english = 100 } } student = Readonly(student)
student.score.math = 20-- Can not modify a readonly table print(student.score.math) -- 100