lua中rawget和rawset
当我们只想单纯的调用table里的字段或者给table字段赋值时,
通过rawget函数来忽略元表的__index作用,
通过rawset函数来忽略元表的__newindex作用
举例:
local father =
{
sayHello = function()
print("大家好,我是father.");
end
}
local temp =
{
__index = father,
__newindex = function(table, key)
print(key .. "字段是不存在的,不允许给它赋值!");
end
}
son =
{
car=1
}
setmetatable(son, temp) --把son的metatable设置为father
print(rawget(son, "house")); //输出nil,因为是rawget,并且son中无house属性
print(rawget(son, "car")); //输出1,因为是rawget,但是son有car属性
rawset(son, "house", "10"); //son无house属性,然后并且是rawset,所以忽略元表中的__newindex方法,所以此时son中被设置了一个house属性
rawset(son, "sayHello", function() //son无方法sayHello,然后并且是rawset,所以忽略元表中的_newindex方法,所以song多了一个sayHello方法
print('============')
end);
print(son.house);
son.sayHello()
输出: