1 | ---
|
2 | title: Builtin Functions (Oils Reference)
|
3 | all_docs_url: ..
|
4 | body_css_class: width40
|
5 | default_highlighter: oils-sh
|
6 | preserve_anchor_case: yes
|
7 | ---
|
8 |
|
9 | <div class="doc-ref-header">
|
10 |
|
11 | [Oils Reference](index.html) —
|
12 | Chapter **Builtin Functions**
|
13 |
|
14 | </div>
|
15 |
|
16 | This chapter describes builtin functions (as opposed to [builtin
|
17 | commands](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 |
|
28 | Returns 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 |
|
37 | Given an arbitrary value, returns a string representing the value's runtime
|
38 | type.
|
39 |
|
40 | For 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 |
|
51 | Similar names: [type][]
|
52 |
|
53 | [type]: chap-index.html#type
|
54 |
|
55 |
|
56 | ## Conversions
|
57 |
|
58 | ### bool()
|
59 |
|
60 | Returns the truth value of its argument. Similar to `bool()` in python, it
|
61 | returns `false` for:
|
62 |
|
63 | - `false`, `0`, `0.0`, `''`, `{}`, `[]`, and `null`.
|
64 |
|
65 | Returns `true` for all other values.
|
66 |
|
67 | ### int()
|
68 |
|
69 | Given a float, returns the largest integer that is less than its argument (i.e. `floor()`).
|
70 |
|
71 | $ = int(1.99)
|
72 | (Int) 1
|
73 |
|
74 | Given a string, `Int()` will attempt to convert the string to a base-10
|
75 | integer. 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 |
|
88 | Given an integer, returns the corressponding flaoting point representation.
|
89 |
|
90 | $ = float(1)
|
91 | (Float) 1.0
|
92 |
|
93 | Given 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 |
|
103 | Converts a `Float` or `Int` to a string.
|
104 |
|
105 | ### list()
|
106 |
|
107 | Given a list, returns a shallow copy of the original.
|
108 |
|
109 | Given an iterable value (e.g. a range or dictionary), returns a list containing
|
110 | one 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 |
|
120 | Given a dictionary, returns a shallow copy of the original.
|
121 |
|
122 | ### runes()
|
123 |
|
124 | TODO
|
125 |
|
126 | Given a string, decodes UTF-8 into a List of integer "runes" (aka code points).
|
127 |
|
128 | Each rune is in the range `U+0` to `U+110000`, and **excludes** the surrogate
|
129 | range.
|
130 |
|
131 | runes(s, start=-1, end=-1)
|
132 |
|
133 | TODO: How do we signal errors?
|
134 |
|
135 | (`runes()` can be used to implement implemented Python's `ord()`.)
|
136 |
|
137 | ### encodeRunes()
|
138 |
|
139 | TODO
|
140 |
|
141 | Given 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 |
|
147 | TODO
|
148 |
|
149 | Given a string, return a List of integer byte values.
|
150 |
|
151 | Each byte is in the range 0 to 255.
|
152 |
|
153 | ### encodeBytes()
|
154 |
|
155 | TODO
|
156 |
|
157 | Given a List of integer byte values, return a string.
|
158 |
|
159 | ## Str
|
160 |
|
161 | ### strcmp()
|
162 |
|
163 | TODO
|
164 |
|
165 | ### split()
|
166 |
|
167 | TODO
|
168 |
|
169 | If no argument is passed, splits by whitespace
|
170 |
|
171 | <!-- respecting Unicode space? -->
|
172 |
|
173 | If a delimiter Str with a single byte is given, splits by that byte.
|
174 |
|
175 | Modes:
|
176 |
|
177 | - Python-like algorithm
|
178 | - Is awk any different?
|
179 | - Split by eggex
|
180 |
|
181 | ### shSplit()
|
182 |
|
183 | Split a string into a List of strings, using the shell algorithm that respects
|
184 | `$IFS`.
|
185 |
|
186 | Prefer `split()` to `shSplit()`.
|
187 |
|
188 |
|
189 | ## List
|
190 |
|
191 | ### join()
|
192 |
|
193 | Given a List, stringify its items, and join them by a separator. The default
|
194 | separator 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 |
|
205 | It'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 | ## Dict
|
214 |
|
215 | ### keys()
|
216 |
|
217 | Returns all existing keys from a dict as a list of strings.
|
218 |
|
219 | var en2fr = {
|
220 | hello: "bonjour",
|
221 | friend: "ami",
|
222 | cat: "chat"
|
223 | }
|
224 | = keys(en2fr)
|
225 | # => (List 0x4689) ["hello","friend","cat"]
|
226 |
|
227 | ### values()
|
228 |
|
229 | Similar to `keys()`, but returns the values of the dictionary.
|
230 |
|
231 | var person = {
|
232 | name: "Foo",
|
233 | age: 25,
|
234 | hobbies: :|walking reading|
|
235 | }
|
236 | = values(en2fr)
|
237 | # => (List 0x4689) ["Foo",25,["walking","reading"]]
|
238 |
|
239 | ### get()
|
240 |
|
241 | Return value for given key, falling back to the default value if the key
|
242 | doesn't exist. Default is required.
|
243 |
|
244 | var book = {
|
245 | title: "Hitchhiker's Guide",
|
246 | published: 1979,
|
247 | }
|
248 | var published = get(book, "published", null)
|
249 | = published
|
250 | # => (Int 1979)
|
251 |
|
252 | var author = get(book, "author", "???")
|
253 | = author
|
254 | # => (Str "???")
|
255 |
|
256 | ## Float
|
257 |
|
258 | ### floatsEqual()
|
259 |
|
260 | Check if two floating point numbers are equal.
|
261 |
|
262 | = floatsEqual(42.0, 42.0)
|
263 | (Bool) true
|
264 |
|
265 | It's usually better to make an approximate comparison:
|
266 |
|
267 | = abs(float1 - float2) < 0.001
|
268 | (Bool) false
|
269 |
|
270 | ## Obj
|
271 |
|
272 | ### Object
|
273 |
|
274 | Construct an object with a prototype and properties:
|
275 |
|
276 | var obj = Object(null, {x: 42}}
|
277 |
|
278 | An object with methods:
|
279 |
|
280 | func mymethod(self) { return (self.x) }
|
281 | var cls = Object(null, {mymethod: mymethod})
|
282 | var obj = Object(cls, {x: 42}}
|
283 |
|
284 | ### prototype()
|
285 |
|
286 | Get the prototype of an object. May be null:
|
287 |
|
288 | ysh$ = prototype(obj)
|
289 | (Null) null
|
290 |
|
291 | ### propView()
|
292 |
|
293 | Get a Dict that aliases an object's properties.
|
294 |
|
295 | ysh andy@hoover:~/git/oilshell/oil$ = propView(obj)
|
296 | (Dict) {x: 42}
|
297 |
|
298 | This means that if the Dict is modified, then the object is too.
|
299 |
|
300 | If you want to copy it, use `dict(obj)`.
|
301 |
|
302 | ## Word
|
303 |
|
304 | ### glob()
|
305 |
|
306 | See `glob-pat` topic for syntax.
|
307 |
|
308 | ### maybe()
|
309 |
|
310 | ## Serialize
|
311 |
|
312 | ### toJson()
|
313 |
|
314 | Convert an object in memory to JSON text:
|
315 |
|
316 | $ = toJson({name: "alice"})
|
317 | (Str) '{"name":"alice"}'
|
318 |
|
319 | Add indentation by passing the `space` param:
|
320 |
|
321 | $ = toJson([42], space=2)
|
322 | (Str) "[\n 42\n]"
|
323 |
|
324 | Similar to `json write (x)`, except the default value of `space` is 0.
|
325 |
|
326 | See [err-json-encode][] for errors.
|
327 |
|
328 | [err-json-encode]: chap-errors.html#err-json-encode
|
329 |
|
330 | ### fromJson()
|
331 |
|
332 | Convert JSON text to an object in memory:
|
333 |
|
334 | = fromJson('{"name":"alice"}')
|
335 | (Dict) {"name": "alice"}
|
336 |
|
337 | Similar to `json read <<< '{"name": "alice"}'`.
|
338 |
|
339 | See [err-json-decode][] for errors.
|
340 |
|
341 | [err-json-decode]: chap-errors.html#err-json-decode
|
342 |
|
343 | ### toJson8()
|
344 |
|
345 | Like `toJson()`, but it also converts binary data (non-Unicode strings) to
|
346 | J8-style `b'foo \yff'` strings.
|
347 |
|
348 | In contrast, `toJson()` will do a lossy conversion with the Unicode replacement
|
349 | character.
|
350 |
|
351 | See [err-json8-encode][] for errors.
|
352 |
|
353 | [err-json8-encode]: chap-errors.html#err-json8-encode
|
354 |
|
355 | ### fromJson8()
|
356 |
|
357 | Like `fromJson()`, but it also accepts binary data denoted by J8-style `b'foo
|
358 | \yff'` strings.
|
359 |
|
360 | See [err-json8-decode][] for errors.
|
361 |
|
362 | [err-json8-decode]: chap-errors.html#err-json8-decode
|
363 |
|
364 | ## Pattern
|
365 |
|
366 | ### `_group()`
|
367 |
|
368 | Like `Match => group()`, but accesses the global match created by `~`:
|
369 |
|
370 | if ('foo42' ~ / d+ /) {
|
371 | echo $[_group(0)] # => 42
|
372 | }
|
373 |
|
374 | ### `_start()`
|
375 |
|
376 | Like `Match => start()`, but accesses the global match created by `~`:
|
377 |
|
378 | if ('foo42' ~ / d+ /) {
|
379 | echo $[_start(0)] # => 3
|
380 | }
|
381 |
|
382 | ### `_end()`
|
383 |
|
384 | Like `Match => end()`, but accesses the global match created by `~`:
|
385 |
|
386 | if ('foo42' ~ / d+ /) {
|
387 | echo $[_end(0)] # => 5
|
388 | }
|
389 |
|
390 | ## Introspection
|
391 |
|
392 | ### `id()`
|
393 |
|
394 | Returns an integer ID for mutable values like List, Dict, and Obj.
|
395 |
|
396 | You can use it to test if two names refer to the same instance.
|
397 |
|
398 | `id()` is undefined on immutable values like Bool, Int, Float, Str, etc.
|
399 |
|
400 | ### `shvarGet()`
|
401 |
|
402 | Given a variable name, return its value. It uses the "dynamic scope" rule,
|
403 | which looks up the stack for a variable.
|
404 |
|
405 | It's meant to be used with `shvar`:
|
406 |
|
407 | proc proc1 {
|
408 | shvar PATH=/tmp { # temporarily set PATH in this stack frame
|
409 | my-proc
|
410 | }
|
411 |
|
412 | proc2
|
413 | }
|
414 |
|
415 | proc proc2 {
|
416 | proc3
|
417 | }
|
418 |
|
419 | proc proc3 {
|
420 | var path = shvarGet('PATH') # Look up the stack (dynamic scoping)
|
421 | echo $path # => /tmp
|
422 | }
|
423 |
|
424 | proc1
|
425 |
|
426 | Note that `shvar` is usually for string variables, and is analogous to `shopt`
|
427 | for "booleans".
|
428 |
|
429 | If the variable isn't defined, `shvarGet()` returns `null`. So there's no way
|
430 | to distinguish an undefined variable from one that's `null`.
|
431 |
|
432 | ### `getVar()`
|
433 |
|
434 | Given a variable name, return its value.
|
435 |
|
436 | $ var x = 42
|
437 | $ echo $[getVar('x')]
|
438 | 42
|
439 |
|
440 | The variable may be local or global. (Compare with `shvarGet()`.) the "dynamic
|
441 | scope" rule.)
|
442 |
|
443 | If the variable isn't defined, `getVar()` returns `null`. So there's no way to
|
444 | distinguish an undefined variable from one that's `null`.
|
445 |
|
446 | ### `setVar()`
|
447 |
|
448 | Bind a name to a value, in the local scope. Returns nothing.
|
449 |
|
450 | call setVar('myname', 42)
|
451 |
|
452 | This is like
|
453 |
|
454 | setvar myname = 42
|
455 |
|
456 | except the name can is a string, which can be constructed at runtime.
|
457 |
|
458 | ### `parseCommand()`
|
459 |
|
460 | Given a code string, parse it as a command (with the current parse options).
|
461 |
|
462 | Returns a `value.Command` instance, or raises an error.
|
463 |
|
464 | ### `parseExpr()`
|
465 |
|
466 | TODO:
|
467 |
|
468 | Given a code string, parse it as an expression.
|
469 |
|
470 | Returns a `value.Expr` instance, or raises an error.
|
471 |
|
472 | ### `evalExpr()`
|
473 |
|
474 | Given a an expression quotation, evaluate it and return its value:
|
475 |
|
476 | $ var expr = ^[1 + 2]
|
477 |
|
478 | $ = evalExpr(expr)
|
479 | 3
|
480 |
|
481 | <!-- TODO: io.evalExpr() -->
|
482 |
|
483 | ## Hay Config
|
484 |
|
485 | ### parseHay()
|
486 |
|
487 | ### evalHay()
|
488 |
|
489 |
|
490 | ## Hashing
|
491 |
|
492 | ### sha1dc()
|
493 |
|
494 | Git's algorithm.
|
495 |
|
496 | ### sha256()
|
497 |
|
498 |
|
499 | <!--
|
500 |
|
501 | ### Better Syntax
|
502 |
|
503 | These functions give better syntax to existing shell constructs.
|
504 |
|
505 | - `shQuote()` for `printf %q` and `${x@Q}`
|
506 | - `trimLeft()` for `${x#prefix}` and `${x##prefix}`
|
507 | - `trimRight()` for `${x%suffix}` and `${x%%suffix}`
|
508 | - `trimLeftGlob()` and `trimRightGlob()` for slow, legacy glob
|
509 | - `upper()` for `${x^^}`
|
510 | - `lower()` for `${x,,}`
|
511 | - `strftime()`: hidden in `printf`
|
512 |
|
513 | -->
|