(原创) cocos2d-x 3.0+ lua 学习和工作(4) : 公共函数(8): 生成只读table

这个函数的作用是:生成只读table。

--[[ 
-- 生成只读table
-- @param table t 需要不允许修改的table
    example:
    local tb = {"星期一", "星期二", "星期日"}    
    local days = readOnly( tb );

    days[2] = "星期三哪去了啊?" ;
    "[string \"Functions.lua\"]:466: 别修改我!我是只读的!"
--]] 

function readOnly( t )
    local newT = t
    local mt = {
        __index = {},  -- 如果改成  newT = {}, __index = t,  会导致无法直接使用for循环遍历,其他遍历我没有试过~~(小白:好懒~~~)
        __newindex = function()
            error( "别修改我!我是只读的!" )
        end
    }
    setmetatable( newT, mt )
    return newT
end

 

作者使用 cocos2d-x 3.0 + lua学习和工作心得,未经作者允许,请勿转载!在此谢谢各位手下留情~~~

本文没有获得作者本人同意,不得转载,否则必追究相关责任。转载请注明出处!!~~

原文地址:http://www.cnblogs.com/wodehao0808/p/4029509.html

posted @ 2014-10-16 19:15  星月相随  阅读(349)  评论(0编辑  收藏  举报