diff ReAction.lua @ 241:09c8e9baa35a

Collect table utility functions
author Flick
date Fri, 25 Mar 2011 16:50:43 -0700
parents 704f4a05a1d7
children b56cff349bd6
line wrap: on
line diff
--- a/ReAction.lua	Fri Mar 25 16:42:21 2011 -0700
+++ b/ReAction.lua	Fri Mar 25 16:50:43 2011 -0700
@@ -11,20 +11,58 @@
 end
 
 ------ Utility ------
-local tcopy
-do
-  function tcopy(x)
-    if type(x) ~= "table" then
-      return x
-    end
-    local r = {}
-    for k,v in pairs(x) do
-      r[k] = tcopy(v)
-    end
-    return r
+-- make a deep copy of a table
+local function tcopy(x)
+  if type(x) ~= "table" then
+    return x
   end
+  local r = {}
+  for k,v in pairs(x) do
+    r[k] = tcopy(v)
+  end
+  return r
 end
 
+-- traverse a table tree by key list and fetch the result or first nil
+local function tfetch(t, ...)
+  for i = 1, select('#', ...) do
+    t = t and t[select(i, ...)]
+  end
+  return t
+end
+
+-- traverse a table tree by key list and build tree as necessary
+local function tbuild(t, ...)
+  for i = 1, select('#', ...) do
+    local key = select(i, ...)
+    if not t[key] then t[key] = { } end
+    t = t[key]
+  end
+  return t
+end
+
+-- return a new array of keys of table 't', sorted by comparing 
+-- sub-fields (obtained via tfetch) of the table values
+local function fieldsort( t, ... )
+  local r = { }
+  for k in pairs(t) do
+    table.insert(r,k)
+  end
+  local path = { ... }
+  table.sort(r, function(lhs, rhs)
+     local olhs = tfetch(t[lhs], unpack(path)) or 0
+     local orhs = tfetch(t[rhs], unpack(path)) or 0
+     return olhs < orhs
+    end)
+  return r
+end
+
+-- store in the addon table
+addonTable.tcopy = tcopy
+addonTable.tfetch = tfetch
+addonTable.tbuild = tbuild
+addonTable.fieldsort = fieldsort
+
 ------ Core ------
 local ReAction = LibStub("AceAddon-3.0"):NewAddon( "ReAction",
   "AceEvent-3.0"