Pit Lib Tablestuff |
|
[!] 版本说明: 以下代码适用于旧版本的 Lua,Lua 4。它在 Lua 5 中无法直接运行。
-- Lua 4 -- table stuff: find a value in a table function tfind(t, s) return foreachi(t, function(i, v) if v==%s then return i end end) end -- like tinsert for sets: only adds if not already in the table function tadd(t, v) if not tfind(t, v) then tinsert(t, v) end end -- print entire table, good for debugging function tdump(table) if type(table) ~= "table" then print(table) -- dump is the same as print on non-table values else local indizes = {} foreach(table, function(i,v) tinsert(%indizes, i) end) if getn(indizes) == 0 then print("<empty table>") else sort(indizes) foreachi(indizes, function(_, index) local value = %table[index] if type(index) == "string" then print(index .. ":\t" .. tostring(value)) else print("[" .. index .. "]\t" .. tostring(value)) end end) end end end -- makes a deep copy of a given table (the 2nd param is optional and for internal use) -- circular dependencies are correctly copied. function tcopy(t, lookup_table) local copy = {} for i,v in t do if type(v) ~= "table" then copy[i] = v else lookup_table = lookup_table or {} lookup_table[t] = copy if lookup_table[v] then copy[i] = lookup_table[v] -- we already copied this table. reuse the copy. else copy[i] = tcopy(v,lookup_table) -- not yet copied. copy it. end end end return copy end
示例
t = {1,2,3,{"a","b"}} if tfind(t,3) then tadd(t,4) -- adds a 5th value tadd(t,1) -- doesn't add again tadd(t,t) -- adds a 6th value: circular reference to self end t2 = tcopy(t) -- make a deep copy of t. print(t2) print(t2[6]) -- see? t2[6] points to t2, as expected tdump(t2)
并非针对 PetersStdLib 的抱怨
tinsert
和 tremove
命名不当,因为它们是列表操作而不是表操作。
我多少同意这一点,但我希望无缝扩展 Lua 的标准库。也许用更好的命名方式完全替换标准库会更好,但我猜这会吓跑潜在的用户。也许 Lua 作者会在未来的 Lua 版本中解决这个问题?(以及表中的“n-field”问题)--PeterPrade