元表

--[[元方法__index:对一个表A的元素id赋值,如果在表A中元素id不存在,不对id赋值]
会调用元表中(如果元表存在)的__newindex表,如果表A中存在id这个元素,则对赋值,不调用元表中__newindex]]
local newindextable = {}
local metableA = { __newindex = newindextable }
local tableA = { id = "tableA id" }
setmetatable( tableA, metableA)
tableA.id = "change id "
tableA.age = "change age"
print(tableA.id, newindextable.id)
print(tableA.age, newindextable.age)

打印结果:

===============20180506===========
change id 	nil
nil	        change age
===============20180506===========

以上可以简写为:

local newindextable = {}
local tableA =  setmetatable( { id = "tableA id" }, { __newindex = newindextable })
tableA.id = "change id "
tableA.age = "change age"

print(tableA.id, newindextable.id)
print(tableA.age, newindextable.age)
a and b   <==>   if  a  then  return  b  else return a  end
a or b   <==>   if  a  then  return  a  else return b  end
(a and {b} or {c})[1]  <==>   if  a  then  return  b  else return c  end


%02d “2”表示一共有两位,“0”表示如果实际长度不够两位使用0填充

os.data(*t) 返回星期几

判断一个表没有任何元素:_G.next(tabel)


猜你喜欢

转载自blog.csdn.net/twicetwice/article/details/80293497
今日推荐