Skip to content

Commit

Permalink
Improve Any derive documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
udoprog committed Apr 7, 2024
1 parent fea782a commit 4c8eba1
Showing 1 changed file with 36 additions and 8 deletions.
44 changes: 36 additions & 8 deletions crates/rune/src/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,26 +56,54 @@ use crate::hash::Hash;
/// ```
pub use rune_macros::Any;

/// A trait which can be stored inside of an [AnyObj](crate::runtime::AnyObj).
/// Derive for types which can be used inside of Rune.
///
/// We use our own marker trait that must be explicitly derived to prevent other
/// VM native types (like strings) which also implement `std::any::Any` from
/// being stored as an `AnyObj`.
/// Rune only supports two types, *built-in* types [`String`] and *external*
/// types which derive `Any`. Before they can be used they must be registered in
/// [`Context::install`] through a [`Module`].
///
/// This means, that only types which derive `Any` can be used inside of the VM:
/// [`AnyObj`]: crate::runtime::AnyObj
/// [`Context::install`]: crate::Context::install
/// [`Module`]: crate::Module
/// [`String`]: std::string::String
///
/// # Examples
///
/// ```
/// use rune::Any;
///
/// #[derive(Any)]
/// struct Npc {
/// name: String,
/// #[rune(get)]
/// health: u32,
/// }
///
/// impl Npc {
/// /// Construct a new NPC.
/// #[rune::function(path = Self::new)]
/// fn new(health: u32) -> Self {
/// Self {
/// health
/// }
/// }
///
/// /// Damage the NPC with the given `amount`.
/// #[rune::function]
/// fn damage(&mut self, amount: u32) {
/// self.health -= amount;
/// }
/// }
///
/// fn install() -> Result<rune::Module, rune::ContextError> {
/// let mut module = rune::Module::new()?;
/// module.ty::<Npc>()?;
/// module.function_meta(Npc::new)?;
/// module.function_meta(Npc::damage)?;
/// Ok(module)
/// }
/// ```
pub trait Any: Named + any::Any {
/// The type hash of the type.
///
/// TODO: make const field when `TypeId::of` is const.
fn type_hash() -> Hash;
}

Expand Down

0 comments on commit 4c8eba1

Please sign in to comment.