【问题标题】:Is it possible to bypass __tostring the way rawget/set bypasses __index/__newindex in Lua?是否可以像 rawget/set 在 Lua 中绕过 __index/__newindex 一样绕过 __tostring?
【发布时间】:2017-04-08 04:35:25
【问题描述】:

例如:

local my_table = { name = "my table" }
local my_table_mt = {}

function my_table_mt.__tostring(tbl)
    return "%s<%s>":format(tbl.name or "?", rawtostring(tbl))
end

这样的事情可能吗?我知道 rawtostring 方法不存在,但是有没有办法模拟这种行为,或者完全绕过它?

【问题讨论】:

    标签: lua metatable meta-method


    【解决方案1】:

    只有这个杂物:

    function rawtostring(t)
       local m=getmetatable(t)
       local f=m.__tostring
       m.__tostring=nil
       local s=tostring(t)
       m.__tostring=f
       return s
    end
    

    【讨论】:

    • 在处理使用__metatable 隐藏真正元表的代码时,请记住使用debug.getmetatable 而不是普通的getmetatable。 (如果 __metatable 妨碍您使用 debug 模块,例如在受限环境中,那么您就不走运了。)
    • 这段代码在 Lua 中是完全安全的。 Lua 不是线程安全的,除非你为它构建一个全局锁。在不同的 OS 线程中使用不同的 Lua 状态
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 2022-06-27
    • 2015-09-26
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多