Software / code / prosody
Comparison
util/format.lua @ 12035:dc7ab05005e8
util.format: Fix Lua 5.1 quirks thanks to ALL THE TESTS
| author | Kim Alvefur <zash@zash.se> |
|---|---|
| date | Sat, 11 Dec 2021 20:40:23 +0100 |
| parent | 12033:161f8268c4b3 |
| child | 12036:2ce06f788093 |
comparison
equal
deleted
inserted
replaced
| 12034:ee94ac51b2dd | 12035:dc7ab05005e8 |
|---|---|
| 27 ["\021"] = "\226\144\149", ["\022"] = "\226\144\150", ["\023"] = "\226\144\151", | 27 ["\021"] = "\226\144\149", ["\022"] = "\226\144\150", ["\023"] = "\226\144\151", |
| 28 ["\024"] = "\226\144\152", ["\025"] = "\226\144\153", ["\026"] = "\226\144\154", | 28 ["\024"] = "\226\144\152", ["\025"] = "\226\144\153", ["\026"] = "\226\144\154", |
| 29 ["\027"] = "\226\144\155", ["\028"] = "\226\144\156", ["\029"] = "\226\144\157", | 29 ["\027"] = "\226\144\155", ["\028"] = "\226\144\156", ["\029"] = "\226\144\157", |
| 30 ["\030"] = "\226\144\158", ["\031"] = "\226\144\159", ["\127"] = "\226\144\161", | 30 ["\030"] = "\226\144\158", ["\031"] = "\226\144\159", ["\127"] = "\226\144\161", |
| 31 }; | 31 }; |
| 32 local supports_p = pcall(string.format, "%p", ""); | 32 local supports_p = pcall(string.format, "%p", ""); -- >= Lua 5.4 |
| 33 local supports_a = pcall(string.format, "%a", 0.0); -- > Lua 5.1 | |
| 33 | 34 |
| 34 local function format(formatstring, ...) | 35 local function format(formatstring, ...) |
| 35 local args = pack(...); | 36 local args = pack(...); |
| 36 local args_length = args.n; | 37 local args_length = args.n; |
| 37 | 38 |
| 64 local t = type(arg); | 65 local t = type(arg); |
| 65 | 66 |
| 66 if option == "s" and t == "string" and not arg:find("[%z\1-\31\128-\255]") then | 67 if option == "s" and t == "string" and not arg:find("[%z\1-\31\128-\255]") then |
| 67 -- No UTF-8 or control characters, assumed to be the common case. | 68 -- No UTF-8 or control characters, assumed to be the common case. |
| 68 return | 69 return |
| 70 elseif option == "s" and t ~= "string" then | |
| 71 args[i] = tostring(arg); | |
| 69 end | 72 end |
| 70 | 73 |
| 71 if option ~= "s" and option ~= "q" and option ~= "p" then | 74 if option ~= "s" and option ~= "q" and option ~= "p" then |
| 72 -- all other options expect numbers | 75 -- all other options expect numbers |
| 73 if t ~= "number" then | 76 if t ~= "number" then |
| 77 spec = "[%s]"; | 80 spec = "[%s]"; |
| 78 t = "string"; | 81 t = "string"; |
| 79 elseif expects_integer[option] and num_type(arg) ~= "integer" then | 82 elseif expects_integer[option] and num_type(arg) ~= "integer" then |
| 80 args[i] = tostring(arg); | 83 args[i] = tostring(arg); |
| 81 return "[%s]"; | 84 return "[%s]"; |
| 85 elseif (option == "a" or option == "A") and not supports_a then | |
| 86 return "%x"; | |
| 82 else | 87 else |
| 83 return -- acceptable number | 88 return -- acceptable number |
| 84 end | 89 end |
| 85 end | 90 end |
| 86 | 91 |