use koto::{Result, derive::*, prelude::*, runtime};
fn main() -> Result<()> {
let script = "
my_type = make_my_type 41
print my_type.get()
print my_type.set 99
";
let mut koto = Koto::default();
koto.prelude()
.add_fn("make_my_type", |ctx| match ctx.args() {
[KValue::Number(n)] => Ok(MyType::make_koto_object(*n).into()),
unexpected => unexpected_args("|Number|", unexpected),
});
koto.compile_and_run(script)?;
Ok(())
}
#[derive(Clone, Copy, KotoCopy, KotoType)]
struct MyType(i64);
#[koto_impl]
impl MyType {
fn make_koto_object(n: KNumber) -> KObject {
let my_type = Self(n.into());
KObject::from(my_type)
}
#[koto_method]
fn get(&self) -> runtime::Result<KValue> {
Ok(self.0.into())
}
#[koto_method]
fn set(ctx: MethodContext<Self>) -> runtime::Result<KValue> {
match ctx.args {
[KValue::Number(n)] => {
ctx.instance_mut()?.0 = n.into();
ctx.instance_result()
}
unexpected => unexpected_args("|Number|", unexpected),
}
}
}
impl KotoObject for MyType {
fn display(&self, ctx: &mut DisplayContext) -> runtime::Result<()> {
ctx.append(format!("MyType({})", self.0));
Ok(())
}
}