LUA教程表相关的Metamethods 只读表 -58

function readOnly (t)
    local proxy = {}
    local mt = {         -- create metatable
       __index = t,
       __newindex = function (t,k,v)
           error("attempt to update a read-only table", 2)
       end
    } 
 
    setmetatable(proxy, mt)
    return proxy
end

(error的第二个参数2,将错误信息返回给企图执行update的地方)作为一个简单的例子,我们对工作日建立一个只读表:

days = readOnly{"Sunday", "Monday", "Tuesday", "Wednesday",
 
       "Thursday", "Friday", "Saturday"}
 
print(days[1])       --> Sunday
days[2] = "Noday"
stdin:1: attempt to update a read-only table

发布日期:

所属分类: 易语言 标签: