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
use crate::{AmountReturned, LuaState, ffi};
const fn likely(b: bool) -> bool {
if !b {
#[cfg(feature = "no_msrv")]
#[clippy::msrv = "1.95.0"]
core::hint::cold_path();
}
b
}
/// Boolean related functions.
impl LuaState {
/// Returns `true` if the value at the given acceptable `index` is a boolean, `false` otherwise.
#[inline]
#[must_use]
pub fn is_boolean(&self, index: i32) -> bool {
// SAFETY: self.0 is always valid.
unsafe { ffi::lua_isboolean(self.0, index) != 0 }
}
/// Converts the value at the given acceptable `index` to a boolean and returns it.
///
/// Any value besides `false` or `nil` is converted to `true`, `false` otherwise.
///
/// This conversion *does not* affect the element in the stack itself (it stays as is).
#[inline]
#[must_use]
pub fn to_boolean(&self, index: i32) -> bool {
// SAFETY: self.0 is always valid.
unsafe { ffi::lua_toboolean(self.0, index) != 0 }
}
/// Pushes the given `boolean` onto the stack.
#[inline]
pub fn push_boolean(&mut self, boolean: bool) {
// SAFETY: self.0 is always valid.
unsafe { ffi::lua_pushboolean(self.0, i32::from(boolean)); }
}
/// Checks if there's a boolean at the given index `arg_n` and returns it.
///
/// If the check fails, [`LuaState::type_error`] is called using `arg_n`.
///
/// # Lua Errors
///
/// Intentionally errors if the check fails.
#[inline]
pub fn check_boolean(&self, arg_n: i32) -> bool {
if likely(self.is_boolean(arg_n)) {
self.to_boolean(arg_n)
} else {
self.type_error(arg_n, c"boolean");
}
}
/// Behaves exactly as [`LuaState::check_boolean`],
/// but returns `default` instead of erroring when the element at the given index `arg_n` is `nil` (or non-existing).
#[inline]
pub fn opt_boolean(&self, arg_n: i32, default: bool) -> bool {
if likely(self.is_boolean(arg_n)) {
self.to_boolean(arg_n)
} else if self.is_none_or_nil(arg_n) {
default
} else {
self.type_error(arg_n, c"boolean");
}
}
/// Finishes the currently called [`CFunction`], returning the given `boolean` to the caller.
///
/// The `LuaState` wrapper is consumed to prevent invalidating the `AmountReturned` (the Lua state itself is left intact).
///
/// [`CFunction`]: ./type.CFunction.html
#[inline]
pub fn return_boolean(mut self, boolean: bool) -> AmountReturned {
self.push_boolean(boolean);
// SAFETY: There should always be at least one element in the stack.
unsafe { AmountReturned::unchecked(1) }
}
}