use crate::functions::run_code::run_code;
use crate::functions::setup_state::setup_state;
use core::cell::RefCell;
use core::ffi::{c_char, CStr};
use std::ffi::CString;
use luaur_common::set_luau_bool_flags;
use luaur_vm::functions::lua_close::lua_close;
use luaur_vm::functions::lua_l_newstate::lua_l_newstate;
use luaur_vm::functions::lua_l_sandboxthread::lua_l_sandboxthread;
use luaur_vm::type_aliases::lua_state::lua_State;
thread_local! {
static RESULT: RefCell<Option<CString>> = const { RefCell::new(None) };
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "C" fn execute_script(source: *const c_char) -> *const c_char {
set_luau_bool_flags(true);
let l: *mut lua_State = lua_l_newstate();
setup_state(l);
lua_l_sandboxthread(l);
let source_str = if source.is_null() {
""
} else {
core::str::from_utf8_unchecked(CStr::from_ptr(source).to_bytes())
};
let result = run_code(l, source_str);
lua_close(l);
if result.is_empty() {
RESULT.with(|r| *r.borrow_mut() = None);
return core::ptr::null();
}
RESULT.with(|r| {
let cstring = CString::new(result).unwrap_or_default();
let ptr = cstring.as_ptr();
*r.borrow_mut() = Some(cstring);
ptr
})
}