首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查Metatable是否为只读

检查Metatable是否为只读
EN

Stack Overflow用户
提问于 2018-12-08 12:41:49
回答 1查看 581关注 0票数 0

我正在尝试找到一种方法来检查Metatable是否为只读

例如

代码语言:javascript
复制
local mt = metatable(game)
if mt == "readonly" do
print("Attempt to modify Metatables")
end

我希望有一种方法可以实现这一点,这样我就可以防止GUI篡改

EN

回答 1

Stack Overflow用户

发布于 2018-12-22 03:03:38

您可以使用getmetatable()查看元表的内容是否受到保护。

示例:

代码语言:javascript
复制
local mt = getmetatable(game)
if mt ~= nil and type(mt) ~= "table" then -- not perfect, as __metatable could be set to {}
    print("This metatable is protected!")
end

或者,如果要查看表本身是否为只读,则需要检查两种行为

  1. 当您尝试向表中添加值时会发生什么
  2. 当您尝试更改表中的值时会发生什么。

只读表示例:

代码语言:javascript
复制
local protected_table = {'1', '2', '3'}
local table  = setmetatable({}, {-- create a dumby table with a metatable
    __index = function(_, k)
        return protected_table[k]-- access protected table
    end,
    __newindex = function()
        error('This value is read-only.')
    end,
    __pairs = function(_)
        return function(_, k)
            return next(protected_table, k)
        end
    end,
    __metatable = false,
})

可能的交互示例:

代码语言:javascript
复制
table[4] = "4" -- read-only error will be generated by _newindex setting

table[1] = "0" -- read-only error will be generated by _newindex setting

first = table[1] -- will retrieve first value of protected_table
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53679564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档