Lua实现只读Table


local DataSourceTable = {}

--对Table进行初始化
for i = 0, 10 do
	DataSourceTable[i] = i
end

--构造只读元方法
local mt = {
	__index = function(table, key)
		print("Access table")
		return DataSourceTable[key]
	end,
	__newindex = function(table, key, value)
		print("This is a read-only Table!")
	end
}

--设置只读Table方法
local function setReadOnlyTable(table)
	setmetatable(table, mt)
	return table
end

--创建只读Table
local ReadOnly = setReadOnlyTable({})

--尝试读取代理Table
local a = ReadOnly[1]
print(a)
--尝试修改代理Table
ReadOnly[1] = 123


--直接对基础table修改
DataSourceTable[1] = 234

print(DataSourceTable[1])

猜你喜欢

转载自blog.csdn.net/qq_29094161/article/details/82838902