zoukankan      html  css  js  c++  java
  • Lua初学习 9-14_04 元表中的 __index 和 __newindex 元方法;以及跟踪teble属性变化(get set)

    1:__index

    a = { name = "a name",age = 99}

    b = { age = 100}

    setmetatable(b,a)

    print(b.name) -----> nil

    print(b.age)  ----> 100

    a.__index = a

    print(b.name) ----> a name

    print(b.age) -----> 100

    当我们get b table中某个属性的时,如果属性存在=》则拿到b table中的属性

    如果属性不存在=》则访问b元表中的__index方法

     

    2: __newindex

    a = { name = "a name" , age = 99}

    b = { age = 100 }

    setmetatable(b,a)

    --set b 属性

    b.name = "b name"

    print(b.name) ----> b name

    --重写b的元表a中的__newindex元方法

    a.__newindex = function () print("a __newindex func") end

    b.game = "dnf" ----> a__newindex func

    print(b.game) ----> nil

    当我们去set b table中某个属性时,会调b的元表中的__newindex元方法

     

     

    3:  以前简单说了get set,在Lua中,叫作跟踪table的访问(就像C#里面一个字段属性器一样,蛋疼的是C#是一个字段可以一个属性        器,而Lua中实现也可以,但是太蛋疼,所以只在元表中的__index _newindex判断一下进来的Key)

         大概的做法就是:

    1,要跟踪 t 的所有访问,声明时置空 t

    2,声明一个空的table _t,储存所有set(__newindex)的key value 

    3,为 t 设置一个元表 mt , mt重写 __index __newindex 方法(get set)

    例子:

    t = {}
    _t = {}
    mt = {}

    --重写Mt __index __newindex
    mt.__index = function (t,k) --get
       print("get",t,k)
       if(k == "money") then print("有地方在拿table的金币属性") end
       return _t.k
    end
    mt.__newindex = function (t,k,v) --set
       print("set",t,k,v)
       if(k == "money") then print("金币增加了,调用视图Text= _t.k + v") end
       _t.k = v
    end
    setmetatable(t,mt)

    t.name = "coco"         --set table: 002CB128 name coco
    t.money = 100           --set table: 002CB128 money 100
    print(t.name)             --get 

    print(t.money)           --get     --有地方在拿table的金币属性

    =================debug=======================

    set table: 002CB128 name coco
    set table: 002CB128 money 100
    金币增加了,调用视图Text= _t.k + v
    get table: 002CB128 name
    100
    get table: 002CB128 money
    有地方在拿table的金币属性
    100

  • 相关阅读:
    继承
    接口
    匿名内部类
    抽象类和接口的区别
    多态
    重载和覆写的区别|this和super区别
    Visual C# 2008+SQL Server 2005 数据库与网络开发――2.2.1 变量
    Visual C# 2008+SQL Server 2005 数据库与网络开发――2.3.1 选择语句
    Visual C# 2008+SQL Server 2005 数据库与网络开发―― 2.5错误和异常处理
    Visual C# 2008+SQL Server 2005 数据库与网络开发―― 2.3 语句
  • 原文地址:https://www.cnblogs.com/cocotang/p/5872166.html
Copyright © 2011-2022 走看看