Skip to main content

low_luajit/lua/type/
boolean.rs

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