Int type

Integer type. On 64 bit platforms it's a 61 bit signed integer

Direct parent types

Eachable1
Eachable which each() calls the callback with one argument
Direct subtypes: 16
Num
A number
Direct subtypes: 2

Constructors

Int(r:Real)
Convert Real (floating) number to Int. Floating part is truncated.

Returns

Int
Int(s:Str, base:Int)
Convert Str to Int.

Example

Int("100", 2)  # 8
Int("80", 16)  # 128
Int() Source: stdlib.ngs:183
Get zero

Returns

0
Int(i:Int) Source: stdlib.ngs:3177
Convert Int to Int, a no-op

Returns

i
Int(s:Str) Source: stdlib.ngs:3183
Convert base-10 string to Int. Throws InvalidArgument if the number in s is not well-formatted.

Returns

Int

Example

Int(" 100 ")  # 100
Int(b:Bool) Source: stdlib.ngs:3193
Convert Bool to int.

Returns

Int

Example

true.Int()   # 1
false.Int()  # 0
Int(t:Time) Source: stdlib.ngs:5869
Undocumented

Methods

%(a:Int, b:Int)
Modulus

Returns

Int

Example

10 % 3  # 1
*(a:Int, b:Int)
Multiplication
*(arr:Arr, n:Int) Source: stdlib.ngs:2071
Repeat all elements in arr n times

Parameters

arrElements to repeat
nNumber of times to repeat the elements

Returns

Arr

Example

[10,20] * 2  # [10,20,10,20]
*(s:Str, n:Int) Source: stdlib.ngs:3348
Repeat string n times

Example

"abc" * 3  # "abcabcabc"
*(cb:Fun, n:Int) Source: stdlib.ngs:5594
Call cb n times without any parameters and accumulate the results.

Example

a = Box * 2; a[0] is Box and a[1] is Box and a[0] !== a[1]  # true
+(a:Int, b:Int)
Addition
-(a:Int, b:Int)
Subtraction
/(a:Int, b:Int)
Division
<(a:Int, b:Int)
Less-than comparison
<=(a:Int, b:Int)
Less-than-or-equal comparison
==(a:Int, b:Int)
Equality comparison
>(a:Int, b:Int)
Greater-than comparison
>=(a:Int, b:Int)
Greater-than-or-equal comparison
[](arr:Arr, idx:Int)
Get element at the given index or throw IndexNotFound if the index is out of range (element at the given index does not exist).

Returns

Any
[](al:ArrLike, idx:Int) Source: stdlib.ngs:657
Set element in the underlying array.
[](arr:Arr, idx:Int) Source: stdlib.ngs:1902
Get array element by index from the end (negative indexes handler). Throws IndexNotFound if abs(idx) > len(arr).

Parameters

idxNegative index

Example

[10,20,30][-1]  # 30
[](s:Str, i:Int) Source: stdlib.ngs:3289
Get given character (currently byte) of the string

Parameters

sOriginal string
iIndex of the character to return

Example

"abc"[0]  # "a"
[](s:Str, i:Int) Source: stdlib.ngs:3299
Get given character (currently byte) of the string (negative indexes handler). Throws IndexNotFound if abs(i) > len(s).

Parameters

sOriginal string.
iNegative index of the character to return

Example

"abc"[-1]  # "c"
[](my:MatchY, idx:Int) Source: stdlib.ngs:5381
Convenience method to access matches in MatchY

Example

("abc" ~ /a(.)c/)[1]  # "b"
[]=(arr:Arr, idx:Int, v:Any)
Set element at the given index or throw IndexNotFound if the index is out of range.

Returns

v
[]=(al:ArrLike, idx:Int, x:Any) Source: stdlib.ngs:660
Get element from the underlying array.
abs(i:Int) Source: stdlib.ngs:3145
Absolute value of a number

Example

abs(5)   # 5
abs(-5)  # 5
access(f:File, mode:Int=0) Source: stdlib.ngs:6090
Check whether current process has the specified access to the file. Wrapper around ACCESS(2). Throws CException.

Parameters

