1mod any;
16mod func;
17
18use std::cell::Cell;
19use std::marker::PhantomData;
20
21use lua_stdlib::auxlib::load_buffer;
22use lua_stdlib::init::open_libs;
23use lua_types::closure::LuaLClosure;
24use lua_types::gc::GcRef;
25use lua_types::upval::UpVal;
26use lua_types::value::LuaValue;
27use lua_vm::api;
28use lua_vm::state::{new_state, LuaState};
29
30pub use any::{AnyHashableLuaValue, AnyLuaString, AnyLuaValue};
31pub use func::{
32 function0, function1, function2, function3, function4, function5, function6, FnHandle,
33 LuaFunction, StringInLua,
34};
35
36use func::{registry_remove, Adapter, FromLuaGlobal, SetValue};
37
38#[derive(Debug, Clone)]
43pub struct LuaError {
44 message: String,
45}
46
47impl LuaError {
48 pub(crate) fn from_vm(err: lua_types::LuaError) -> Self {
49 LuaError {
50 message: format!("{err}"),
51 }
52 }
53}
54
55impl std::fmt::Display for LuaError {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 f.write_str(&self.message)
58 }
59}
60
61impl std::error::Error for LuaError {}
62
63pub struct Lua<'lua> {
68 state: LuaState,
69 owned_closures: Vec<usize>,
70 _marker: PhantomData<&'lua ()>,
71}
72
73impl Default for Lua<'_> {
74 fn default() -> Self {
75 Self::new()
76 }
77}
78
79impl<'lua> Lua<'lua> {
80 pub fn new() -> Lua<'lua> {
90 let mut state = new_state().expect("omniLua state allocation failed");
91 state.global_mut().parser_hook = Some(parser_hook);
92 {
93 let _bootstrap_scope = state.global().heap.bootstrap_scope();
94 let _heap_guard = {
95 let g = state.global();
96 lua_gc::HeapGuard::push(&g.heap)
97 };
98 open_libs(&mut state).expect("opening omniLua standard libraries failed");
99 }
100 Lua {
101 state,
102 owned_closures: Vec::new(),
103 _marker: PhantomData,
104 }
105 }
106
107 pub fn open_string(&mut self) {}
110
111 pub fn execute<T: FromExec>(&mut self, code: &str) -> Result<T, LuaError> {
113 let status =
114 load_buffer(&mut self.state, code.as_bytes(), b"=(load)").map_err(LuaError::from_vm)?;
115 if status != 0 {
116 let err = self.state.pop();
117 return Err(LuaError::from_vm(lua_types::LuaError::from_value(err)));
118 }
119 api::pcall_k(&mut self.state, 0, 0, 0, 0, None).map_err(LuaError::from_vm)?;
120 T::from_exec(self)
121 }
122
123 pub fn set<V: SetValue>(&mut self, name: &str, value: V) {
125 value.set_into(self, name);
126 }
127
128 pub fn get<'l, V>(&'l mut self, name: &str) -> Option<V>
131 where
132 V: FromLuaGlobal<'l>,
133 {
134 V::from_lua_global(self, name)
135 }
136
137 pub(crate) fn state_mut(&mut self) -> &mut LuaState {
138 &mut self.state
139 }
140
141 pub(crate) fn install_closure(&mut self, name: &str, adapter: Adapter) {
144 let index = func::registry_insert(adapter);
145 self.owned_closures.push(index);
146 let state = &mut self.state;
147 api::push_integer(state, index as i64);
148 api::push_cclosure(state, func::trampoline, 1).expect("push_cclosure failed");
149 api::set_global(state, name.as_bytes()).expect("set_global failed");
150 }
151}
152
153impl Drop for Lua<'_> {
154 fn drop(&mut self) {
155 for &index in &self.owned_closures {
156 registry_remove(index);
157 }
158 }
159}
160
161pub trait FromExec: Sized {
164 fn from_exec(lua: &mut Lua<'_>) -> Result<Self, LuaError>;
165}
166
167impl FromExec for () {
168 fn from_exec(_lua: &mut Lua<'_>) -> Result<Self, LuaError> {
169 Ok(())
170 }
171}
172
173fn parser_hook(
177 state: &mut LuaState,
178 z: &mut lua_vm::zio::ZIO,
179 name: &[u8],
180 firstchar: i32,
181) -> Result<GcRef<LuaLClosure>, lua_types::LuaError> {
182 let proto = lua_parse::parse(
183 state,
184 lua_parse::DynData::default(),
185 z,
186 name,
187 firstchar,
188 )?;
189 let nupvals = proto.upvalues.len();
190 let mut upvals = Vec::with_capacity(nupvals);
191 for _ in 0..nupvals {
192 upvals.push(Cell::new(GcRef::new(UpVal::closed(LuaValue::Nil))));
193 }
194 Ok(GcRef::new(LuaLClosure {
195 proto: GcRef::new(*proto),
196 upvals: upvals.into_boxed_slice(),
197 }))
198}