OILS / doc / ref / chap-builtin-func.md View on Github | oilshell.org

402 lines, 236 significant
1---
2title: Builtin Functions (Oils Reference)
3all_docs_url: ..
4body_css_class: width40
5default_highlighter: oils-sh
6preserve_anchor_case: yes
7---
8
9<div class="doc-ref-header">
10
11[Oils Reference](index.html) &mdash;
12Chapter **Builtin Functions**
13
14</div>
15
16This chapter describes builtin functions (as opposed to [builtin
17commands](chap-builtin-cmd.html).)
18
19<span class="in-progress">(in progress)</span>
20
21<div id="dense-toc">
22</div>
23
24## Values
25
26### len()
27
28Returns the
29
30- number of entries in a `List`
31- number of pairs in a `Dict`
32- number of bytes in a `Str`
33 - TODO: `countRunes()` can return the number of UTF-8 encoded code points.
34
35### func/type()
36
37Given an arbitrary value, returns a string representing the value's runtime
38type.
39
40For example:
41
42 var d = {'foo': 'bar'}
43 var n = 1337
44
45 $ = type(d)
46 (Str) 'Dict'
47
48 $ = type(n)
49 (Str) 'Int'
50
51Similar names: [type][]
52
53[type]: chap-index.html#type
54
55
56## Conversions
57
58### bool()
59
60Returns the truth value of its argument. Similar to `bool()` in python, it
61returns `false` for:
62
63- `false`, `0`, `0.0`, `''`, `{}`, `[]`, and `null`.
64
65Returns `true` for all other values.
66
67### int()
68
69Given a float, returns the largest integer that is less than its argument (i.e. `floor()`).
70
71 $ = int(1.99)
72 (Int) 1
73
74Given a string, `Int()` will attempt to convert the string to a base-10
75integer. The base can be overriden by calling with a second argument.
76
77 $ = int('10')
78 (Int) 10
79
80 $ = int('10', 2)
81 (Int) 2
82
83 ysh$ = Int('foo')
84 # fails with an expression error
85
86### float()
87
88Given an integer, returns the corressponding flaoting point representation.
89
90 $ = float(1)
91 (Float) 1.0
92
93Given a string, `Float()` will attempt to convert the string to float.
94
95 $ = float('1.23')
96 (Float) 1.23
97
98 ysh$ = float('bar')
99 # fails with an expression error
100
101### str()
102
103Converts a `Float` or `Int` to a string.
104
105### list()
106
107Given a list, returns a shallow copy of the original.
108
109Given an iterable value (e.g. a range or dictionary), returns a list containing
110one element for each item in the original collection.
111
112 $ = list({'a': 1, 'b': 2})
113 (List) ['a', 'b']
114
115 $ = list(1:5)
116 (List) [1, 2, 3, 4, 5]
117
118### dict()
119
120Given a dictionary, returns a shallow copy of the original.
121
122### runes()
123
124TODO
125
126Given a string, decodes UTF-8 into a List of integer "runes" (aka code points).
127
128Each rune is in the range `U+0` to `U+110000`, and **excludes** the surrogate
129range.
130
131 runes(s, start=-1, end=-1)
132
133TODO: How do we signal errors?
134
135(`runes()` can be used to implement implemented Python's `ord()`.)
136
137### encodeRunes()
138
139TODO
140
141Given a List of integer "runes" (aka code points), return a string.
142
143(`encodeRunes()` can be used to implement implemented Python's `chr()`.)
144
145### bytes()
146
147TODO
148
149Given a string, return a List of integer byte values.
150
151Each byte is in the range 0 to 255.
152
153### encodeBytes()
154
155TODO
156
157Given a List of integer byte values, return a string.
158
159## Str
160
161### strcmp()
162
163TODO
164
165### split()
166
167TODO
168
169If no argument is passed, splits by whitespace
170
171<!-- respecting Unicode space? -->
172
173If a delimiter Str with a single byte is given, splits by that byte.
174
175Modes:
176
177- Python-like algorithm
178- Is awk any different?
179- Split by eggex
180
181### shSplit()
182
183Split a string into a List of strings, using the shell algorithm that respects
184`$IFS`.
185
186Prefer `split()` to `shSplit()`.
187
188
189## List
190
191### join()
192
193Given a List, stringify its items, and join them by a separator. The default
194separator is the empty string.
195
196 var x = ['a', 'b', 'c']
197
198 $ echo $[join(x)]
199 abc
200
201 $ echo $[join(x, ' ')] # optional separator
202 a b c
203
204
205It's also often called with the `=>` chaining operator:
206
207 var items = [1, 2, 3]
208
209 json write (items => join()) # => "123"
210 json write (items => join(' ')) # => "1 2 3"
211 json write (items => join(', ')) # => "1, 2, 3"
212
213## Float
214
215### floatsEqual()
216
217Check if two floating point numbers are equal.
218
219 = floatsEqual(42.0, 42.0)
220 (Bool) true
221
222It's usually better to make an approximate comparison:
223
224 = abs(float1 - float2) < 0.001
225 (Bool) false
226
227## Word
228
229### glob()
230
231See `glob-pat` topic for syntax.
232
233### maybe()
234
235## Serialize
236
237### toJson()
238
239Convert an object in memory to JSON text:
240
241 $ = toJson({name: "alice"})
242 (Str) '{"name":"alice"}'
243
244Add indentation by passing the `space` param:
245
246 $ = toJson([42], space=2)
247 (Str) "[\n 42\n]"
248
249Similar to `json write (x)`, except the default value of `space` is 0.
250
251See [err-json-encode][] for errors.
252
253[err-json-encode]: chap-errors.html#err-json-encode
254
255### fromJson()
256
257Convert JSON text to an object in memory:
258
259 = fromJson('{"name":"alice"}')
260 (Dict) {"name": "alice"}
261
262Similar to `json read <<< '{"name": "alice"}'`.
263
264See [err-json-decode][] for errors.
265
266[err-json-decode]: chap-errors.html#err-json-decode
267
268### toJson8()
269
270Like `toJson()`, but it also converts binary data (non-Unicode strings) to
271J8-style `b'foo \yff'` strings.
272
273In contrast, `toJson()` will do a lossy conversion with the Unicode replacement
274character.
275
276See [err-json8-encode][] for errors.
277
278[err-json8-encode]: chap-errors.html#err-json8-encode
279
280### fromJson8()
281
282Like `fromJson()`, but it also accepts binary data denoted by J8-style `b'foo
283\yff'` strings.
284
285See [err-json8-decode][] for errors.
286
287[err-json8-decode]: chap-errors.html#err-json8-decode
288
289## Pattern
290
291### `_group()`
292
293Like `Match => group()`, but accesses the global match created by `~`:
294
295 if ('foo42' ~ / d+ /) {
296 echo $[_group(0)] # => 42
297 }
298
299### `_start()`
300
301Like `Match => start()`, but accesses the global match created by `~`:
302
303 if ('foo42' ~ / d+ /) {
304 echo $[_start(0)] # => 3
305 }
306
307### `_end()`
308
309Like `Match => end()`, but accesses the global match created by `~`:
310
311 if ('foo42' ~ / d+ /) {
312 echo $[_end(0)] # => 5
313 }
314
315## Introspection
316
317### `shvarGet()`
318
319Given a variable name, return its value. It uses the "dynamic scope" rule,
320which looks up the stack for a variable.
321
322It's meant to be used with `shvar`:
323
324 proc proc1 {
325 shvar PATH=/tmp { # temporarily set PATH in this stack frame
326 my-proc
327 }
328
329 proc2
330 }
331
332 proc proc2 {
333 proc3
334 }
335
336 proc proc3 {
337 var path = shvarGet('PATH') # Look up the stack (dynamic scoping)
338 echo $path # => /tmp
339 }
340
341 proc1
342
343Note that `shvar` is usually for string variables, and is analogous to `shopt`
344for "booleans".
345
346If the variable isn't defined, `shvarGet()` returns `null`. So there's no way
347to distinguish an undefined variable from one that's `null`.
348
349### `getVar()`
350
351Given a variable name, return its value.
352
353 $ var x = 42
354 $ echo $[getVar('x')]
355 42
356
357The variable may be local or global. (Compare with `shvarGet()`.) the "dynamic
358scope" rule.)
359
360If the variable isn't defined, `getVar()` returns `null`. So there's no way to
361distinguish an undefined variable from one that's `null`.
362
363### `evalExpr()`
364
365Given a an expression quotation, evaluate it and return its value:
366
367 $ var expr = ^[1 + 2]
368
369 $ = evalExpr(expr)
370 3
371
372## Hay Config
373
374### parseHay()
375
376### evalHay()
377
378
379## Hashing
380
381### sha1dc()
382
383Git's algorithm.
384
385### sha256()
386
387
388<!--
389
390### Better Syntax
391
392These functions give better syntax to existing shell constructs.
393
394- `shQuote()` for `printf %q` and `${x@Q}`
395- `trimLeft()` for `${x#prefix}` and `${x##prefix}`
396- `trimRight()` for `${x%suffix}` and `${x%%suffix}`
397- `trimLeftGlob()` and `trimRightGlob()` for slow, legacy glob
398- `upper()` for `${x^^}`
399- `lower()` for `${x,,}`
400- `strftime()`: hidden in `printf`
401
402-->