modeOne of the file ACCESS::* modes, defaults to ACCESS::F_OK (test file existance only).

Returns

Bool

Example

access(File("mydata"), ACCESS::R_OK).not() throws Error("No access to data file").set("file", "mydata")
Arg(x:Int) Source: stdlib.ngs:4625
Convert to string, appropriate for using as argument to external process.

Automatically called by NGS for syntax

$(mycommand $num) # num is Int
assert_exit_code(cp:CommandsPipeline, expected:Int, title:Str=null) Source: autoload/test.ngs:165
Assert process exits with the specified exit code. Throws TestFail.

Returns

cp

Example

p = $(true); assert_exit_code(p, 0)   # OK
p = $(false); assert_exit_code(p, 1)  # OK
p = $(false); assert_exit_code(p, 0)  # Throws TestFail
band(a:Int, b:Int)
Bitwise and

Returns

Int

Example

7.band(5)  # 5
bor(a:Int, b:Int)
Bitwise or

Returns

Int

Example

1.bor(8)  # 9
bxor(a:Int, b:Int)
Bitwise xor

Returns

Int

Example

15.bxor(1)  # 14
c_access(pathname:Str, mode:Int)
Call ACCESS(2)
c_close(fd:Int)
Close a file. Uses CLOSE(2).

Returns

Int - zero on success or -1
c_dlopen(filename:Str, flags:Int)
Unfinished feature. Don't use!
c_dup2(oldfd:Int, newfd:Int)
Duplicate a file descriptor. Uses DUP2(2).

Returns

Int - file descriptor or -1
c_exit(status:Int)
Call EXIT(3). Don't use directly unless you must. Use FatalError exception.
c_fstat(fd:Int)
Call FSTAT(2)
c_gmtime(timep:Int)
Call GMTIME_R(3)

Example

ngs -pl 'c_gmtime(0).Hash().Strs()'
tm_sec=0
tm_min=0
tm_hour=0
tm_mday=1
tm_mon=0
tm_year=70
tm_wday=4
tm_yday=0
tm_isdst=0
c_isatty(fd:Int)
Check if file descriptor refers to a TTY device. Uses ISATTY(3).

Returns

Int: 1 or 0
c_kill(pid:Int, sig:Int)
Call KILL(2). Global variable SIGNALS contains mapping between signals' names and values.
c_localtime(timep:Int)
Call LOCALTIME(3)

Example

ngs -pl 'c_gmtime(0).Hash().keys()'
tm_sec
tm_min
tm_hour
tm_mday
tm_mon
tm_year
tm_wday
tm_yday
tm_isdst
c_lseek(fd:Int, offset:Int, whence:Str)
Call LSEEK(2).

Parameters

whenceOne of: set, cur, end

Returns

Int: new offset or -1
c_pcre_compile(regexp:Str, flags:Int)
Throws RegExpCompileFail on errors.

Returns

RegExp
c_pcre_exec(regexp:RegExp, subject:Str, offset:Int, options:Int)
Search string for regular expression. Uses PCRE_EXEC(3). Do not use this function directly!

Returns

Int or Arr of Int
c_poll(fds_evs:Arr, timeout:Int)
Undocumented
c_pthread_mutexattr_settype(mutex:c_pthread_mutexattr_t, type:Int)
Call PTHREAD_MUTEXATTR_SETTYPE(3)
c_read(fd:Int, count:Int)
Read from a file. Uses READ(2).

Parameters

countMaximal number of bytes to read.

Returns

Arr of two elements: Int - number of bytes read or -1, Str - the read bytes
c_strerror(errnum:Int)
Call STRERROR(2)
c_waitpid(pid:Int)
Call WAITPID(2)
C_WEXITSTATUS(status:Int)
Use WEXITSTATUS macro.
c_write(fd:Int, s:Str)
Write to a file. Uses WRITE(2).

Returns

Int - number of bytes written or -1
C_WTERMSIG(status:Int)
Use WTERMSIG macro.
calculate_num_cols_to_show(t:Table, max_colums_widths:Arr, available_cols:Int) Source: autoload/Table.ngs:110
Internal method. Please do not use.
chr(code:Int)
Get character (byte) by it's ordinal value.

