diff options
author | Damien George <damien.p.george@gmail.com> | 2014-01-05 05:42:37 -0800 |
---|---|---|
committer | Damien George <damien.p.george@gmail.com> | 2014-01-05 05:42:37 -0800 |
commit | a3ab68e9493481a3fcbd1b74278d199c53a3c2f6 (patch) | |
tree | 1dc84badc53294e7ab7f043761815fc5820fa746 /py/objlist.c | |
parent | 1dd657fa87cdfe93ddc30df014a385c801d8dacf (diff) | |
parent | 7e73a8fd09a8070a3bbb90d2ddc4f04af4e2828a (diff) | |
download | micropython-a3ab68e9493481a3fcbd1b74278d199c53a3c2f6.tar.gz micropython-a3ab68e9493481a3fcbd1b74278d199c53a3c2f6.zip |
Merge pull request #78 from chipaca/list_index
Implements list.index. Fixes issue #57.
Diffstat (limited to 'py/objlist.c')
-rw-r--r-- | py/objlist.c | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/py/objlist.c b/py/objlist.c index 3018826113..7b3b6f1772 100644 --- a/py/objlist.c +++ b/py/objlist.c @@ -177,10 +177,31 @@ static mp_obj_t list_count(mp_obj_t self_in, mp_obj_t value) { return mp_obj_new_int(count); } +static mp_obj_t list_index(int n_args, const mp_obj_t *args) { + assert(2 <= n_args && n_args <= 4); + assert(MP_OBJ_IS_TYPE(args[0], &list_type)); + mp_obj_list_t *self = args[0]; + mp_obj_t *value = args[1]; + + uint start = mp_get_index(self->base.type, self->len, + n_args >= 3 ? args[2] : mp_obj_new_int(0)); + uint stop = mp_get_index(self->base.type, self->len, + n_args >= 4 ? args[3] : mp_obj_new_int(-1)); + + for (uint i = start; i <= stop; i++) { + if (mp_obj_equal(self->items[i], value)) { + return mp_obj_new_int(i); + } + } + + nlr_jump(mp_obj_new_exception_msg(rt_q_ValueError, "Object not in list.")); +} + static MP_DEFINE_CONST_FUN_OBJ_2(list_append_obj, mp_obj_list_append); static MP_DEFINE_CONST_FUN_OBJ_1(list_clear_obj, list_clear); static MP_DEFINE_CONST_FUN_OBJ_1(list_copy_obj, list_copy); static MP_DEFINE_CONST_FUN_OBJ_2(list_count_obj, list_count); +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(list_index_obj, 2, 4, list_index); static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(list_pop_obj, 1, 2, list_pop); static MP_DEFINE_CONST_FUN_OBJ_2(list_sort_obj, list_sort); @@ -199,6 +220,7 @@ const mp_obj_type_t list_type = { { "clear", &list_clear_obj }, { "copy", &list_copy_obj }, { "count", &list_count_obj }, + { "index", &list_index_obj }, { "pop", &list_pop_obj }, { "sort", &list_sort_obj }, { NULL, NULL }, // end-of-list sentinel |