low-luajit 0.2.0

Low level but safe bindings to the LuaJIT C API with no dependencies and no-std support to create Lua modules using Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
use core::{ffi::CStr, mem::{self, MaybeUninit}, ptr};
use crate::{LuaState, SafeFn, ffi::{self, LUA_IDSIZE, lua_Debug, lua_Hook}, map_ptr};

#[cfg(doc)]
use crate::CFunction;

/// Debugging function that is called by specified [`HookEvent`]s.
///
/// See [`LuaState::set_hook`] for more information on how to enable an `Hook`.
/// There can only be one `Hook` enabled at a time.
///
/// When called, `info` can be used to retrieve the [`HookEvent`] that called the hook (see [`DebugInfo::event`]).
///
/// If [`HookEvent::Line`] is the event that called the `Hook`, [`DebugInfo::current_line`] will also be set.
///
/// To get more information about the function that was running at the time,
/// [`LuaState::get_info`] can be called using `info` without needing to specify a function using [`LuaState::get_stack`].
///
/// While the current `Hook` is running, it cannot be called again.
/// Which means it is possible to call other functions from within the hook itself without issues.
///
/// Just like [`CFunction`], this type is technically a *subset* of [`lua_Hook`], as it only allows safe functions.
/// Different methods will use either [`lua_Hook`] or `Hook` based on if they work with only safe functions or not.
pub type Hook = extern "C-unwind" fn(lua: LuaState, info: &mut DebugInfo);

impl SafeFn for Hook {
	type RawFn = lua_Hook;

	#[inline]
	unsafe fn from_raw(raw: lua_Hook) -> Self {
		// SAFETY: lua_Hook and Hook are effectively the same.
		unsafe { mem::transmute(raw) }
	}

	#[inline]
	fn to_raw(self) -> lua_Hook {
		// SAFETY: Hook and lua_Hook are effectively the same.
		unsafe { mem::transmute(self) }
	}
}

/// All possible event types that can call the current [`Hook`].
#[repr(i32)]
#[derive(Debug, Clone, Copy)]
pub enum HookEvent {
	/// Calls the current [`Hook`] whenever a function is called, just after Lua enters the function but before it receives its arguments.
	Call = ffi::LUA_HOOKCALL,

	/// Calls the current [`Hook`] whenever a called function returns, just before Lua leaves the function.
	///
	/// The values being returned by the returning function cannot be accessed.
	Return = ffi::LUA_HOOKRET,

	/// Calls the current [`Hook`] whenever a new line of code is executed or when Lua jumps back to a previous (or the same) line.
	///
	/// This event only happens for Lua functions (not [`CFunction`]s).
	Line = ffi::LUA_HOOKLINE,

	/// Calls the current [`Hook`] every time after Lua executes a specified amount of instructions (see [`LuaState::set_hook`]).
	///
	/// This event only happens for Lua functions (not [`CFunction`]s).
	Count = ffi::LUA_HOOKCOUNT,
}

impl HookEvent {
	/// [`HookEvent::Call`]'s mask value.
	///
	/// See [`LuaState::set_hook`] for more information.
	pub const MASK_CALL: i32 = ffi::LUA_MASKCALL;

	/// [`HookEvent::Return`]'s mask value.
	///
	/// See [`LuaState::set_hook`] for more information.
	pub const MASK_RETURN: i32 = ffi::LUA_MASKRET;

	/// [`HookEvent::Line`]'s mask value.
	///
	/// See [`LuaState::set_hook`] for more information.
	pub const MASK_LINE: i32 = ffi::LUA_MASKLINE;

	/// [`HookEvent::Count`]'s mask value.
	///
	/// See [`LuaState::set_hook`] for more information.
	pub const MASK_COUNT: i32 = ffi::LUA_MASKCOUNT;

	/// Returns this `HookEvent`'s mask value.
	///
	/// See [`LuaState::set_hook`] for more information.
	#[inline]
	#[must_use]
	pub const fn as_mask(self) -> i32 {
		1 << self as i32
	}
}

