나는 예를 썼다.
function readOnly(t)
local newTable = {}
local metaTable = {}
metaTable.__index = t
metaTable.__newindex = function(tbl, key, value) error("Data cannot be changed!") end
setmetatable(newTable, metaTable)
return newTable
end
local tbl = {
sex = {
male = 1,
female = 1,
},
identity = {
police = 1,
student = 2,
doctor = {
physician = 1,
oculist = 2,
}
}
}
local hold = readOnly(tbl)
print(hold.sex)
hold.sex = 2 --error
이는 "tbl"테이블의 필드에 대한 액세스 권한을 부여 할 수 있지만 동시에 필드와 관련된 값을 변경할 수 없음을 의미합니다.
이제 문제는 중첩 된 모든 테이블이이 읽기 전용 속성을 소유하게하려는 것입니다. "readOnly"메서드를 어떻게 개선 할 수 있습니까?
readOnly
내부 테이블 필드에도 함수를 재귀 적 으로 적용하면됩니다 . __index
메타 메서드 에서 온 액세스로 그렇게 할 수 있습니다 . 또한 생성 한 읽기 전용 프록시 테이블을 캐시해야합니다. 그렇지 않으면 내부 테이블 (예 :)에 대한 읽기 액세스가 hold.sex
새 프록시 테이블을 생성합니다.
-- remember mappings from original table to proxy table
local proxies = setmetatable( {}, { __mode = "k" } )
function readOnly( t )
if type( t ) == "table" then
-- check whether we already have a readonly proxy for this table
local p = proxies[ t ]
if not p then
-- create new proxy table for t
p = setmetatable( {}, {
__index = function( _, k )
-- apply `readonly` recursively to field `t[k]`
return readOnly( t[ k ] )
end,
__newindex = function()
error( "table is readonly", 2 )
end,
} )
proxies[ t ] = p
end
return p
else
-- non-tables are returned as is
return t
end
end
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다