vm_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package muesli
  2. import (
  3. "fmt"
  4. "testing"
  5. )
  6. func TestVm1(test *testing.T) {
  7. vm := NewVM()
  8. bi := vm.RegisterBuiltin("foo", func(vm *VM, args ...Value) []Value {
  9. fmt.Printf("I am foo. See me foo?")
  10. return EmptyValueArray()
  11. })
  12. if vm == nil {
  13. test.Errorf("Could not construct VM")
  14. }
  15. if _, ok := bi.(BuiltinValue); !ok {
  16. test.Errorf("Could not construct register a builtin function.")
  17. }
  18. foo := vm.Lookup("foo")
  19. biv, ok := foo.(BuiltinValue)
  20. if foo == nil || !ok {
  21. test.Errorf("Could not look up foo.")
  22. }
  23. biv.Handler(vm)
  24. }
  25. func ExampleVm1() {
  26. vm := NewVM()
  27. vm.RegisterBuiltin("foo", func(vm *VM, args ...Value) []Value {
  28. fmt.Printf("I am foo. See me foo?")
  29. return EmptyValueArray()
  30. })
  31. foo := vm.Lookup("foo")
  32. biv, ok := foo.(BuiltinValue)
  33. if foo == nil || !ok {
  34. fmt.Println("Could not look up foo.")
  35. }
  36. //Output: I am foo. See me foo?
  37. biv.Handler(vm)
  38. }
  39. func ExampleVm2() {
  40. vm := NewVM()
  41. vm.RegisterBuiltin("foo", func(vm *VM, args ...Value) []Value {
  42. var s string
  43. From(args[0], &s)
  44. fmt.Printf("I am foo. See me %s?", s)
  45. return EmptyValueArray()
  46. })
  47. //Output: I am foo. See me bar?
  48. vm.CallNamed("foo", To("bar"))
  49. }
  50. func ExampleVm3() {
  51. vm := NewVM()
  52. vm.RegisterBuiltin("multi", func(vm *VM, args ...Value) []Value {
  53. var one string
  54. var two int64
  55. err := ListFrom(args, &one, &two)
  56. if err != nil {
  57. fmt.Printf("Error: %s", err.Error())
  58. }
  59. fmt.Printf("I am multi. See me %s, %d?", one, two)
  60. return EmptyValueArray()
  61. })
  62. //Output: I am multi. See me bar, 7?
  63. vm.CallNamed("multi", ListTo("bar", 7)...)
  64. }
  65. func ExampleVm4() {
  66. vm := NewVM()
  67. vm.RegisterBuiltin("printf", func(vm *VM, args ...Value) []Value {
  68. var form string
  69. var rest = args[1:len(args)]
  70. resri := ListFromList(rest)
  71. err := From(args[0], &form)
  72. if err != nil {
  73. fmt.Printf("Error: %s", err.Error())
  74. } else {
  75. fmt.Printf(form, resri...)
  76. }
  77. return EmptyValueArray()
  78. })
  79. //Output: printf 7
  80. vm.CallNamed("printf", ListTo("printf %d", 7)...)
  81. }