笨木头花心贡献,哈?花心?不,是用心~
转载请注明,原文地址:http://www.benmutou.com/archives/1766
文章来源:笨木头与游戏开发
[cce]
local t = {
name = "hehe",
}
print(t.money);
[/cce]
输出结果当然是:nil[cce]
local t = {
name = "hehe",
}
local mt = {
__index = function(table, key)
print("虽然你调用了我不存在的字段,不过没关系,我能探测出来:" .. key);
end
}
setmetatable(t,mt);
print(t.money);
[/cce]
我们给table设置了一个自定义的元表,元表的__index元方法使用了我们的函数。[cce]
local t = {
name = "hehe",
}
local mt = {
__index = {
money = "900,0000",
}
}
setmetatable(t,mt);
print(t.money);
[/cce]
留意__index,我们给它赋值了一个table,这个table中有一个money对象。[cce]
local smartMan = {
name = "none",
age = 25,
money = 9000000,
sayHello = function()
print("大家好,我是聪明的豪。");
end
}
local t1 = {};
local t2 = {}
local mt = {__index = smartMan}
setmetatable(t1, mt);
setmetatable(t2, mt);
print(t1.money);
t2.sayHello();
[/cce]
我们定义了一个table,叫做smartMan,作为“基类”。