/// Activation record related to a specified active function.
///
/// All internal fields of this record may be unset if not requested,
/// the methods describe how to request the field they return.
///
/// `DebugInfo`s can be directly created and used (see [`DebugInfo::new`]) or are passed as arguments to hooks (see [`Hook`]).
///
/// Requesting information related to different functions using the same `DebugInfo`
/// will result in the activation record containing information related to both functions simultaneously...which could be confusing.
/// *(Unless the requested information is the same both times, in which case all the info is just overwritten.)*
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct DebugInfo(lua_Debug);

/// Extracts the possibly uninitialized field only if the `DebugInfo::IS_FULLY_INIT` flag is toggled on.
///
/// Otherwise it makes the function return `None`.
macro_rules! get_maybe_uninit_field {
	($self:ident.$zero:literal.$field:ident) => {
		if $self.is_fully_init() {
			// SAFETY: IS_FULLY_INIT should only be toggled on when all fields are initialized.
			unsafe { $self.0.$field.assume_init() }
		} else {
			return None;
		}
	};
	(&raw $self:ident.$zero:literal.$field:ident) => {
		if $self.is_fully_init() { $self.0.$field.as_ptr() } else { return None; }
	};
}

impl DebugInfo {
	/// Creates a new `DebugInfo`.
	///
	/// All the internal fields of the returned activation record will be unset, see [`LuaState::get_info`] to request information.
	#[inline]
	#[must_use]
	pub const fn new() -> Self {
		Self(lua_Debug {
			event: -1 | Self::IS_FULLY_INIT,
			name: MaybeUninit::new(ptr::null()),
			namewhat: MaybeUninit::new(ptr::null()),
			what: MaybeUninit::new(ptr::null()),
			source: MaybeUninit::new(ptr::null()),
			currentline: -1,
			nups: MaybeUninit::new(-1),
			linedefined: MaybeUninit::new(-1),
			lastlinedefined: MaybeUninit::new(-1),
			short_src: MaybeUninit::new([1; ffi::LUA_IDSIZE]),
			i_ci: 0,
		})
	}

	/// Wraps a pre-existing raw [`lua_Debug`].
	///
	/// # Safety
	///
	/// If all `MaybeUninit` fields are initialized:
	/// - `name`, `namewhat`, `what`, and `source` must either be null or point to valid nul-terminated strings.
	/// - `event` must either be `-1` or the numerical value of any [`HookEvent`] value bit or'd with `1 << 31`.
	///
	/// If all `MaybeUninit` fields are uninitialized:
	/// - `event` must be just the numerical value of any [`HookEvent`] value.
	///
	/// A non-modified [`lua_Debug`] obtained from [`DebugInfo::into_raw`] should always be safe to use.
	///
	/// If the private field is somehow accessed, it should preferably be kept at `0` or otherwise any value Lua might set it to.
	#[inline]
	#[must_use]
	pub const unsafe fn from_raw(raw: lua_Debug) -> Self {
		Self(raw)
	}

	/// Returns the wrapped [`lua_Debug`].
	///
	/// There are no guarantees on the raw fields of the returned [`lua_Debug`]:
	/// some fields may have unexpected values and the `MaybeUninit` fields may not be initialized.
	///
	/// The raw [`lua_Debug`] can be safely converted back into a `DebugInfo` using [`DebugInfo::from_raw`], as long as it is not modified.
	#[inline]
	#[must_use]
	pub const fn into_raw(self) -> lua_Debug {
		self.0
	}

	/// Returns a pointer to the wrapped [`lua_Debug`].
	///
	/// This can be used to pass this `DebugInfo` to raw [`ffi`] functions.
	#[inline]
	#[must_use]
	pub const fn as_ptr(&self) -> *const lua_Debug {
		&raw const self.0
	}

