Skip to main content

luaur_vm/functions/
str_byte.rs

1use crate::functions::lua_l_checklstring::lua_l_checklstring;
2use crate::functions::lua_l_checkstack::lua_l_checkstack;
3use crate::functions::lua_l_error_l::lua_l_error_l;
4use crate::functions::lua_l_optinteger::lua_l_optinteger;
5use crate::functions::lua_pushinteger::lua_pushinteger;
6use crate::functions::posrelat::posrelat;
7use crate::macros::lua_l_error::luaL_error;
8use crate::macros::uchar::uchar;
9use crate::type_aliases::lua_state::lua_State;
10use core::ffi::c_int;
11
12#[no_mangle]
13pub unsafe fn str_byte(L: *mut lua_State) -> c_int {
14    let mut len: usize = 0;
15    let s = lua_l_checklstring(L, 1, &mut len);
16    let mut posi = posrelat(lua_l_optinteger(L, 2, 1), len);
17    let mut pose = posrelat(lua_l_optinteger(L, 3, posi), len);
18
19    if posi <= 0 {
20        posi = 1;
21    }
22    if (pose as usize) > len {
23        pose = len as c_int;
24    }
25
26    if posi > pose {
27        return 0; // empty interval; return no values
28    }
29
30    let n = pose - posi + 1;
31    if posi + n <= pose {
32        // overflow?
33        luaL_error!(L, "string slice too long");
34    }
35
36    lua_l_checkstack(L, n, "string slice too long");
37
38    let s_ptr = s.add((posi - 1) as usize);
39    for _i in 0..n {
40        let val = uchar(*s_ptr.add(_i as usize) as c_int);
41        lua_pushinteger(L, val as c_int);
42    }
43
44    n
45}