Pit Lib Tablestuff

lua-users home
wiki

PetersStdLib,作為一個新增到 Lua 的標準函式表(tinsert、tremove)

Tables 函式庫程式碼

[!] VersionNotice:以下程式碼屬於舊版的 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 演講

VersionNotice:tinsert 和 tremove 是 Lua4 函式,在 Lua 5 中是 table.insert 和 table.remove。

我多少有些認同,但我想要無縫地擴充 lua 的標準函式庫。或許完全用另一個名稱來取代標準函式庫會是一個比較好的點子,但是我想這可能會嚇走可能的使用者。也許 Lua 作者會在 Lua 的未來版本中解決這個問題?(還有表格中的「n-欄位」問題)--PeterPrade

VersionNotice:n-欄位的問題在 Lua 5 中已經修正。請參考 LuaTableSize

另請參閱


RecentChanges · 偏好設定
編輯 · 歷程
最後編輯於 2008 年 9 月 13 日,格林威治標準時間上午 5:03 (diff)