	/// Returns a mutable pointer to the wrapped [`lua_Debug`].
	///
	/// This can be used to pass this `DebugInfo` to raw [`ffi`] functions.
	#[inline]
	#[must_use]
	pub const fn as_mut_ptr(&mut self) -> *mut lua_Debug {
		&raw mut self.0
	}

	/// Internal hack to keep `DebugInfo` safe to use:
	/// when received from an [`Hook`], most of the fields are left uninitialized.
	///
	/// Any method that may read a potentially uninitialized field will first check if `event` contains this bit flag:
	/// if not, the field will not be read and `None` will be returned.
	///
	/// If [`LuaState::get_info`] is called using a `DebugInfo` that is not masked as fully initialized,
	/// the potentially uninitialized fields will be set to their default value and the `DebugInfo` will be marked as initialized.
	///
	/// The advantage of this solution is that `DebugInfo`s created from within Rust continue to function almost completely normally,
	/// while `DebugInfo`s received from an [`Hook`] can be used safely and are fully initialized only when actually needed.
	///
	/// The disadvantage is that the `event` field is used for more than it was meant to and requires this bit flag to be removed whenever read,
	/// which is an acceptable trade-off in my opinion.
	const IS_FULLY_INIT: i32 = 1 << 31;

	#[must_use]
	const fn is_fully_init(&self) -> bool {
		self.0.event & Self::IS_FULLY_INIT != 0
	}

	/// Returns the literal source of the specified function if said function was loaded via a string.
	/// Otherwise, it returns the chunk name, which is usually `'@'` followed by the file path or `"=[C]"` (but could be anything).
	///
	/// This field will only be set if the `'S'` selector is used (see [`LuaState::get_info`]), and will always be `None` otherwise.
	#[inline]
	#[must_use]
	pub const fn source(&self) -> Option<&CStr> {
		let source = get_maybe_uninit_field!(self.0.source);
		// SAFETY: self.0.source should always be a valid nul-terminated string pointer when not null.
		map_ptr!(source, unsafe { CStr::from_ptr(source) })
	}

	/// Returns a "printable" version of [`DebugInfo::source`], intended to be used in error messages (which Lua does).
	///
	/// The returned string is never longer than 60 characters.
	///
	/// This field will only be set if the `'S'` selector is used (see [`LuaState::get_info`]), and will always be `None` otherwise.
	#[inline]
	#[must_use]
	pub const fn short_source(&self) -> Option<&CStr> {
		let short_source = get_maybe_uninit_field!(&raw self.0.short_src);
		// SAFETY: self.0.short_src is initialized and casting from [c_char] to [u8] is safe since they're both just 1 byte.
		match CStr::from_bytes_until_nul(unsafe { &*short_source.cast::<[u8; ffi::LUA_IDSIZE]>() }) {
			Ok(short_src) => Some(short_src),
			Err(_) => None,
		}
	}

	/// Returns the line number where the definition of the specified Lua function starts.
	/// [`CFunction`]s return `None` instead.
	///
	/// This field will only be set if the `'S'` selector is used (see [`LuaState::get_info`]), and will always be `None` otherwise.
	#[inline]
	#[must_use]
	pub const fn line_defined(&self) -> Option<i32> {
		match get_maybe_uninit_field!(self.0.linedefined) {
			-1 => None,
			linedefined => Some(linedefined),
		}
	}

	/// Returns the line number where the definition of the specified Lua function ends.
	/// [`CFunction`]s return `None` instead.
	///
	/// This field will only be set if the `'S'` selector is used (see [`LuaState::get_info`]), and will always be `None` otherwise.
	#[inline]
	#[must_use]
	pub const fn last_line_defined(&self) -> Option<i32> {
		match get_maybe_uninit_field!(self.0.lastlinedefined) {
			-1 => None,
			lastlinedefined => Some(lastlinedefined),
		}
	}

