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

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