1. 程式人生 > >關於Lua中const型變數或者常量的實現

關於Lua中const型變數或者常量的實現

--定義一個常量
local const = {}
local temp = {} 

local mt = { --建立一個元表
__newindex = function(t,k,v)
    if not temp[k] then
        temp[k] = v
    else
        error("嘗試給 const."..k.." 賦值")
    end
end,


__index = temp
}
setmetatable(const, mt)
const.test1 = "test1=="
const.test2 = "test2=="
print(const.test1, const.test2)