diff options
author | Damien George <damien.p.george@gmail.com> | 2014-01-08 18:11:23 +0000 |
---|---|---|
committer | Damien George <damien.p.george@gmail.com> | 2014-01-08 18:11:23 +0000 |
commit | 6c73ca1e754aa5fb822999a0b46f01e216619ec6 (patch) | |
tree | 6fdd7b4205d2a4ef7056753ff067f78fb1197f41 /py/objexcept.c | |
parent | 199b9e04eb186320f5d94bdc3b852f2443e466e0 (diff) |
py: add variable argument exception constructor function.
Addresses issue #104.
Diffstat (limited to 'py/objexcept.c')
-rw-r--r-- | py/objexcept.c | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/py/objexcept.c b/py/objexcept.c index 829b14785..4708a27bf 100644 --- a/py/objexcept.c +++ b/py/objexcept.c @@ -1,6 +1,7 @@ #include <stdlib.h> #include <stdint.h> #include <string.h> +#include <stdarg.h> #include <assert.h> #include "nlr.h" @@ -79,6 +80,37 @@ mp_obj_t mp_obj_new_exception_msg_2_args(qstr id, const char *fmt, const char *a return o; } +mp_obj_t mp_obj_new_exception_msg_varg(qstr id, const char *fmt, ...) { + // count number of arguments by number of % signs, excluding %% + int n_args = 1; // count fmt + for (const char *s = fmt; *s; s++) { + if (*s == '%') { + if (s[1] == '%') { + s += 1; + } else { + n_args += 1; + } + } + } + + // make exception object + mp_obj_exception_t *o = m_new_obj_var(mp_obj_exception_t, void*, n_args); + o->base.type = &exception_type; + o->id = id; + o->n_args = n_args; + o->args[0] = fmt; + + // extract args and store them + va_list ap; + va_start(ap, fmt); + for (int i = 1; i < n_args; i++) { + o->args[i] = va_arg(ap, void*); + } + va_end(ap); + + return o; +} + qstr mp_obj_exception_get_type(mp_obj_t self_in) { assert(MP_OBJ_IS_TYPE(self_in, &exception_type)); mp_obj_exception_t *self = self_in; |