这两天一直在折腾lua了,到现在才大概明白一点元方法的含义,恩,应该是我太笨了,现在,呵呵~
首先,
__index: 索引访问table[key]
function gettable_event (table, key)
local h
if type(table) == "table" then
local v = rawget(table, key)
if v ~= nil then
return v
end
h = metatable(table).__index
if h == nil then
return nil
end
else
h = metatable(table).__index
if h == nil then
error(...);
end
end
if type(h) == "function" then
return (h(table, key)) -- 调用处理程序
else
return h[key] -- 对它重复上述操作
end
end
__newindex: 索引赋值table[key] = value。
function settable_event (table, key, value)
local h
if type(table) == "table" then
local v = rawget(table, key)
if v ~= nil then
rawset(table, key, value)
return
end
h = metatable(table).__newindex
if h == nil then
rawset(table, key, value)
return
end
else
h = metatable(table).__newindex
if h == nil then
error(...)
end
end
if type(h) == "function" then
h(table, key,value) -- 调用处理程序
else
h[key] = value -- 对它重复上述操作
end
end
其中,关于rawget,rawset:
Gets the real value of table[index], without invoking any metamethod. table must be a table; index may be any value.
得到table在index索引出的值,并且不会触发元方法。
Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index any value different from nil, and value any Lua value.
This function returns table.
给一个表中的非空索引赋值,函数返回这个表
本文深入浅出地介绍了Lua语言中的元方法__index和__newindex的使用方式及工作原理,解释了如何通过这两个元方法来控制Lua表的索引访问和赋值行为。
2742

被折叠的 条评论
为什么被折叠?