	/// Returns what the specified function is:
	/// - `"Lua"` for Lua functions.
	/// - `"C"` for [`CFunction`]s.
	/// - `"main"` if it's the main part of a chunk.
	///
	/// This field will only be set if the `'S'` selector is used (see [`LuaState::get_info`]), and will always be `None` otherwise.
	#[inline]
	#[must_use]
	pub const fn what(&self) -> Option<&CStr> {
		let what = get_maybe_uninit_field!(self.0.what);
		// SAFETY: self.0.what should always be a valid nul-terminated string pointer when not null.
		map_ptr!(what, unsafe { CStr::from_ptr(what) })
	}

	/// Returns, if known, the current line where the specified function is executing.
	/// `None` is returned if the current line is not known.
	///
	/// This field will only be set if the `'l'` selector is used (see [`LuaState::get_info`]) or within [`Hook`]s called by [`HookEvent::Line`]
	/// (see [`Hook`]), and will always be `None` otherwise.
	#[inline]
	#[must_use]
	pub const fn current_line(&self) -> Option<i32> {
		match self.0.currentline {
			-1 => None,
			currentline => Some(currentline),
		}
	}

	/// Returns a reasonable name for the specified function based on how it was called, or `None` if no suitable name could be found.
	///
	/// This field will only be set if the `'n'` selector is used (see [`LuaState::get_info`]), and will always be `None` otherwise.
	#[inline]
	#[must_use]
	pub const fn name(&self) -> Option<&CStr> {
		let name = get_maybe_uninit_field!(self.0.name);
		// SAFETY: self.0.name should always be a valid nul-terminated string pointer when not null.
		map_ptr!(name, unsafe { CStr::from_ptr(name) })
	}

	/// Returns an explenation of how [`DebugInfo::name`] is found.
	///
	/// Possible returned values are:
	/// - `"global"`.
	/// - `"local"`.
	/// - `"method"`.
	/// - `"field"`.
	/// - `"upvalue"`.
	/// - `"metamethod"`.
	/// - `""`. *(Returned when no other option applies or no suitable name was found.)*
	///
	/// This field will only be set if the `'n'` selector is used (see [`LuaState::get_info`]), and will always be `None` otherwise.
	#[inline]
	#[must_use]
	pub const fn name_what(&self) -> Option<&CStr> {
		let namewhat = get_maybe_uninit_field!(self.0.namewhat);
		// SAFETY: self.0.namewhat should always be a valid nul-terminated string pointer when not null.
		map_ptr!(namewhat, unsafe { CStr::from_ptr(namewhat) })
	}

	/// Returns the number of upvalues of the specified function.
	///
	/// This field will only be set if the `'u'` selector is used (see [`LuaState::get_info`]), and will always be `None` otherwise.
	#[inline]
	#[must_use]
	pub const fn n_upvalues(&self) -> Option<i32> {
		match get_maybe_uninit_field!(self.0.nups) {
			-1 => None,
			nups => Some(nups),
		}
	}

	/// Returns the [`HookEvent`] that called the current [`Hook`].
	///
	/// This field will only be set if this `DebugInfo` comes from the [`Hook`]'s arguments (see [`Hook`]), and will always be `None` otherwise.
	#[inline]
	#[must_use]
	pub const fn event(&self) -> Option<HookEvent> {
		match self.0.event {
			-1 => None, // SAFETY: self.0.event (without the IS_FULLY_INIT flag) should always be a valid HookEvent.
			event => Some(unsafe { mem::transmute::<i32, HookEvent>(event & !Self::IS_FULLY_INIT) })
		}
	}
}

impl Default for DebugInfo {
	#[inline]
	fn default() -> Self {
		Self::new()
	}
}

