【IT168 技术文档】你是否希望你使用的table, 当他为nil时会以一个默认值来代替. 那么参照下面的方法.
我使用了一个count table当我迭代其他一些数据结构时可以为他们计数.
countTable = {}; ... thingImCounting = blahblahblah...; if (countTable[thingImCounting]==nil) then countTable[thingImCounting] = 0; end countTable[thingImCounting] = countTable[thingImCounting] + 1;
你可以使用一个函数来创建一个count table, 如果key对应的值不存在则返回默认值0.
function newCountTable() -- A table, t, where t[foo] returns 0 for undefined foo. local result = {}; setmetatable (result, {__index = function(tbl,key) return 0; end}); return result; end ... countTable = newCountTable(); ... thingImCounting = blahblahblah...; countTable[thingImCounting] = countTable[thingImCounting] + 1;
通过使用Metatable的__index来实现当table的key对应的value不存在时调用__index对应函数返回值.
然而, 你可以不使用Metatable而用Lua更简短的形式.
countTable = newCountTable(); ... thingImCounting = blahblahblah...; countTable[thingImCounting] = (countTable[thingImCounting] or 0) + 1;
然而这个方法, 你需要注意你的countTable所应用的地方, 并不是所用人在使用countTable时都会记得这么做'countTable[thingImCounting] or 0'.
最后提醒下, 默认值无需是0或者固定某数. 这里是可以根据需要自定义的.
为你的表table使用默认值II
上面我们使用了newCountTable来创建table不存在key的默认值这样的表, 如果需要对不存在的赋予默认值, 可以这样做.
function newTableOfCountTables() -- A table, t, where t[foo] returns a table, and t[foo][bar]==0 for undefined foo and bar. local result = {}; setmetatable (result, {__index = function(tbl,key) tbl[key]=newCountTable(); return tbl[key]; end}); return result; end
如果t[foo]存在则返回, 否则分配一个新的count table给他并返回.