door.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package muesli
  2. import "fmt"
  3. // Door is an example of how to wrap a custom type in Muesli.
  4. type Door struct {
  5. name string
  6. locked bool
  7. opened bool
  8. }
  9. var _ Value = &Door{}
  10. const DoorType = TypeValue("Door")
  11. func (door * Door) String() string {
  12. return fmt.Sprintf("Door: %s %v %v", door.name, door.locked, door.opened)
  13. }
  14. func (*Door) Type() TypeValue {
  15. return DoorType
  16. }
  17. func (from * Door) Convert(to interface{}) error {
  18. switch toPtr := to.(type) {
  19. case **Door:
  20. (*toPtr) = from
  21. case *Door:
  22. (*toPtr) = *from
  23. case *Value:
  24. (*toPtr) = from
  25. default:
  26. return NewErrorValuef("Cannot convert DoorValue value %v to %v", from, to)
  27. }
  28. return nil
  29. }
  30. func door(vm *VM, val ...Value) [] Value {
  31. var name string
  32. var locked bool
  33. _, err := ParseOptArgs(val, 1, &name, &locked)
  34. if err != nil {
  35. return Fail(err)
  36. }
  37. d := &Door{name: name, locked: locked, opened:false}
  38. return Ok(d)
  39. }
  40. func (door * Door) Open() {
  41. door.opened = true
  42. }
  43. func openDoor(vm *VM, val ...Value) [] Value {
  44. var door *Door
  45. _, err := ParseArgs(val, &door)
  46. if err != nil {
  47. return Fail(err)
  48. }
  49. if door == nil {
  50. return Fail(NewErrorValuef("Door may not be nil."))
  51. }
  52. door.Open()
  53. return Ok(door)
  54. }
  55. func nameDoor(vm *VM, val ...Value) [] Value {
  56. var door *Door
  57. var name string
  58. _, err := ParseArgs(val, &door, &name)
  59. if err != nil {
  60. return Fail(err)
  61. }
  62. if door == nil {
  63. return Fail(NewErrorValuef("Door may not be nil."))
  64. }
  65. if name == "" {
  66. return Fail(NewErrorValuef("Name may not be empty."))
  67. }
  68. door.name = name
  69. return Ok(door)
  70. }
  71. func RegisterDoor(vm * VM) {
  72. vm.RegisterBuiltin("door", door)
  73. vm.RegisterBuiltin("openDoor", openDoor).Takes(DoorType).Returns(DoorType)
  74. vm.RegisterBuiltin("nameDoor", nameDoor).Takes(DoorType).Returns(DoorType)
  75. vm.Register("Door", DoorType)
  76. vm.AddOverloadByName("open", "openDoor", 0)
  77. vm.AddOverloads("name", Over("nameDoor", 0, DoorType))
  78. }