/// Debug interface functions.
///
/// See [§3.8](https://www.lua.org/manual/5.1/manual.html#3.8) for more information on the Debug interface.
///
/// *[See also the `DebugInfo` struct](struct.DebugInfo.html)*.
impl LuaState {
	/// Requests information about a specified function. The retrieved information will be stored in `info`.
	///
	/// There are three ways to specify a function:
	/// - From the interpreter runtime stack by using [`LuaState::get_stack`].
	/// - From the top element by adding `'>'` at the start of `what` (the element will be popped).
	/// - Pre-specified when [`DebugInfo`] is received from an [`Hook`]'s arguments (see [`Hook`]).
	///
	/// The type of information requested is based on which "selectors" (characters) `what` contains:
	/// - `'n'` will set [`DebugInfo::name`] and [`DebugInfo::name_what`].
	/// - `'S'` will set [`DebugInfo::source`], [`DebugInfo::short_source`], [`DebugInfo::line_defined`],
	///   [`DebugInfo::last_line_defined`], and [`DebugInfo::what`].
	/// - `'l'` will set [`DebugInfo::current_line`].
	/// - `'u'` will set [`DebugInfo::n_upvalues`].
	/// - `'f'` pushes onto the stack the specified function itself.
	/// - `'L'` pushes onto the stack a table whose indices are the number of valid lines (with associated code) of the specified function.
	///
	/// *(The selectors are executed based on their order in `what`.)*
	///
	/// If an invalid character is present in `what`, or `'>'` is used and the top elemenet is not a function,
	/// this function will end early and return `false`. `true` is returned otherwise.
	///
	/// # Panics
	///
	/// Panics if none of the three ways of specifying a function are attempted.
	#[inline]
	pub fn get_info(&mut self, what: &CStr, info: &mut DebugInfo) -> bool {
		// SAFETY: c_char can be casted as u8 (they're both 1 byte) and CStrs should always have at least 1 character (the nul terminator).
		assert!(info.0.i_ci != 0 || unsafe { *what.as_ptr().cast::<u8>() == b'>' }, "tried to get debug information without specifying a function");

		if !info.is_fully_init() {
			// Initialize all MaybeUninit fields and mark the DebugInfo as fully initialized.
			info.0.name.write(ptr::null());
			info.0.namewhat.write(ptr::null());
			info.0.what.write(ptr::null());
			info.0.source.write(ptr::null());
			info.0.nups.write(-1);
			info.0.linedefined.write(-1);
			info.0.lastlinedefined.write(-1);
			info.0.short_src.write([1; LUA_IDSIZE]);
			info.0.event |= DebugInfo::IS_FULLY_INIT;
		}

		// SAFETY: self.0, what, and info should always be valid and info either has a valid i_ci value or '>' is being used.
		unsafe { ffi::lua_getinfo(self.0, what.as_ptr(), info.as_mut_ptr()) != 0 }
	}

	/// Prepare the given `info` to specify the function at the given `level`:
	/// level `0` is the current running function, level `1` is the function that called the current running function, and so on.
	///
	/// If the given `level` is invalid, `info` is not prepared and the function returns `false`. `true` is returned otherwise.
	///
	/// This function is meant to be used alongside [`LuaState::get_info`] to get information about the specified function.
	#[inline]
	pub fn get_stack(&self, level: i32, info: &mut DebugInfo) -> bool {
		// SAFETY: self.0 and info are always valid.
		let success = unsafe { ffi::lua_getstack(self.0, level, info.as_mut_ptr()) != 0 };

		if !success {
			// Reset i_ci to keep it marked as invalid.
			info.0.i_ci = 0;
		}

		success
	}

	/// Get information about a local variable of a specified function.
	///
	/// There are three ways to specify a function:
	/// - From the interpreter runtime stack by using [`LuaState::get_stack`].
	/// - From the top element by passing `None` for `info` (the element will *not* be popped).
	/// - Pre-specified when [`DebugInfo`] is received from an [`Hook`]'s arguments (see [`Hook`]).
	///
	/// `n` selects which local to get, `1` being the first local and so on until the last local.
	/// Negative values of `n` can be used to get vararg arguments.
	///
	/// When `info` is `Some`, this function will push to the stack the local's value and return the local's name.
	/// Otherwise only the name is returned and nothing is pushed to the stack.
	///
	/// Invalid values of `n` or the top element not being a function (when `info` is `None`)
	/// will result in the function returning `None` and pushing nothing to the stack.
	///
	/// If the returned name is enclosed in round brackets, the queried local is an internal variable.
	///
	/// # Panics
	///
	/// Panics if none of the three ways of specifying a function are attempted.
	#[inline]
	pub fn get_local(&mut self, info: Option<&DebugInfo>, n: i32) -> Option<&CStr> {
		if let Some(info) = info {
			assert!(info.0.i_ci != 0, "tried to get a local without specifying a function");
		}

		// SAFETY: self.0 and info's pointer are always valid, lua_getlocal accepts a null lua_Debug,
		// and lua_getlocal returns valid nul-terminated string pointers when not null.
		let local = unsafe { ffi::lua_getlocal(self.0, info.map_or(ptr::null(), DebugInfo::as_ptr), n) };
		map_ptr!(local, unsafe { CStr::from_ptr(local) })
	}

