2014年10月13日 星期一

LUA read only table

-----------------------------------------------
-- file DIR.lua

function readOnly (table)
  local proxy = {}
  local mt = {       -- create metatable
    __index = table
    ,__newindex = function (x,k,v)
      error("read-only "..k, 2)
    end
    ,__metatable = false
  }
  setmetatable(proxy, mt)
  return proxy
end

local t = { LEFT = 7, RIGHT = 8 }
DIR = readOnly(t)

---------------------------------------------
-- file test.lua
dofile("DIR.lua")

print("t="..tostring(t))

print("LEFT="..DIR.LEFT)
-- DIR.LEFT = 9                -- : read-only LEFT
print("LEFT="..DIR.LEFT)

mt = getmetatable(DIR)
print("mt="..tostring(mt))

---------------------------------------------
-- output
t=nil
LEFT=7
LEFT=7
mt=false

沒有留言:

張貼留言

車 和 東 , 兩個 不喜歡的 簡體字 寫法

  车 是 草書 形變, 很難 和 小孩 解釋 為什麼 長這樣(反正你就背), 反而 車 就 很形象. 东 是 草書 形變, 很難 和 小孩 解釋 為什麼 長這樣( 反正你就背), (古人觀察到 日出東方, 東 是 木頭 加 日 , 那個方向 是 東.