Returns

Str of length 1 (byte).

Example

chr(65)  # "A" on my machine
close(fd:Int) Source: stdlib.ngs:4400
Close a file. Uses CLOSE(2). Throws FileIOFail if an underlying error occurs.
code(n:Int) Source: stdlib.ngs:3200
Convert an Int to NGS code that would produce the integer when executed. Not fully functional yet.

Returns

Str
collector(n:Int, body:Fun) Source: stdlib.ngs:1343
Defines collector { ... collect(...) ... } behaviour for integers (summarizes collected items).

Parameters

nInitial number
bodyThe body after collector keyword and initial value, wrapped in a function "collector/100 THIS_CODE"

Returns

Constructed array

Example

collector/0 { (1...10).each(collect) }  # 55
column(t:Table, n:Int) Source: autoload/Table.ngs:90
Get values in the given table column.

Returns

Arr
create(rd:ResDef, n:Int, **props:Hash) Source: autoload/Res.ngs:174
Create n resources with given props. Typically called by converge().

Returns

rd
die(s:Str, exit_code:Int=1) Source: stdlib.ngs:3877
Write message in s to standard error and exit, printing backtrace
digest(a:Arr, chunk_size:Int, marker:Str='(...)') Source: stdlib.ngs:5619
Convert an array to a possibly shorter version, for displaying to human.

Parameters

chunk_sizenumber of elements to retain at the beginning and at the end.
markerhow to mark the cut elements in the middle.

Returns

Arr

Example

my_array = Arr(1...100)
digest(my_array, 2).each(echo)
# 1
# 2
# (...)
# 99
# 100
drop(i:Iter, n:Int) Source: autoload/Iter.ngs:77
Fetch and drop next n values from iterator i.

Example

i = Iter([10,20,30])
drop(i, 1)
echo(i.next())
# Output: 20
dup2(oldfd:Int, newfd:Int) Source: stdlib.ngs:4137
Duplicate a file descriptor. Uses DUP2(2). Handles EINTR.
dup2_reading_end(p:Pipe, newfd:Int) Source: stdlib.ngs:4298
DUP2(2) reading file descriptor
dup2_writing_end(p:Pipe, newfd:Int) Source: stdlib.ngs:4295
DUP2(2) writing file descriptor
each(arr:Arr, n:Int, cb:Fun) Source: stdlib.ngs:1669
Process each N elements of an Array at a time. Throws InvalidArgument if number of items in arr is not divisible by n. cb is called as cb(eltI, ..., eltJ) where I is multiple of n and J is I+n-1

Parameters

arrItems to iterate in chunks of n
nNumber of items in chunk
cbFunction to be called with values from arr

Returns

arr

Example

[1,2,3,4].each(2, F(a, b) echo("$a - $b"))  # Outputs: "1 - 2" and on the next line "3 - 4"
each(n:Int, cb:Fun) Source: stdlib.ngs:3157
Iterate from zero up to but not including n

Parameters

cbFunction to call with current number

Returns

n

Example

10.each(echo)  # Outputs numbers from 0 to 9 inclusive, one on each line
each_chunk(e:Eachable1, n:Int, cb:Fun)experimental Source: stdlib.ngs:2199
Call cb with array of maximum length of n, repeatedely for all items of e. TODO: better doc
echo(fd:Int, s:Str)
Print given string and a newline to a file referenced by descriptor.

Returns

Unspecified

Example

echo(2, "blah")  # Output on stderr: blah
exit(s:Str, exit_code:Int=1) Source: stdlib.ngs:3880
Write message in s to standard error and exit
exit(exit_code:Int=1) Source: stdlib.ngs:3883
Exit with given exit_code
ExitCode(n:Int) Source: bootstrap.ngs:48
Undocumented

Returns

n
expect(rd:ResDef, e:Int) Source: autoload/Res.ngs:61
Throw an exception unless there is exactly e resources were found. Useful to express assumptions before operating.

Returns

rd

Example