	/// Sets the value of a local variable of a specified function to the value of the top element (which is popped),
	/// returning the local's name.
	///
	/// There are *two* ways to specify a function:
	/// - From the interpreter runtime stack by using [`LuaState::get_stack`].
	/// - Pre-specified when [`DebugInfo`] is received from an [`Hook`]'s arguments (see [`Hook`]).
	///
	/// `n` selects which local to get, `1` being the first local and so on until the last local.
	/// Negative values of `n` can be used to get vararg arguments.
	///
	/// Invalid values of `n` will result in the function returning `None` and not changing any local, but the top element will still be popped!
	///
	/// If the returned name is enclosed in round brackets, the changed local is an internal variable.
	///
	/// # Panics
	///
	/// Panics if none of the two ways of specifying a function are attempted or if the stack is empty.
	pub fn set_local(&mut self, info: &DebugInfo, n: i32) -> Option<&CStr> {
		assert!(self.get_top() > 0, "tried to set a local's value despite having an empty stack");
		assert!(info.0.i_ci != 0, "tried to set a local's value without specifying a function");

		// SAFETY: self.0 and info's pointer are always valid, and lua_setlocal returns valid nul-terminated string pointers when not null.
		let local = unsafe { ffi::lua_setlocal(self.0, info.as_ptr(), n) };
		map_ptr!(local, unsafe { CStr::from_ptr(local) })
	}

	/// Get information about the `n`th upvalue of the function at index `func_index`.
	///
	/// The upvalue's value is pushed onto the stack and its name is returned.
	///
	/// If the `n`th upvalue doesn't exist or the element at index `func_index` is not a function,
	/// `None` is returned and nothing is pushed onto the stack.
	///
	/// If the function is a [`CFunction`], the returned upvalue name will be an empty string.
	#[inline]
	pub fn get_upvalue(&mut self, func_index: i32, n: i32) -> Option<&CStr> {
		// SAFETY: self.0 is always valid and lua_getupvalue returns valid nul-terminated string pointers when not null.
		let upvalue = unsafe { ffi::lua_getupvalue(self.0, func_index, n) };
		map_ptr!(upvalue, unsafe { CStr::from_ptr(upvalue) })
	}

	/// Sets the value of the `n`th upvalue of the function at index `func_index` to the value of the top element (which is popped),
	/// returning the upvalue's name.
	///
	/// If the `n`th upvalue doesn't exist or the element at index `func_index` is not a function,
	/// `None` is returned and the upvalue is not changed (the top element will not be popped).
	///
	/// # Panics
	///
	/// Panics if the stack is empty.
	#[inline]
	pub fn set_upvalue(&mut self, func_index: i32, n: i32) -> Option<&CStr> {
		assert!(self.get_top() > 0, "tried to set an upvalue's value despite having an empty stack");

		// SAFETY: self.0 is always valid and lua_setupvalue returns valid nul-terminated string pointers when not null.
		let upvalue = unsafe { ffi::lua_setupvalue(self.0, func_index, n) };
		map_ptr!(upvalue, unsafe { CStr::from_ptr(upvalue) })
	}

