lua首页投稿(暂停使用,暂停投稿)

Lua __index

2016-06-28  本文已影响1035人  AlbertS

前言#

上一篇文章中大概讲了API函数lua_getfield的用法,其中讲到调用lua_getfield方法时可能触发对应 "index" 事件的元方法,下面我们来看一下这个神奇的元方法。

内容#

元方法在lua中堪称强大,我们来试想一下,如果对一个table进行取值操作,但是table根本就没有这个值呢?一般情况下,lua会返回一个lua独有的值nil来表示访问的值不存在。那么如果我们不希望这样,而是想在访问无效时调用一个默认的操作应该怎么办呢?这就需要我们实现这个表的元表,以及元表的__index方法,实现的过程如下:

-- 定义一个table
local information = 
{
    name = "tom",
    age = 18,
    sex = "man",
}

-- 打印一下信息
print("the information is :")
print(information.name)
print(information.age)
print(information.sex)
print(information.address)

local mt = {
    __index = function(table, key)
    print("I haven't this field : " .. key);
end
}

-- 设置原表
setmetatable(information, mt);

-- 再次打印信息
print("\nafter set __index, the information is :")
print(information.name)
print(information.age)
print(information.sex)
print(information.address)

总结#

上一篇 下一篇

猜你喜欢

热点阅读