Skip to main content

luaur_vm/functions/
tinsert.rs

1use crate::enums::lua_type::lua_Type;
2use crate::functions::lua_gettop::lua_gettop;
3use crate::functions::lua_l_checkinteger::lua_l_checkinteger;
4use crate::functions::lua_l_checktype::lua_l_checktype;
5use crate::functions::lua_l_error_l::lua_l_error_l;
6use crate::functions::lua_objlen::lua_objlen;
7use crate::functions::lua_rawseti::lua_rawseti;
8use crate::functions::moveelements::moveelements;
9use crate::type_aliases::lua_state::lua_State;
10
11#[no_mangle]
12pub unsafe fn tinsert(L: *mut lua_State) -> core::ffi::c_int {
13    lua_l_checktype(L, 1, lua_Type::LUA_TTABLE as core::ffi::c_int);
14    let n = lua_objlen(L, 1);
15    let top = lua_gettop(L);
16    let pos: core::ffi::c_int;
17
18    match top {
19        2 => {
20            // called with only 2 arguments
21            pos = n + 1; // insert new element at the end
22        }
23        3 => {
24            // 2nd argument is the position
25            pos = lua_l_checkinteger(L, 2);
26
27            // move up elements if necessary
28            if 1 <= pos && pos <= n {
29                moveelements(L, 1, 1, pos, n, pos + 1);
30            }
31        }
32        _ => {
33            lua_l_error_l(
34                L,
35                c"wrong number of arguments to 'insert'".as_ptr(),
36                core::format_args!("wrong number of arguments to 'insert'"),
37            );
38            return 0;
39        }
40    }
41
42    lua_rawseti(L, 1, pos); // t[pos] = v
43    0
44}