lua程序员

Lua base getmetatable()

2016-08-28  本文已影响258人  AlbertS
原始的风景.jpg

前言

今天来总结一个查询元表的函数,这个函数可以查询对象是否有元表,如果有还可以将元表返回,有了这个函数我们就可以查询某个对象的值到底是它本身很久拥有的,还是在原表中存在的,接下来我们就一起来看看这个函数的用法吧。

内容


getmetatable


usage

-- 查看没有元表的情况
local aNumber = 100
print("\nthe matetable of a number is", getmetatable(aNumber))


-- 普通的元表
local tab1 = { 
    x = 13,
    y = 36,
}
local m1 = { z = 36}
print("\nm1 is ", m1)

setmetatable(tab1, m1)
print("\nthe matetable of a table tab1 is", getmetatable(tab1))

-- 有字段"__metatable"的元表
local tab2 = { 
    x = 1,
    y = 3,
}
local m2 = {
    z = 28,
    ["__metatable"] = "hehe"
}
print("\nm2 is ", m2)

setmetatable(tab2, m2)
print("\nthe matetable of a table tab2 is", getmetatable(tab2))
base_getmetatable.png

总结

上一篇下一篇

猜你喜欢

热点阅读