OILS / spec / ysh-convert.test.sh View on Github | oilshell.org

190 lines, 116 significant
1#### bool() conversion
2echo "$[bool(1234)]"
3echo "$[bool(0)]"
4echo "$[bool('foo')]"
5echo "$[bool(true)]"
6echo "$[bool(1.234)]"
7echo "$[bool([])]"
8echo "$[bool({})]"
9echo "$[bool(null)]"
10echo "$[bool(len)]"
11echo "$[bool('foo'=>startsWith)]"
12echo "$[bool(1..3)]"
13## STDOUT:
14true
15false
16true
17true
18true
19false
20false
21false
22true
23true
24true
25## END
26
27#### bool() more
28var a = bool( :|| )
29var b = bool( :|foo| )
30write $a $b
31## STDOUT:
32false
33true
34## END
35
36
37#### int() conversion
38echo "$[int(1234)]"
39echo "$[int('1234')]"
40echo "$[int(1.234)]"
41## STDOUT:
421234
431234
441
45## END
46
47#### int() more
48pp test_ (int("3"))
49pp test_ (int("-35"))
50pp test_ (int('5_6'))
51
52shopt -s ysh:upgrade
53
54try {
55 var c = int("bad")
56}
57echo code=$[_error.code]
58
59## STDOUT:
60(Int) 3
61(Int) -35
62(Int) 56
63code=3
64## END
65
66#### float() conversion
67echo "$[float(1234)]"
68echo "$[float('1.234')]"
69echo "$[float(2.345)]"
70## STDOUT:
711234.0
721.234
732.345
74## END
75
76#### float() overflow / underflow
77
78var a = float("1.2")
79var b = float("3.4")
80
81var c = float("42.1e500")
82var d = float("-42.1e500")
83
84write $a $b $c $d
85## STDOUT:
861.2
873.4
88inf
89-inf
90## END
91
92#### str() conversion
93echo $[str(1234)]
94echo $[str(1.234)]
95echo $[str('foo')]
96
97echo
98
99# Added with Stringify()
100
101echo $[str(true)]
102echo $[str(null)]
103echo $[str(/d+/)]
104
105echo $[str([1,2,3])]
106
107## status: 3
108## STDOUT:
1091234
1101.234
111foo
112
113true
114null
115[[:digit:]]+
116## END
117
118#### dict() converts from BashAssoc to Dict
119declare -A foo
120foo=([a]=1 [b]=2 [c]=3)
121
122json write (type(foo))
123json write (dict(foo))
124## STDOUT:
125"BashAssoc"
126{
127 "a": "1",
128 "b": "2",
129 "c": "3"
130}
131## END
132
133#### dict() does shallow copy
134var d = {'a': 1}
135var d2 = d
136setvar d2['b'] = 2
137echo $['b' in d] # d2 should be an alias for d
138
139var d3 = dict(d)
140setvar d3['c'] = 3
141
142# d3 should NOT be an alias
143echo $['c' in d]
144echo $['c' in d3]
145## STDOUT:
146true
147false
148true
149## END
150
151#### list() does shallow copy
152var l = [1]
153var l2 = l
154call l2->append(2)
155echo $[len(l)] # d2 should be an alias for d
156
157var l3 = list(l)
158call l3->append(3)
159
160# l3 should NOT be an alias
161echo $[len(l)]
162echo $[len(l3)]
163## STDOUT:
1642
1652
1663
167## END
168
169#### list() from Dict
170shopt -s ysh:upgrade
171
172var a = list({'a': 1, 'foo': 'bar'})
173write @a
174## STDOUT:
175a
176foo
177## END
178
179
180#### list() from range
181shopt -s ysh:upgrade
182
183var mylist = list(0..3)
184write @mylist
185## STDOUT:
1860
1871
1882
189## END
190