|

楼主 |
发表于 2011-12-28 20:55:35
|
显示全部楼层
那你得实现几个metamethod
newindex,用于给这个table添加新项目的时候
len,用于获取table的长度
你可以 ...
jason 发表于 2011-12-27 11:45 PM 
很不幸,你说的这种方法是不行的。首先,看__newindex的定义:
- 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 -- 当table中key所对应的值不为空时,直接rawset并返回
- 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) -- call the handler
- else h[key] = value -- or repeat operation on it
- end
- end
复制代码
从上面那句关键的话可以看到,对于ht[key]=nil;这样的语句,如果ht中已经存在key,就不会触发__newindex中的后续处理。
也就是说,只要有删除元素的操作,统计计数就会出错。
再来看len的定义:
- function len_event (op)
- if type(op) == "string" then
- return strlen(op) -- primitive string length
- elseif type(op) == "table" then
- return #op -- primitive table length -- 若op是table,则直接返回原生的#op
- else
- local h = metatable(op).__len
- if h then
- -- call the handler with the operand
- return (h(op))
- else -- no handler available: default behavior
- error(···)
- end
- end
- end
复制代码
从上面的关键的语句可以看出,对于table的#操作符,是无法修改的。
综上所述,lua中的metatable,并不是操作符重载语法。 |
|