_index和__newindex元方法

这两天一直在折腾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.

 

 

给一个表中的非空索引赋值,函数返回这个表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值