slave_build_server = AWS::Instance(Tags={'env': 'aux', 'role': 'build-slave'}).expect(1)
subnets = AWS::Subnet(my_vpc_anchor).expect(2)
get(arr:Arr, idx:Int, dflt:Any)
Get element at the given index or return dflt if the index is out of range (element at the given index does not exist)

Returns

Any

Example

[1,2,3].get(0, 10)  # 1
[1,2,3].get(5, 10)  # 10
get(al:ArrLike, idx:Int, dflt:Any) Source: stdlib.ngs:663
Get element at the given index or return dflt if the index is out of range (element at the given index does not exist). See get(Arr).
gmtime(t:Int) Source: stdlib.ngs:5830
Low-level function. Do not use directly. Use Time type.
in(n:Int, r:NumRange) Source: stdlib.ngs:1227
Check whether the number is in range 10 in 10..20 # true 1 in 10..20 # false
index(arr:Arr, predicate:Any, start:Int=0, dflt:Any=[]) Source: stdlib.ngs:1781
Find index of first value that satisfies the predicate. TODO: Make it work on anything with each() method. In future, will throw exception if element is not found and default is not provided. Now returns null for backwards compatibilty in this case.

Parameters

arrItems to look at
predicateTest function
startIndex to start search at
dfltdefault value to return when element is not found

Returns

Int or dflt. Temporary also null, for backwards compatibilty.

Example

[1,2,11,3,4].index(X>10)  # 2
init(e:CException, errno:Int, message:Str) Source: stdlib.ngs:1004
CException constructor. In addition to storing message field, adds errno and errno_name fields.
init(e:LockFail, op:Str, code:Int, msg:Str) Source: stdlib.ngs:1029
Initialize LockFail exception.
init(ee:ExitException, message:Str, exit_code:Int=1) Source: stdlib.ngs:3750
Initializes ExitException.
init(ee:ExitException, exit_code:Int=1) Source: stdlib.ngs:3754
Undocumented
init(f:File, fd:Int) Source: stdlib.ngs:4313
Create File object from the given file descriptor.
init(t:Time, epoch:Int) Source: stdlib.ngs:5855
Initialize Time object with the given epoch time.
inspect(i:Int) Source: stdlib.ngs:5664
Inspect Int

Returns

Arr with one element, Str
is_global_variable_defined(idx:Int)
Do not use directly! Check whether global variable is defined by index.
isatty(fd:Int) Source: stdlib.ngs:4205
Check whether given fd represents a TTY. Uses ISATTY(3). Throws TtyCheckFail.

Returns

Bool
Iter(n:Int) Source: autoload/Iter.ngs:244
Create Iter from Int
kill(pid:Int, sig:Int=15) Source: stdlib.ngs:4964
Send signal to a process. Uses KILL(2). Throws KillFail on error.

Parameters

sigSignal to send. Defaults to SIGNALS.TERM

Returns

unspecified at this time, do not count on it
kill(p:Process, sig:Int=15) Source: stdlib.ngs:4977
Send signal to a Process. Uses KILL(2). Throws InvalidArgument if Process does not have "pid". Throws KillFail on error.

Parameters

sigSignal to send. Defaults to SIGNALS.TERM

Returns

unspecified at this time, do not count on it
kill(cp:CommandsPipeline, sig:Int=15) Source: stdlib.ngs:4983
Kill all processes in the CommandsPipeline. Throws InvalidArgument if CommandsPipeline is not running (yet).
limit(a:Arr, l:Int) Source: stdlib.ngs:2008
Truncate an array if necessary so it would have maximum l elements.

Parameters

aArray to (possibly) truncate.
lMaximum elements

Returns

Either a or new Arr of length l

Example

[10,11,12].limit(2)   # [10,11]
[10,11,12].limit(10)  # [10,11,12]
limit(h:Hash, l:Int) Source: stdlib.ngs:2584
Truncate a Hash if necessary so it would have maximum l key-value pairs.

Parameters

hSource hash
lMaximum elements

Returns

Hash

Example

{"a": 1, "b": 2}.limit(1)  # {"a": 1}
limit(s:Str, n:Int, marker:Str='') Source: stdlib.ngs:3483
Truncate a string if necessary so it would have maximum n characters (currently bytes).

