Skip to main content

low_luajit/lua/type/
boolean.rs

1use crate::{AmountReturned, LuaState, ffi};
2
3const fn likely(b: bool) -> bool {
4	if !b {
5		#[cfg(feature = "no_msrv")]
6		#[clippy::msrv = "1.95.0"]
7		core::hint::cold_path();
8	}
9
10	b
11}
12
13/// Boolean related functions.
14impl LuaState {
15	/// Returns `true` if the value at the given acceptable `index` is a boolean, `false` otherwise.
16	#[inline]
17	#[must_use]
18	pub fn is_boolean(&self, index: i32) -> bool {
19		// SAFETY: self.0 is always valid.
20		unsafe { ffi::lua_isboolean(self.0, index) != 0 }
21	}
22
23	/// Converts the value at the given acceptable `index` to a boolean and returns it.
24	///
25	/// Any value besides `false` or `nil` is converted to `true`, `false` otherwise.
26	///
27	/// This conversion *does not* affect the element in the stack itself (it stays as is).
28	#[inline]
29	#[must_use]
30	pub fn to_boolean(&self, index: i32) -> bool {
31		// SAFETY: self.0 is always valid.
32		unsafe { ffi::lua_toboolean(self.0, index) != 0 }
33	}
34
35	/// Pushes the given `boolean` onto the stack.
36	#[inline]
37	pub fn push_boolean(&mut self, boolean: bool) {
38		// SAFETY: self.0 is always valid.
39		unsafe { ffi::lua_pushboolean(self.0, i32::from(boolean)); }
40	}
41
42	/// Checks if there's a boolean at the given index `arg_n` and returns it.
43	///
44	/// If the check fails, [`LuaState::type_error`] is called using `arg_n`.
45	///
46	/// # Lua Errors
47	///
48	/// Intentionally errors if the check fails.
49	#[inline]
50	pub fn check_boolean(&self, arg_n: i32) -> bool {
51		if likely(self.is_boolean(arg_n)) {
52			self.to_boolean(arg_n)
53		} else {
54			self.type_error(arg_n, c"boolean");
55		}
56	}
57
58	/// Behaves exactly as [`LuaState::check_boolean`],
59	/// but returns `default` instead of erroring when the element at the given index `arg_n` is `nil` (or non-existing).
60	#[inline]
61	pub fn opt_boolean(&self, arg_n: i32, default: bool) -> bool {
62		if likely(self.is_boolean(arg_n)) {
63			self.to_boolean(arg_n)
64		} else if self.is_none_or_nil(arg_n) {
65			default
66		} else {
67			self.type_error(arg_n, c"boolean");
68		}
69	}
70
71	/// Finishes the currently called [`CFunction`], returning the given `boolean` to the caller.
72	///
73	/// The `LuaState` wrapper is consumed to prevent invalidating the `AmountReturned` (the Lua state itself is left intact).
74	///
75	/// [`CFunction`]: ./type.CFunction.html
76	#[inline]
77	pub fn return_boolean(mut self, boolean: bool) -> AmountReturned {
78		self.push_boolean(boolean);
79
80		// SAFETY: There should always be at least one element in the stack.
81		unsafe { AmountReturned::unchecked(1) }
82	}
83}