Lua设置只读表

简单理解一下:在lua中,当你从一个Table中查询值的时候,实际上是Lua解释器触发了_index ,而当你赋值时,则是访问了_newindex ,如果_newindex存在就会调用这个函数,而不进行赋值。

所以重写这两个函数就可以达到只读表的效果:

function table_read_only(t)

     local temp= t or {} 
     local mt = {
      __index = function(t,k)

             return temp[k] 

      end 
      __newindex = function(t, k, v)
            error("attempt to update a read-only table!")
       end
     }
 setmetatable(temp, mt) 
 return temp

end

用法:

local t_a = {1,2,3}

local t_b = table_read_only( t_a) --t_b为只读

t_b[5] = 1 --对表进行更新,会报错:attempt to update a read-only table!

你可能感兴趣的:(个人心得)