Parameters

sThe string to (possibly) truncate.
nMaximum characters
markerThe truncation marker

Returns

Either s or new Str of length n

Example

"abc".limit(5, "...")     # "abc"
"abcdef".limit(5, "...")  # "ab..."
"abcdef".limit(2)         # "ab"
localtime(t:Int) Source: stdlib.ngs:5837
Low-level function. Do not use directly. Use Time type.
map(arr:Arr, n:Int, mapper:Fun) Source: stdlib.ngs:1690
Map each N elements of an Array at a time. mapper is called as cb(eltI, ..., eltJ) where I is multiple of n and J is I+n-1 Throws InvalidArgument if number of items in arr is not divisible by n. mapper is called as mapper(eltI, ..., eltJ) where I is multiple of n and J is I+n-1

Parameters

arrItems to iterate in chunks of n
nNumber of items in chunk
mapperFunction to be called with values from arr

Returns

Arr

Example

[1,2,3,4].map(2, F(a,b) "$a=$b").join("&")  # Outputs: 1=2&3=4
map_base_idx(base:Any, n:Int, mapper:Fun)deprecated Source: stdlib.ngs:559
Deprecated. Map when there is more than one element. If there is exactly one element, it's left as is

Parameters

mapperWill be called with zero based index and successive elements from arr

Returns

Arr
ord(s:Str, idx:Int)
Get character (byte) ordinal value. Throws InvalidArgument if idx is not pointing into s.

Parameters

idxIndex of the character to get value of

Returns

Int

Example

ord("A", 0)  # 65 on my machine
pos(haystack:Str, needle:Str, start:Int)
Find substring position

Parameters

startNon-negative Int, position where the search starts

Returns

Int or null. Not -1 as in many languages
print_exception(e:Exception, level:Int=0, parent:Exception=null) Source: stdlib.ngs:5724
Print exception to stderr. Uses inspect().

Parameters

levelindentation level to use (two spaces for each level)
parentparent exception if print_exception() was called for .cause exception
ptimes(n:Int, cb:Fun) Source: stdlib.ngs:3711
Run cb in n parallel threads. Each thread runs one cb but this might change in future (preserving the total n calls to cb).
rand(something:Any, n:Int) Source: stdlib.ngs:5909
Pick n elements from something. Uniqueness of picked elements is not guaranteed.

Returns

Any
rand(n:Int) Source: stdlib.ngs:5914
Pick random number from 0 up to but not including n

Returns

Int
rand(a:Str, n:Int) Source: stdlib.ngs:5931
Undocumented
rand_uniq(something:Any, n:Int) Source: stdlib.ngs:5892
Pick n random unique elements from something

Returns

Arr
read(fd:Int, count:Any=null) Source: stdlib.ngs:4155
Read all data from a file referenced by file descriptor without parsing it.

Parameters

fdFile descriptor to read from

Returns

Str

Example

read(0)  # All data from stdin
Real(n:Int)
Convert Int to Real
resolve_instruction_pointer(ip:Int)
Resolves Instruction Pointer to source location

Parameters

ipResult of calling Backtrace(). Backtrace().frames[0].ip for example.

Returns

Hash with keys: file, first_line, first_column, last_line, last_column, ip

Example

resolve_instruction_pointer(Backtrace().frames[0].ip)
# {ip=4770, file=/etc/ngs/bootstrap.ngs, first_line=245, first_column=1, last_line=245, last_column=34}
retry(times:Int=60, sleep:Any=1, logger:Fun=method, success_predicate:Any=method, title:Any='<retry>', progress_cb:Fun=method, success_cb:Fun=method, fail_cb:Any=null, body:Fun=method) Source: stdlib.ngs:5974
Retry. Executes given "body" "times" times. Throws RetryFail if all calls fail and fail_cb is not provided.

Parameters

