From 6fb6d3ba629fce35345232d4a60753e1ff0cafee Mon Sep 17 00:00:00 2001 From: Connor Olding Date: Sun, 11 Dec 2016 03:54:59 -0800 Subject: [PATCH] . --- extra.lua | 34 +++++++++++++++++++++++++++++----- pt.lua | 9 +++++---- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/extra.lua b/extra.lua index 68e7afb..c0aa538 100755 --- a/extra.lua +++ b/extra.lua @@ -1,13 +1,13 @@ -function strpad(num, count, pad) +local function strpad(num, count, pad) num = tostring(num) return (pad:rep(count)..num):sub(#num) end -function add_zeros(num, count) +local function add_zeros(num, count) return strpad(num, count - 1, '0') end -function mixed_sorter(a, b) +local function mixed_sorter(a, b) a = type(a) == 'number' and add_zeros(a, 16) or tostring(a) b = type(b) == 'number' and add_zeros(b, 16) or tostring(b) return a < b @@ -15,7 +15,7 @@ end -- loosely based on http://lua-users.org/wiki/SortedIteration -- the original didn't make use of closures for who knows why -function order_keys(t) +local function order_keys(t) local oi = {} for key in pairs(t) do table.insert(oi, key) @@ -24,7 +24,7 @@ function order_keys(t) return oi end -function opairs(t, cache) +local function opairs(t, cache) local oi = cache and cache[t] or order_keys(t) if cache then cache[t] = oi @@ -36,3 +36,27 @@ function opairs(t, cache) if key then return key, t[key] end end end + +local function traverse(path) + if not path then return end + local parent = _G + local key + for w in path:gfind("[%w_]+") do + if key then + parent = rawget(parent, key) + if type(parent) ~= 'table' then return end + end + key = w + end + if not key then return end + return {parent=parent, key=key} +end + +return { + strpad = strpad, + add_zeros = add_zeros, + mixed_sorter = mixed_sorter, + order_keys = order_keys, + opairs = opairs, + traverse = traverse, +} diff --git a/pt.lua b/pt.lua index 5f16f1b..19c7e4c 100755 --- a/pt.lua +++ b/pt.lua @@ -1,10 +1,11 @@ -require 'extra' +local extra = require 'extra' +local opairs = extra.opairs local pt = {} pt.__index = pt setmetatable(pt, pt) -function rawstr(v) +local function rawstr(v) if v == nil then return 'nil' end local mt = getmetatable(v) local ts = mt and rawget(mt, '__tostring') @@ -15,11 +16,11 @@ function rawstr(v) return s end -function getaddr(t) +local function getaddr(t) return rawstr(t):sub(#type(t) + 3) end -function copy(t) +local function copy(t) -- shallow copy if type(t) ~= 'table' then return end local new = {}