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

474 lines, 283 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 overridden 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 corresponding floating 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### shSplit()
166
167Split a string into a List of strings, using the shell algorithm that respects
168`$IFS`.
169
170Prefer `split()` to `shSplit()`.
171
172
173## List
174
175### join()
176
177Given a List, stringify its items, and join them by a separator. The default
178separator is the empty string.
179
180 var x = ['a', 'b', 'c']
181
182 $ echo $[join(x)]
183 abc
184
185 $ echo $[join(x, ' ')] # optional separator
186 a b c
187
188
189It's also often called with the `=>` chaining operator:
190
191 var items = [1, 2, 3]
192
193 json write (items => join()) # => "123"
194 json write (items => join(' ')) # => "1 2 3"
195 json write (items => join(', ')) # => "1, 2, 3"
196
197## Dict
198
199### keys()
200
201Returns all existing keys from a dict as a list of strings.
202
203 var en2fr = {
204 hello: "bonjour",
205 friend: "ami",
206 cat: "chat"
207 }
208 = keys(en2fr)
209 # => (List 0x4689) ["hello","friend","cat"]
210
211### values()
212
213Similar to `keys()`, but returns the values of the dictionary.
214
215 var person = {
216 name: "Foo",
217 age: 25,
218 hobbies: :|walking reading|
219 }
220 = values(en2fr)
221 # => (List 0x4689) ["Foo",25,["walking","reading"]]
222
223### get()
224
225Return value for given key, falling back to the default value if the key
226doesn't exist.
227
228 var book = {
229 title: "Hitchhiker's Guide",
230 published: 1979,
231 }
232
233 var published = get(book, 'published', null)
234 = published
235 # => (Int) 1979
236
237 var author = get(book, 'author', "???")
238 = author
239 # => (Str) "???"
240
241If not specified, the default value is `null`:
242
243 var author = get(book, 'author')
244 = author
245 # => (Null) null
246
247## Float
248
249### floatsEqual()
250
251Check if two floating point numbers are equal.
252
253 = floatsEqual(42.0, 42.0)
254 (Bool) true
255
256It's usually better to make an approximate comparison:
257
258 = abs(float1 - float2) < 0.001
259 (Bool) false
260
261## Obj
262
263### first()
264
265Get the Dict that contains an object's properties.
266
267 ysh$ = first(obj)
268 (Dict) {x: 42}
269
270The Dict and Obj share the same storage. So if the Dict is modified, the
271object is too.
272
273If you want a copy, use `dict(obj)`.
274
275### rest()
276
277Get the "prototype" of an Obj, which is another Obj, or null:
278
279 ysh$ = rest(obj)
280 (Null) null
281
282## Word
283
284### glob()
285
286See `glob-pat` topic for syntax.
287
288### maybe()
289
290## Serialize
291
292### toJson()
293
294Convert an object in memory to JSON text:
295
296 $ = toJson({name: "alice"})
297 (Str) '{"name":"alice"}'
298
299Add indentation by passing the `space` param:
300
301 $ = toJson([42], space=2)
302 (Str) "[\n 42\n]"
303
304Similar to `json write (x)`, except the default value of `space` is 0.
305
306See [err-json-encode][] for errors.
307
308[err-json-encode]: chap-errors.html#err-json-encode
309
310### fromJson()
311
312Convert JSON text to an object in memory:
313
314 = fromJson('{"name":"alice"}')
315 (Dict) {"name": "alice"}
316
317Similar to `json read <<< '{"name": "alice"}'`.
318
319See [err-json-decode][] for errors.
320
321[err-json-decode]: chap-errors.html#err-json-decode
322
323### toJson8()
324
325Like `toJson()`, but it also converts binary data (non-Unicode strings) to
326J8-style `b'foo \yff'` strings.
327
328In contrast, `toJson()` will do a lossy conversion with the Unicode replacement
329character.
330
331See [err-json8-encode][] for errors.
332
333[err-json8-encode]: chap-errors.html#err-json8-encode
334
335### fromJson8()
336
337Like `fromJson()`, but it also accepts binary data denoted by J8-style `b'foo
338\yff'` strings.
339
340See [err-json8-decode][] for errors.
341
342[err-json8-decode]: chap-errors.html#err-json8-decode
343
344## Pattern
345
346### `_group()`
347
348Like `Match => group()`, but accesses the global match created by `~`:
349
350 if ('foo42' ~ / d+ /) {
351 echo $[_group(0)] # => 42
352 }
353
354### `_start()`
355
356Like `Match => start()`, but accesses the global match created by `~`:
357
358 if ('foo42' ~ / d+ /) {
359 echo $[_start(0)] # => 3
360 }
361
362### `_end()`
363
364Like `Match => end()`, but accesses the global match created by `~`:
365
366 if ('foo42' ~ / d+ /) {
367 echo $[_end(0)] # => 5
368 }
369
370## Introspect
371
372### `shvarGet()`
373
374Given a variable name, return its value. It uses the "dynamic scope" rule,
375which looks up the stack for a variable.
376
377It's meant to be used with `shvar`:
378
379 proc proc1 {
380 shvar PATH=/tmp { # temporarily set PATH in this stack frame
381 my-proc
382 }
383
384 proc2
385 }
386
387 proc proc2 {
388 proc3
389 }
390
391 proc proc3 {
392 var path = shvarGet('PATH') # Look up the stack (dynamic scoping)
393 echo $path # => /tmp
394 }
395
396 proc1
397
398Note that `shvar` is usually for string variables, and is analogous to `shopt`
399for "booleans".
400
401If the variable isn't defined, `shvarGet()` returns `null`. So there's no way
402to distinguish an undefined variable from one that's `null`.
403
404### `getVar()`
405
406Given a variable name, return its value.
407
408 $ var x = 42
409 $ echo $[getVar('x')]
410 42
411
412The variable may be local or global. (Compare with `shvarGet()`.) the "dynamic
413scope" rule.)
414
415If the variable isn't defined, `getVar()` returns `null`. So there's no way to
416distinguish an undefined variable from one that's `null`.
417
418### `setVar()`
419
420Bind a name to a value, in the local scope. Returns nothing.
421
422 call setVar('myname', 42)
423
424This is like
425
426 setvar myname = 42
427
428except the name can is a string, which can be constructed at runtime.
429
430### `parseCommand()`
431
432Given a code string, parse it as a command (with the current parse options).
433
434Returns a `value.Command` instance, or raises an error.
435
436### `parseExpr()`
437
438TODO:
439
440Given a code string, parse it as an expression.
441
442Returns a `value.Expr` instance, or raises an error.
443
444## Hay Config
445
446### parseHay()
447
448### evalHay()
449
450
451## Hashing
452
453### sha1dc()
454
455Git's algorithm.
456
457### sha256()
458
459
460<!--
461
462### Better Syntax
463
464These functions give better syntax to existing shell constructs.
465
466- `shQuote()` for `printf %q` and `${x@Q}`
467- `trimLeft()` for `${x#prefix}` and `${x##prefix}`
468- `trimRight()` for `${x%suffix}` and `${x%%suffix}`
469- `trimLeftGlob()` and `trimRightGlob()` for slow, legacy glob
470- `upper()` for `${x^^}`
471- `lower()` for `${x,,}`
472- `strftime()`: hidden in `printf`
473
474-->