Skip to content

Instantly share code, notes, and snippets.

@Choonster
Last active December 22, 2015 09:59
Show Gist options
  • Save Choonster/6456133 to your computer and use it in GitHub Desktop.
Save Choonster/6456133 to your computer and use it in GitHub Desktop.
This is a function (with supporting code) that attempts to verify a format string for Lua's `os.date` function. It receives the format string as its sole argument and returns `true` plus a formatted date string if it's valid or `false` plus an error message if its invalid. This implementation is designed for World of Warcraft's embedded Lua, but…
local verifyDateFormat
do
local specifiers = { -- ANSI C strftime conversion specifiers (usable on Windows and Mac)
a = true, A = true, b = true,
B = true, c = true, d = true,
H = true, I = true, j = true,
m = true, M = true, p = true,
S = true, U = true, w = true,
W = true, x = true, X = true,
y = true, Y = true, Z = true,
["%"] = true,
}
local specifierPattern
if IsWindowsClient() then -- Windows only adds one specifiers and one optional flag to the standard set.
specifiers.z = true
specifierPattern = "%%#?(%S)"
elseif IsMacClient() then -- Mac adds specifiers from POSIX, Olson's timezone package, GNU C Library and C99. It also adds several optional flags.
local S = specifiers
S["+"], S.B, S.C = true, true, true
S.D, S.e, S.F = true, true, true
S.G, S.g, S.h = true, true, true
S.k, S.l, S.n = true, true, true
S.O, S.R, S.r = true, true, true
S.s, S.t, S.T = true, true, true
S.u, S.V, S.v = true, true, true
S.X, S.y, S.z = true, true, true
specifierPattern = "%%[_0%-%^]?%d*[EO]?(%S)"
else
error("Client not recognised as Windows or Mac. Something has gone horribly wrong!")
end
local invalidSpecifiers = {}
function verifyDateFormat(input)
local numInvalidSpecifiers = 0
for specifier in input:gmatch(specifierPattern) do
if not specifiers[specifier] then
numInvalidSpecifiers = numInvalidSpecifiers + 1
invalidSpecifiers[numInvalidSpecifiers] = s
end
end
if numInvalidSpecifiers == 0 then
return pcall(date, input) -- If it looks valid, try to call date() with it.
else
return false, format(L["Invalid date specifier(s): %s"], tconcat(invalidSpecifiers, ", ", 1, numInvalidSpecifiers))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment