Pit Lib Tablestuff

lua-users home
wiki

From PetersStdLib, an addition to the standard table functions of Lua (tinsert, tremove):

Tables Library code

[!] VersionNotice: The below code pertains to an older Lua version, Lua 4. It does not run as is under 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

Examples:

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)

Comments

not-necessarily-directed-at-PetersStdLib rants:

VersionNotice: tinsert and tremove are Lua4 functions, which are table.insert and table.remove in Lua 5.

I somewhat have to agree on that, but I wanted to seamlessly extend the standard libraries of lua. Perhaps it would be a better idea to completely replace the standardlibrary with a better named one, but I guess this would scare away possible users. Maybe the Lua authors will address this issue in a future version of Lua? (together with the "n-field" issue in tables) --PeterPrade

VersionNotice: The n-field issue is fixed in Lua 5. See LuaTableSize.

See Also


RecentChanges · preferences
edit · history
Last edited September 13, 2008 4:03 am GMT (diff)