-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
example_switch_statement_test.go
114 lines (96 loc) · 2.01 KB
/
example_switch_statement_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package evalfilter
import (
"fmt"
)
// SwitchFunction is just a temporary structure.
//
// Without this the following error occurs when linting this code:
//
//
// $ go vet ./...
// # github.com/skx/evalfilter/v2
// ./example_switch_statement_test.go:16:1: ExampleSwitchFunction refers to unknown identifier: SwitchFunction
//
type SwitchFunction struct {
foo string
}
// ExampleSwitchFunction demonstrates how the case/switch statement
// in our scripting language works.
//
func ExampleSwitchFunction() {
// Ignore this - just to resolve the linter warning
x := SwitchFunction{}
x.foo = "bar"
//
// We'll run this script, which defines a function and uses
// it.
//
//
script := `
function test( name ) {
switch( name ) {
case "Ste" + "ve" {
printf("\tI know you - expression-match!\n" );
}
case "Steven" {
printf("\tI know you - literal-match!\n" );
}
case /steve kemp/i {
printf("\tI know you - regexp-match!\n");
}
default {
printf("\tDefault: I don't know who you are\n" );
}
}
}
printf("Running: Steve\n");
test( "Steve" );
printf("Running: Steven\n");
test( "Steven" );
printf("Running: steve kemp\n");
test( "steve kemp" );
printf("Running: bob\n");
test( "Bob" );
printf("Testing is all over\n")
`
//
// Create the evaluator
//
eval := New(script)
//
// Prepare the evaluator.
//
err := eval.Prepare()
if err != nil {
fmt.Printf("Failed to compile the code:%s\n", err.Error())
return
}
//
// Call the filter - since we're testing
// the user-defined function we don't
// care about passing a real-object to it.
//
res, err := eval.Run(nil)
//
// Error-detection is important (!)
//
if err != nil {
panic(err)
}
//
// Show the output of the call.
//
if res {
fmt.Printf("%v\n", res)
}
// Output:
// Running: Steve
// I know you - expression-match!
//Running: Steven
// I know you - literal-match!
//Running: steve kemp
// I know you - regexp-match!
//Running: bob
// Default: I don't know who you are
//Testing is all over
}