Lua JSON decoder error reporter with line/col

Lua
local function decode_json(text, decode)
  assert(type(decode) == 'function', 'a JSON decoder function is required')
  local ok, res, err = pcall(decode, text)
  if ok and res ~= nil then return res end
  local msg = tostring(err or res or 'decode failed')
  local pos = math.min(tonumber(msg:match('(%d+)')) or 1, math.max(1, #text))
  local before = text:sub(1, pos - 1)
  local line = 1 + select(2, before:gsub('\n', ''))
  local col = #(before:match('([^\n]*)$')) + 1
  local near = (text:sub(math.max(1, pos - 20), pos + 20):gsub('%s+', ' '))
  return nil, ('invalid JSON at line %d col %d near %q: %s'):format(line, col, near, msg)
end

return decode_json