笨木头花心贡献,哈?花心?不,是用心~
转载请注明,原文地址:http://www.benmutou.com/archives/1777
文章来源:笨木头与游戏开发
[cce]
local smartMan = {
name = "none",
money = 9000000,
sayHello = function()
print("大家好,我是聪明的豪。");
end
}
local t1 = {};
local mt = {
__index = smartMan,
}
setmetatable(t1, mt);
t1.sayHello = function()
print("en");
end;
t1.sayHello();
[/cce]
这是上一篇用过的例子,一个模仿继承结构的例子。[cce]
local smartMan = {
name = "none",
money = 9000000,
sayHello = function()
print("大家好,我是聪明的豪。");
end
}
local t1 = {};
local mt = {
__index = smartMan,
__newindex = function(table, key, value)
print(key .. "字段是不存在的,不要试图给它赋值!");
end
}
setmetatable(t1, mt);
t1.sayHello = function()
print("en");
end;
t1.sayHello();
[/cce]
留意mt元表,我们给它加了一个__newindex。[cce]
local smartMan = {
name = "none",
}
local other = {
name = "大家好,我是很无辜的table"
}
local t1 = {};
local mt = {
__index = smartMan,
__newindex = other
}
setmetatable(t1, mt);
print("other的名字,赋值前:" .. other.name);
t1.name = "小偷";
print("other的名字,赋值后:" .. other.name);
print("t1的名字:" .. t1.name);
[/cce]
这次的代码和刚刚差不多,但是我们新加了一个other的table,然后把other作为__newindex的值。