	/// Returns `true` if the `n`th upvalue of the function at index `func_index` exists, `false` otherwise.
	#[inline]
	pub fn is_function_upvalue(&mut self, func_index: i32, n: i32) -> bool {
		let exists = self.get_upvalue(func_index, n).is_some();

		if exists {
			// Remove the upvalue's value from the stack.
			self.pop(1);
		}

		exists
	}

	/// Returns an unique generic pointer for the `n`th upvalue of the function at index `func_index`.
	///
	/// Different upvalues will always return different pointers,
	/// thus the pointers can be compared to see if different functions share the same upvalue.
	///
	/// If `func_index` or `n` are invalid a null pointer will be returned instead.
	///
	/// There is no intended way to convert the pointer to the upvalue itself.
	#[inline]
	pub fn upvalue_id(&mut self, func_index: i32, n: i32) -> *mut () {
		if self.is_function_upvalue(func_index, n) {
			// SAFETY: self.0 is always valid and func_index and n are also valid.
			unsafe { ffi::lua_upvalueid(self.0, func_index, n).cast() }
		} else {
			ptr::null_mut()
		}
	}

	/// Returns the current [`Hook`], or `None` if no hook is currently enabled.
	///
	/// [`lua_Hook`] is returned instead of [`Hook`] as this function cannot determine its safety.
	#[inline]
	pub fn get_hook(&self) -> Option<lua_Hook> {
		// SAFETY: self.0 is always valid.
		unsafe { ffi::lua_gethook(self.0) }
	}

	/// Sets a new debugging [`Hook`] function, replacing the previous hook (see [`Hook`]).
	///
	/// `mask` specifies which [`HookEvent`]s can call `hook`,
	/// the "mask value" of an [`HookEvent`] can be obtained from [`HookEvent::as_mask`] or from the `HookEvent::MASK_*` constants.
	/// Different mask values can be bit or'd together so that the hook can be called from different events.
	///
	/// If `mask` is `0` or invalid, this function behaves the same as [`LuaState::unset_hook`].
	///
	/// If [`HookEvent::Count`] is one of the possible events for this hook, `count` specifies the amounts of instructions inbetween each call
	/// (it's ignored otherwise).
	///
	/// # Examples
	///
	/// ```
	/// # use low_luajit::{LuaState, DebugInfo, HookEvent};
	/// extern "C-unwind" fn example_hook(lua: LuaState, info: &mut DebugInfo) {
	///     println!("Hook called by {:?}!", info.event());
	/// }
	///
	/// # fn example(lua: LuaState) {
	/// lua.set_hook(example_hook, HookEvent::MASK_CALL | HookEvent::MASK_RETURN, 0);
	/// # }
	/// ```
	#[inline]
	pub fn set_hook(&self, hook: Hook, mask: i32, count: i32) {
		// SAFETY: self.0 is always valid and hook will be called properly.
		unsafe { ffi::lua_sethook(self.0, Some(hook.to_raw()), mask, count); }
	}

	/// Disables the current [`Hook`], without replacing it with another.
	///
	/// To replace it with a new one instead, see [`LuaState::set_hook`].
	#[inline]
	pub fn unset_hook(&self) {
		// SAFETY: self.0 is always valid.
		unsafe { ffi::lua_sethook(self.0, None, 0, 0); }
	}

	/// Returns the current [`Hook`]'s mask value.
	///
	/// See [`LuaState::set_hook`] for more information.
	#[inline]
	pub fn get_hook_mask(&self) -> i32 {
		// SAFETY: self.0 is always valid.
		unsafe { ffi::lua_gethookmask(self.0) }
	}

	/// Returns the current [`Hook`]'s "count" (not the *current* count, simply the value that was specified).
	///
	/// See [`LuaState::set_hook`] for more information.
	#[inline]
	pub fn get_hook_count(&self) -> i32 {
		// SAFETY: self.0 is always valid.
		unsafe { ffi::lua_gethookcount(self.0) }
	}

	// TODO: set_hook_mask or set_hook_count for convenience?
}