Lua基本语法 (3)

                                       元表与元方法

 local mt = {}
mt.__add=function ( a1,a2 )
print("两个表相加")
end
local  t1 = {}

local t2 = {}

//给两个table设置新的元表

setmetatable(t1,mt)

setmetatable(t2,mt)

//进行加法操作

local result = t1+t2

例如:

 local mt = {}
mt.__add=function ( s1,s2 )
      local result = ""
if s1.sex=="boy"and s2.sex=="girl" then
result="完美家庭"
elseif s1.sex=="girl"and s2.sex=="girl" then
result="不好"
else   result="不好"
                         end
         return result  
end

local s1 = {name="Hello",sex="boy"}
local s2 = {name="Good",sex="girl"}

setmetatable(s1,mt)
setmetatable(s2,mt)

local result = s1+s2

print(result)结果 完美家庭


扫描二维码关注公众号,回复: 67199 查看本文章

——index :当你访问表中不存在字段的时候,回调用该表所对应原表中的——index元方法。
1:——index :函数:会调用该函数
2:——index: 表:回查询该表中的字段
__newindex:当你给表中不存在字段赋值的时候,回调用该表所对应原表中的__newindex元方法
1:__newindex:函数:会调用该函数

2:__newindex:表:会在该表中插入/修改该字段


例如:

local mt = {}
mt.__index=function (  )
	print("不存在")
end
t1={2,}
setmetatable(t1,mt)
print(t1[2])
运行结果:不存在
nil

例如;

local  mt = {}
mt.__index={2,4,"222"}
t1={}
setmetatable(t1,mt)
print(t1[1])
运行结果:2

例题

local mt = {}
mt.__index={ 1}
mt.__newindex=function ( table,key,value )
	print(key .."是不存在的")
end
t1={}
setmetatable(t1,mt)
print(t1[1])
t1.x=10
print(t1.x)
运行结果:1
x是不存在的
nil

例题

local smartMan = {name="none"}
local other = {name="大家好,我是你B哥"}
local t1 = {}
local mt = {
	__index=smartMan,
	__newindex=other
}
setmetatable(t1,mt)
print("other赋值前:" ..other.name)
t1.name="小偷"
print("other赋值后:" ..other.name)
print("t1的名字:" ..t1.name)
运行结果:other赋值前:大家好,我是你B哥
other赋值后:小偷
t1的名字:none
5.忽略元表

有的时候我们想忽略元表_index和_newindex功能

local smartMan = { name="none" }
local t1 = { haha=123}
local mt = {    __index=smartMan, __newindex=function ( t,k,v )
	print("别赋值")
end          }

setmetatable(t1,mt);
print(rawget(t1,"name"))
print(rawget(t1,"haha"))
print(rawget(t1,"name","小偷"))
print(rawget(t1,"name"))
运行结果:
nil
123
nil
nil
自带
local t1 = { haha=123}忽略不了

猜你喜欢

转载自blog.csdn.net/qq_41939248/article/details/80085621