door.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. *BasicObject
  6. name string
  7. locked bool
  8. opened bool
  9. }
  10. var _ Value = &Door{}
  11. const DoorType = TypeValue("Door")
  12. func (door * Door) String() string {
  13. return fmt.Sprintf("Door: %s %v %v", door.name, door.locked, door.opened)
  14. }
  15. func (*Door) Type() TypeValue {
  16. return DoorType
  17. }
  18. func (from * Door) Convert(to interface{}) error {
  19. switch toPtr := to.(type) {
  20. case **Door:
  21. (*toPtr) = from
  22. case *Door:
  23. (*toPtr) = *from
  24. case *Value:
  25. (*toPtr) = from
  26. default:
  27. return NewErrorValuef("Cannot convert DoorValue value %v to %v", from, to)
  28. }
  29. return nil
  30. }
  31. func door(vm *VM, val ...Value) [] Value {
  32. var name string
  33. var locked bool
  34. _, err := ParseOptArgs(val, 1, &name, &locked)
  35. if err != nil {
  36. return Fail(err)
  37. }
  38. d := &Door{name: name, locked: locked, opened:false}
  39. d.BasicObject = NewBasicObject(d, nil)
  40. d.Getter("name", func() Value {
  41. return StringValue(d.name)
  42. })
  43. d.Getter("locked", func() Value {
  44. return BoolValue(d.locked)
  45. })
  46. d.Getter("opened", func() Value {
  47. return BoolValue(d.opened)
  48. })
  49. d.Method("open", func(...Value) []Value {
  50. d.Open()
  51. return Ok(d)
  52. })
  53. return Ok(d)
  54. }
  55. func (door * Door) Open() {
  56. door.opened = true
  57. }
  58. func openDoor(vm *VM, val ...Value) [] Value {
  59. var door *Door
  60. _, err := ParseArgs(val, &door)
  61. if err != nil {
  62. return Fail(err)
  63. }
  64. if door == nil {
  65. return Fail(NewErrorValuef("Door may not be nil."))
  66. }
  67. door.Open()
  68. return Ok(door)
  69. }
  70. func nameDoor(vm *VM, val ...Value) [] Value {
  71. var door *Door
  72. var name string
  73. _, err := ParseArgs(val, &door, &name)
  74. if err != nil {
  75. return Fail(err)
  76. }
  77. if door == nil {
  78. return Fail(NewErrorValuef("Door may not be nil."))
  79. }
  80. if name == "" {
  81. return Fail(NewErrorValuef("Name may not be empty."))
  82. }
  83. door.name = name
  84. return Ok(door)
  85. }
  86. func RegisterDoor(vm * VM) {
  87. vm.RegisterBuiltin("door", door)
  88. vm.RegisterBuiltin("openDoor", openDoor).Takes(DoorType).Returns(DoorType)
  89. vm.RegisterBuiltin("nameDoor", nameDoor).Takes(DoorType).Returns(DoorType)
  90. vm.Register("Door", DoorType)
  91. vm.AddOverloadByName("open", "openDoor", 0)
  92. vm.AddOverloads("name", Over("nameDoor", 0, DoorType))
  93. }