This commit is contained in:
Connor Olding 2016-12-11 03:54:59 -08:00
parent 176b8b32b0
commit 6fb6d3ba62
2 changed files with 34 additions and 9 deletions

View File

@ -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,
}

9
pt.lua
View File

@ -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 = {}