前言#
前兩篇文章中大概講了API函數lua_setfield的用法,其中講到調用lua_setfield方法時可能觸發對應 "newindex" 事件的元方法,對比上一章我們說的__index方法,下面我們來再次看一下這個神奇的元方法。
內容#
前面我們剛剛說過__index元方法,當取一個table的不存在的字段時會觸發,可以幫助我們解決table中字段的默認值問題。在此基礎上我們再試想一下,如果給一個table中不存在的字段賦值會出現什么情況?答案是沒有意外情況,直接賦值就可以,但是如果我們想監測這種情況呢?也就是說我們要監測給table中不存在的字段賦值這種情況,不得不說這種監測是有一定意義的,比如說table新加字段時需要做一些特殊操作就需要用到這種監測,接下來我們來看看怎么實現:
- 首先新建一個文件命名為__newindex.lua,然后在文件中實現下面的代碼:
-- 定義一個table
local information =
{
name = "tom",
age = 18,
sex = "man",
}
-- 無元表情況下設置值
information.age = 22;
information.address = 'china';
-- 打印一下信息
print("the information is :")
print(information.name)
print(information.age)
print(information.sex)
print(information.address)
-- 先清空address字段
information.address = nil;
-- 定義元表
local mt = {
__newindex = function(table, key, value)
print("\nthis is the first time to assignment for the field : " .. key.." = "..value);
rawset(table, key, value);
end
}
-- 設置原表
setmetatable(information, mt);
-- 有元表情況下設置值
information.age = 24;
information.address = 'beijing';
-- 再次打印信息
print("\nafter set __index, the information is :")
print(information.name)
print(information.age)
print(information.sex)
print(information.address)
- 結果
__newindex.png
結論#
- 由結果可以看到當我們給address賦值的時候,由于address值為nil也就是不存在,所以調用了__newindex元方法。
- 注意index和newindex的使用情況,記住:__index用于查詢,__newindex用于更新。
- 學會使用newindex元方法檢測給table空字段賦值的情況。