|
1 | 1 | #![cfg(feature = "macros")] |
2 | 2 |
|
3 | | -use mlua::{Lua, Result, UserData}; |
| 3 | +use mlua::{AnyUserData, Lua, Result, UserData}; |
4 | 4 |
|
5 | 5 | #[derive(Default, Clone, Debug, UserData)] |
6 | 6 | struct Rectangle { |
@@ -412,6 +412,65 @@ fn test_known_borrow_wrappers() -> Result<()> { |
412 | 412 | Ok(()) |
413 | 413 | } |
414 | 414 |
|
| 415 | +#[derive(Clone, Copy, Debug, PartialEq, UserData)] |
| 416 | +struct Vec2 { |
| 417 | + x: i32, |
| 418 | + y: i32, |
| 419 | +} |
| 420 | + |
| 421 | +#[mlua::userdata_impl] |
| 422 | +impl Vec2 { |
| 423 | + #[lua(infallible)] |
| 424 | + fn new(x: i32, y: i32) -> Self { |
| 425 | + Vec2 { x, y } |
| 426 | + } |
| 427 | + |
| 428 | + #[lua(meta, infallible, name = "__add")] |
| 429 | + fn add(this: &Vec2, other: &Vec2) -> Vec2 { |
| 430 | + Vec2 { |
| 431 | + x: this.x + other.x, |
| 432 | + y: this.y + other.y, |
| 433 | + } |
| 434 | + } |
| 435 | + |
| 436 | + #[lua(meta, infallible, name = "__eq")] |
| 437 | + fn eq(this: &Vec2, other: &Vec2) -> bool { |
| 438 | + this == other |
| 439 | + } |
| 440 | + |
| 441 | + #[lua(meta, infallible, name = "__call")] |
| 442 | + fn call(_lua: &Lua, _proxy: AnyUserData, x: i32, y: i32) -> Vec2 { |
| 443 | + Self::new(x, y) |
| 444 | + } |
| 445 | +} |
| 446 | + |
| 447 | +#[test] |
| 448 | +fn test_static_metamethods() { |
| 449 | + let lua = Lua::new(); |
| 450 | + lua.globals() |
| 451 | + .set("Vec2", lua.create_proxy::<Vec2>().unwrap()) |
| 452 | + .unwrap(); |
| 453 | + lua.load( |
| 454 | + r#" |
| 455 | + local a = Vec2.new(1, 2) |
| 456 | + local b = Vec2.new(3, 4) |
| 457 | +
|
| 458 | + local c = a + b |
| 459 | + assert(c.x == 4, "__add x should be 1 + 3 = 4, got " .. tostring(c.x)) |
| 460 | + assert(c.y == 6, "__add y should be 2 + 4 = 6, got " .. tostring(c.y)) |
| 461 | +
|
| 462 | + assert(a == Vec2.new(1, 2), "__eq should report vectors equal") |
| 463 | + assert(a ~= b, "__eq should report vectors unequal") |
| 464 | +
|
| 465 | + -- `__call` on the proxy |
| 466 | + local d = Vec2(7, 14) |
| 467 | + assert(d.x == 7 and d.y == 14, "__call should build Vec2(7, 14)") |
| 468 | + "#, |
| 469 | + ) |
| 470 | + .exec() |
| 471 | + .unwrap(); |
| 472 | +} |
| 473 | + |
415 | 474 | #[cfg(feature = "async")] |
416 | 475 | mod async_tests { |
417 | 476 | use mlua::{Lua, Result, UserData}; |
|
0 commit comments