obsidian/笔记文件/2.笔记/Lua base getmetatable().md
2025-03-26 00:02:56 +08:00

63 lines
1.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#unity/日常积累
# 前言
今天来总结一个查询元表的函数,这个函数可以查询对象是否有元表,如果有还可以将元表返回,有了这个函数我们就可以查询某个对象的值到底是它本身很久拥有的,还是在原表中存在的,接下来我们就一起来看看这个函数的用法吧。
# 内容
---
## getmetatable
- getmetatable(object)
- 解释:如果对象没有一个元表,则函数返回`nil`,否则函数会查询原表中是否有`"__metatable"`字段,如果有返回其关联值,如果没有则会返回所给对象的元表。
---
## usage
- 首先我们新建一个文件将文件命名为getmetatabletest.lua然后编写代码如下
```lua
-- 查看没有元表的情况
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))
```
- 运行结果
![[Pasted image 20220426111728.png]]
# 总结
- 没有元表的对象返回`nil`
- 有普通原表的对象返回元表本身,由`tab1` 返回的结果`table: 001A9968`等于m1可知。
- 当对象的元表包含字段`"__metatable"`时,则会直接返回这和字段的值,由第三组的运行结果可知。