Lua 元表

-- 设置元表
tb = {}                          
metatb = {}                      
setmetatable(tb, metatb) 
getmetatable(tb) 

tb = setmetatable({}, {})

--index
tb = setmetatable({1, 2, 3}, {
    __index = function(tb, key)
        print(key.."不存在")
    end
})
print(tb.key)

--newindex
tb = setmetatable({1, 2, 3}, {
    __newindex = function(tb, key, val)
        print("赋值")
        rawset(tb, key, val)
    end
})
tb.key = 1

--add
tb = setmetatable({1, 2, 3}, {
    __add = function(tb, tb2)
        print("相加")
        return {}
    end
})
tb = tb+tb

--call
tb = setmetatable({10}, {
    __call = function(tb, tb2)
        print("调用表")
    end
})
tb()

--tostring
tb = setmetatable({10, 20, 30}, {
    __tostring = function(tb)
        return "打印表"
    end
})
print(tb)

--[[
	__add	     '+'
	__sub	     '-'
	__mul	     '*'
	__div	     '/'
	__mod	     '%'
	__unm	     '-'
	__concat	 '..'
	__eq	     '=='
	__lt	     '<'
	__le	     '<='
]]

猜你喜欢

转载自blog.csdn.net/weixin_35338800/article/details/83099749
今日推荐