__index元方法

如果定义了一个元表

table = {a = 1}

setmetatable(table, {__index = {b = 2}})

那么如果在table中取没有定义的键,那么lua就会在__index元方法里面去找,前提是__index是一个表,她还可以是一个函数

print(table.a,table.b)

------------

那么当__index元方法是函数会怎么样呢?lua会调用这个函数,并传入表和你写的那个键

t = setmetatable({a=1},{__index = function(table,key)

    --如果你查询一个表中没有的函数,lua就会调到这里来

    table.b = 2

    print(table.b,key)

    --[[或者是

    if key == "c" then

      return "b"

    else

      return nil

    end

    ]]

  end})

 

print(t.a,t.hehe)

这里首先她会打印2和hehe,然后才是1和nil。

为什么,因为t.hehe是查找,主表没找到,找元表,元表也没找到(没有return出来),自然是nil

posted @ 2017-08-24 22:39  小张学代码  阅读(483)  评论(0编辑  收藏  举报