timesLimit of times to run "body"
sleepEither sleep in seconds between tries or Iter that returns successive sleep times in seconds
loggerFunction to use to log attempts, caught body exceptions and sleep times. Defaults to stdlib's debug.
success_predicateCANDIDATE FOR REMOVAL. Run against body results to. Says whether the attempt succeeded. Defaults to Bool.
titlePrefix strings sent to logger with this string. Defaults to "<retry>".
progress_cbCalled before each attempt with (1) current attempt number and (2) limit of attempts ("times"). Defaults to do nothing.
success_cbCalled when body succeeds with the result that comes from body. Defaults to identity function.
fail_cbIf passed, called if all attempts fail. Defaults to null.

Returns

Any. Result of success_cb or result of fail_cb.

Example

page = retry(times=10, sleep=ExpBackIter(), body={ try `curl "http://flaky-site.com"` })
set_global_variable(idx:Int, val:Any)
Do not use directly! Set global variable by index.
split(s:Str, delim:Str, max_parts:Int=null) Source: stdlib.ngs:3325
Split string by substring

Returns

Arr of Str

Example

":a:bc:d:".split(":")   # ["", "a", "bc", "d", ""]
":a:bc:d:".split("bc")  # [":a:", ":d:"]
srand(seed:Int)
Seed random generator. Uses SRANDOM(3).

Returns

Unspecified
Str(n:Int)
Convert Int to Str
Str(x:Any, target_width:Int, ch:Str=' ') Source: stdlib.ngs:3353
Convert anything to Str of a given width
Str(s:Str, target_width:Int, ch:Str=' ') Source: stdlib.ngs:3360
Pad a string to given width with spaces

Parameters

target_widthPositive pads on right, negative pads on left

Example

Str("x", 3)  # 'x  '
Str("x",-3)  # '  x'
Str(n:Int, target_width:Int, ch:Str=' ') Source: stdlib.ngs:3382
Convert a number to a string and pad it

Parameters

target_widthPositive pads on left, negative pads on right

Example

Str(10,  4)  # '  10'
Str(10, -4)  # '10  '
StrForTable(x:Any, width:Int) Source: autoload/Table.ngs:14
Internal method. Please do not use.
StrForTable(x:Null, width:Int) Source: autoload/Table.ngs:20
Internal method. Please do not use.
take(i:Iter, n:Int) Source: autoload/Iter.ngs:82
Fetch and convert to array next n values from iterator i.

Example

i = Iter([10,20,30])
echo(i.take(2))  # Output: [10,20]
times(n:Int, cb:Fun) Source: stdlib.ngs:3169
Call cb n times without arguments.

Parameters

cbFunction to call

Example

r=0; 5.times(F() r=r+2);  # r is now 10
write(s:Str, fd:Int)deprecated Source: stdlib.ngs:4187
DEPRECATED! Do not use!
write(fd:Int, s:Str) Source: stdlib.ngs:4197
Write data to a file referenced by file descriptor. WARNING: Incomplete implementation. TODO: handle errors, throw exceptions. TODO: handle possible EINTR.

Parameters

fdFile descriptor to write to

Returns

unspecified at this time, do not count on it
~(haystack:Str, needle:Str, offset:Int=0) Source: stdlib.ngs:3508
Find substring in string. Uses pos().

Returns

Match

Example

"abc" ~ "bc"  # <MatchY ...>
"abc" ~ "X"   # <MatchN>
~(s:Str, r:RegExp, offset:Int=0, options:Int=0) Source: stdlib.ngs:5401
Find PCRE regular expression in s. Empty string without options returns MatchN. Throws Error if more than 20 captures are used or if there is an error during matching.

Automatically called by NGS for syntax

my_str ~ my_regexp

Parameters

offsetsearch start offset
optionsoptions to pass to underlying PCRE_EXEC(3).

Returns

Match

Example

globals().keys().filter(/^C_PCRE/)  # lists possible options
"xabcy" ~ /a(.)c/  # <MatchY matches=['abc','b'] named={} positions=[[1,4],[2,3]] whole=abc before=x after=y>
m = ("xabcy" ~ /a(?P<mychar>.)c/)
echo(m.named.mychar)  # Outputs: b
AWS::util::world_open_port(port:Int, proto:Str='tcp') Source: autoload/AWS.ngs:1510
Undocumented