system

検索
分類:

The compiler depends on the System module to work properly and the System module depends on the compiler. Most of the routines listed here use special compiler magic.

Each module implicitly imports the System module; it must not be listed explicitly. Because of this there cannot be a user-defined module named system.

System module

The System module imports several separate modules, and their documentation is in separate files:

Here is a short overview of the most commonly used functions from the system module. Function names in the tables below are clickable and will take you to the full documentation of the function.

The amount of available functions is much larger. Use the table of contents on the left-hand side and/or Ctrl+F to navigate through this module.

Strings and characters

Proc用法
len(s)Return the length of a string
chr(i)Convert an int in the range 0..255 to a character
ord(c)Return int value of a character
a & bConcatenate two strings
s.add(c)Add character to the string
$Convert various types to string

関連:

  • strutils module for common string functions
  • strformat module for string interpolation and formatting
  • unicode module for Unicode UTF-8 handling
  • strscans for scanf and scanp macros, which offer easier substring extraction than regular expressions
  • strtabs module for efficient hash tables (dictionaries, in some programming languages) mapping from strings to strings

Seqs

Proc用法
newSeqCreate a new sequence of a given length
newSeqOfCapCreate a new sequence with zero length and a given capacity
setLenSet the length of a sequence
lenReturn the length of a sequence
@Turn an array into a sequence
addAdd an item to the sequence
insertInsert an item at a specific position
deleteDelete an item while preserving the order of elements (O(n) operation)
delO(1) removal, doesn't preserve the order
popRemove and return last item of a sequence
x & yConcatenate two sequences
x[a..b]Slice of a sequence (both ends included)

関連:

集合

Built-in bit sets.

Proc用法
inclInclude element y in the set x
exclExclude element y from the set x
cardReturn the cardinality of the set, i.e. the number of elements
a * bIntersection
a + bUnion
a - bDifference
containsCheck if an element is in the set
a < bCheck if a is a subset of b

関連:

数値

Proc用法 Also known as (in other languages)
divInteger division//
modInteger modulo (remainder)%
shlShift left<<
shrShift right>>
ashrArithmetic shift right
andBitwise and&
orBitwise or|
xorBitwise xor^
notBitwise not (complement)~
toIntConvert floating-point number into an int
toFloatConvert an integer into a float

関連:

Ordinals

Ordinal type includes integer, bool, character, and enumeration types, as well as their subtypes.

Proc用法
succSuccessor of the value
predPredecessor of the value
incIncrement the ordinal
decDecrement the ordinal
highReturn the highest possible value
lowReturn the lowest possible value
ordReturn int value of an ordinal value

Misc

Proc用法
isCheck if two arguments are of the same type
isnotNegated version of is
!=Not equals
addrTake the address of a memory location
T and FBoolean and
T or FBoolean or
T xor FBoolean xor (exclusive or)
not TBoolean not
a .. bBinary slice that constructs an interval [a, b]
a ..< bInterval [a, b) (excluded upper bound)
runnableExamplesCreate testable documentation

int {...}{.magic: Int.}
Default integer type; bitwidth depends on architecture, but is always the same as a pointer.   ソース 編集
int8 {...}{.magic: Int8.}
Signed 8 bit integer type.   ソース 編集
int16 {...}{.magic: Int16.}
Signed 16 bit integer type.   ソース 編集
int32 {...}{.magic: Int32.}
Signed 32 bit integer type.   ソース 編集
int64 {...}{.magic: Int64.}
Signed 64 bit integer type.   ソース 編集
uint {...}{.magic: UInt.}
Unsigned default integer type.   ソース 編集
uint8 {...}{.magic: UInt8.}
Unsigned 8 bit integer type.   ソース 編集
uint16 {...}{.magic: UInt16.}
Unsigned 16 bit integer type.   ソース 編集
uint32 {...}{.magic: UInt32.}
Unsigned 32 bit integer type.   ソース 編集
uint64 {...}{.magic: UInt64.}
Unsigned 64 bit integer type.   ソース 編集
float {...}{.magic: Float.}
Default floating point type.   ソース 編集
float32 {...}{.magic: Float32.}
32 bit floating point type.   ソース 編集
float64 {...}{.magic: Float.}
64 bit floating point type.   ソース 編集
bool {...}{.magic: Bool.} = enum
  false = 0, true = 1
Built-in boolean type.   ソース 編集
char {...}{.magic: Char.}
Built-in 8 bit character type (unsigned).   ソース 編集
string {...}{.magic: String.}
Built-in string type.   ソース 編集
cstring {...}{.magic: Cstring.}
Built-in cstring (compatible string) type.   ソース 編集
pointer {...}{.magic: Pointer.}
Built-in pointer type, use the addr operator to get a pointer to a variable.   ソース 編集
typedesc {...}{.magic: TypeDesc.}
Meta type to denote a type description.   ソース 編集
Ordinal[T] {...}{.magic: Ordinal.}
Generic ordinal type. Includes integer, bool, character, and enumeration types as well as their subtypes. Note uint and uint64 are not ordinal types for implementation reasons.   ソース 編集
ptr[T] {...}{.magic: Pointer.}
Built-in generic untraced pointer type.   ソース 編集
ref[T] {...}{.magic: Pointer.}
Built-in generic traced pointer type.   ソース 編集
void {...}{.magic: "VoidType".}
Meta type to denote the absence of any type.   ソース 編集
auto {...}{.magic: Expr.}
Meta type for automatic type determination.   ソース 編集
any = distinct auto
Meta type for any supported type.   ソース 編集
untyped {...}{.magic: Expr.}
Meta type to denote an expression that is not resolved (for templates).   ソース 編集
typed {...}{.magic: Stmt.}
Meta type to denote an expression that is resolved (for templates).   ソース 編集
SomeSignedInt = int | int8 | int16 | int32 | int64
Type class matching all signed integer types.   ソース 編集
SomeUnsignedInt = uint | uint8 | uint16 | uint32 | uint64
Type class matching all unsigned integer types.   ソース 編集
SomeInteger = SomeSignedInt | SomeUnsignedInt
Type class matching all integer types.   ソース 編集
SomeOrdinal = int | int8 | int16 | int32 | int64 | bool | enum | uint | uint8 | uint16 | uint32 |
    uint64
Type class matching all ordinal types; however this includes enums with holes.   ソース 編集
SomeFloat = float | float32 | float64
Type class matching all floating point number types.   ソース 編集
SomeNumber = SomeInteger | SomeFloat
Type class matching all number types.   ソース 編集
static[T] {...}{.magic: "Static".}

Meta type representing all values that can be evaluated at compile-time.

The type coercion static(x) can be used to force the compile-time evaluation of the given expression x.

  ソース 編集
type[T] {...}{.magic: "Type".}

Meta type representing the type of all type values.

The coercion type(x) can be used to obtain the type of the given expression x.

  ソース 編集
TypeOfMode = enum
  typeOfProc,                 ## Prefer the interpretation that means `x` is a proc call.
  typeOfIter                  ## Prefer the interpretation that means `x` is an iterator call.
Possible modes of typeof.   ソース 編集
range[T] {...}{.magic: "Range".}
Generic type to construct range types.   ソース 編集
array[I; T] {...}{.magic: "Array".}
Generic type to construct fixed-length arrays.   ソース 編集
openArray[T] {...}{.magic: "OpenArray".}
Generic type to construct open arrays. Open arrays are implemented as a pointer to the array data and a length field.   ソース 編集
varargs[T] {...}{.magic: "Varargs".}
Generic type to construct a varargs type.   ソース 編集
seq[T] {...}{.magic: "Seq".}
Generic type to construct sequences.   ソース 編集
set[T] {...}{.magic: "Set".}
Generic type to construct bit sets.   ソース 編集
UncheckedArray[T] {...}{.magic: "UncheckedArray".}
  ソース 編集
sink[T] {...}{.magic: "BuiltinType".}
  ソース 編集
lent[T] {...}{.magic: "BuiltinType".}
  ソース 編集
HSlice[T; U] = object
  a*: T                        ## The lower bound (inclusive).
  b*: U                        ## The upper bound (inclusive).
  
"Heterogeneous" slice type.   ソース 編集
Slice[T] = HSlice[T, T]
An alias for HSlice[T, T].   ソース 編集
byte = uint8
This is an alias for uint8, that is an unsigned integer, 8 bits wide.   ソース 編集
Natural = range[0 .. high(int)]
is an int type ranging from zero to the maximum value of an int. This type is often useful for documentation and debugging.   ソース 編集
Positive = range[1 .. high(int)]
is an int type ranging from one to the maximum value of an int. This type is often useful for documentation and debugging.   ソース 編集
RootObj {...}{.compilerproc, inheritable.} = object

The root of Nim's object hierarchy.

Objects should inherit from RootObj or one of its descendants. However, objects that have no ancestor are also allowed.

  ソース 編集
RootRef = ref RootObj
Reference to RootObj.   ソース 編集
RootEffect {...}{.compilerproc.} = object of RootObj

Base effect class.

Each effect should inherit from RootEffect unless you know what you're doing.

  ソース 編集
TimeEffect = object of RootEffect
Time effect.   ソース 編集
IOEffect = object of RootEffect
IO effect.   ソース 編集
ReadIOEffect = object of IOEffect
Effect describing a read IO operation.   ソース 編集
WriteIOEffect = object of IOEffect
Effect describing a write IO operation.   ソース 編集
ExecIOEffect = object of IOEffect
Effect describing an executing IO operation.   ソース 編集
StackTraceEntry = object
  procname*: cstring           ## Name of the proc that is currently executing.
  line*: int                   ## Line number of the proc that is currently executing.
  filename*: cstring           ## Filename of the proc that is currently executing.
  
In debug mode exceptions store the stack trace that led to them. A StackTraceEntry is a single entry of the stack trace.   ソース 編集
Exception {...}{.compilerproc, magic: "Exception".} = object of RootObj
  parent*: ref Exception        ## Parent exception (can be used as a stack).
  name*: cstring               ## The exception's name is its Nim identifier.
               ## This field is filled automatically in the
               ## ``raise`` statement.
  msg* {...}{.exportc: "message".}: string ## The exception's message. Not
                                  ## providing an exception message
                                  ## is bad style.
  when defined(js):
      trace: string

  else:
      trace: seq[StackTraceEntry]

  when defined(nimBoostrapCsources0_19_0):
      raise_id: uint

  else:
      raiseId: uint

  up: ref Exception

Base exception class.

Each exception has to inherit from Exception. See the full exception hierarchy.

  ソース 編集
Defect = object of Exception
Abstract base class for all exceptions that Nim's runtime raises but that are strictly uncatchable as they can also be mapped to a quit / trap / exit operation.   ソース 編集
CatchableError = object of Exception
Abstract class for all exceptions that are catchable.   ソース 編集
IOError = object of CatchableError
Raised if an IO error occurred.   ソース 編集
EOFError = object of IOError
Raised if an IO "end of file" error occurred.   ソース 編集
OSError = object of CatchableError
  errorCode*: int32            ## OS-defined error code describing this error.
  
Raised if an operating system service failed.   ソース 編集
LibraryError = object of OSError
Raised if a dynamic library could not be loaded.   ソース 編集
ResourceExhaustedError = object of CatchableError
Raised if a resource request could not be fulfilled.   ソース 編集
ArithmeticError = object of Defect
Raised if any kind of arithmetic error occurred.   ソース 編集
DivByZeroError = object of ArithmeticError
Raised for runtime integer divide-by-zero errors.   ソース 編集
OverflowError = object of ArithmeticError

Raised for runtime integer overflows.

This happens for calculations whose results are too large to fit in the provided bits.

  ソース 編集
AccessViolationError = object of Defect
Raised for invalid memory access errors   Source Edit
AssertionError = object of Defect

Raised when assertion is proved wrong.

Usually the result of using the assert() template.

  ソース 編集
ValueError = object of CatchableError
Raised for string and object conversion errors.   ソース 編集
KeyError = object of ValueError

Raised if a key cannot be found in a table.

Mostly used by the tables module, it can also be raised by other collection modules like sets or strtabs.

  ソース 編集
OutOfMemError = object of Defect
Raised for unsuccessful attempts to allocate memory.   ソース 編集
IndexError = object of Defect
Raised if an array index is out of bounds.   ソース 編集
FieldError = object of Defect
Raised if a record field is not accessible because its discriminant's value does not fit.   ソース 編集
RangeError = object of Defect
Raised if a range check error occurred.   ソース 編集
StackOverflowError = object of Defect
Raised if the hardware stack used for subroutine calls overflowed.   ソース 編集
ReraiseError = object of Defect
Raised if there is no exception to reraise.   ソース 編集
ObjectAssignmentError = object of Defect
Raised if an object gets assigned to its parent's object.   ソース 編集
ObjectConversionError = object of Defect
Raised if an object is converted to an incompatible object type. You can use of operator to check if conversion will succeed.   ソース 編集
FloatingPointError = object of Defect
Base class for floating point exceptions.   ソース 編集
FloatInvalidOpError = object of FloatingPointError

Raised by invalid operations according to IEEE.

Raised by 0.0/0.0, for example.

  ソース 編集
FloatDivByZeroError = object of FloatingPointError

Raised by division by zero.

Divisor is zero and dividend is a finite nonzero number.

  ソース 編集
FloatOverflowError = object of FloatingPointError

Raised for overflows.

The operation produced a result that exceeds the range of the exponent.

  ソース 編集
FloatUnderflowError = object of FloatingPointError

Raised for underflows.

The operation produced a result that is too small to be represented as a normal number.

  ソース 編集
FloatInexactError = object of FloatingPointError

Raised for inexact results.

The operation produced a result that cannot be represented with infinite precision -- for example: 2.0 / 3.0, log(1.1)

Note: Nim currently does not detect these!

  ソース 編集
DeadThreadError = object of Defect
Raised if it is attempted to send a message to a dead thread.   ソース 編集
NilAccessError = object of Defect

Raised on dereferences of nil pointers.

This is only raised if the segfaults module was imported!

  ソース 編集
JsRoot = ref object of RootObj
  
Root type of the JavaScript object hierarchy   Source Edit
owned[T] {...}{.magic: "BuiltinType".}
type constructor to mark a ref/ptr or a closure as owned.   ソース 編集
Endianness = enum
  littleEndian, bigEndian
Type describing the endianness of a processor.   ソース 編集
TaintedString = string
A distinct string type that is tainted, see taint mode for details. It is an alias for string if the taint mode is not turned on.   ソース 編集
ByteAddress = int
is the signed integer type that should be used for converting pointers to integer addresses for readability.   ソース 編集
BiggestInt = int64
is an alias for the biggest signed integer type the Nim compiler supports. Currently this is int64, but it is platform-dependent in general.   ソース 編集
BiggestFloat = float64
is an alias for the biggest floating point type the Nim compiler supports. Currently this is float64, but it is platform-dependent in general.   ソース 編集
BiggestUInt = uint64
is an alias for the biggest unsigned integer type the Nim compiler supports. Currently this is uint32 for JS and uint64 for other targets.   ソース 編集
clong {...}{.importc: "long", nodecl.} = int32
This is the same as the type long in C.   Source Edit
culong {...}{.importc: "unsigned long", nodecl.} = uint32
This is the same as the type unsigned long in C.   Source Edit
cchar {...}{.importc: "char", nodecl.} = char
This is the same as the type char in C.   Source Edit
cschar {...}{.importc: "signed char", nodecl.} = int8
This is the same as the type signed char in C.   Source Edit
cshort {...}{.importc: "short", nodecl.} = int16
This is the same as the type short in C.   Source Edit
cint {...}{.importc: "int", nodecl.} = int32
This is the same as the type int in C.   Source Edit
csize {...}{.importc: "size_t", nodecl.} = int
This is the same as the type size_t in C.   Source Edit
clonglong {...}{.importc: "long long", nodecl.} = int64
This is the same as the type long long in C.   Source Edit
cfloat {...}{.importc: "float", nodecl.} = float32
This is the same as the type float in C.   Source Edit
cdouble {...}{.importc: "double", nodecl.} = float64
This is the same as the type double in C.   Source Edit
clongdouble {...}{.importc: "long double", nodecl.} = BiggestFloat
This is the same as the type long double in C. This C type is not supported by Nim's code generator.   Source Edit
cuchar {...}{.importc: "unsigned char", nodecl.} = char
This is the same as the type unsigned char in C.   Source Edit
cushort {...}{.importc: "unsigned short", nodecl.} = uint16
This is the same as the type unsigned short in C.   Source Edit
cuint {...}{.importc: "unsigned int", nodecl.} = uint32
This is the same as the type unsigned int in C.   Source Edit
culonglong {...}{.importc: "unsigned long long", nodecl.} = uint64
This is the same as the type unsigned long long in C.   Source Edit
cstringArray {...}{.importc: "char**", nodecl.} = ptr UncheckedArray[cstring]
This is binary compatible to the type char** in C. The array's high value is large enough to disable bounds checking in practice. Use cstringArrayToSeq proc to convert it into a seq[string].   ソース 編集
PFloat32 = ptr float32
An alias for ptr float32.   ソース 編集
PFloat64 = ptr float64
An alias for ptr float64.   ソース 編集
PInt64 = ptr int64
An alias for ptr int64.   ソース 編集
PInt32 = ptr int32
An alias for ptr int32.   ソース 編集
AtomType = SomeNumber | pointer | ptr | char | bool
Type Class representing valid types for use with atomic procs   Source Edit
GC_Strategy = enum
  gcThroughput,               ## optimize for throughput
  gcResponsiveness,           ## optimize for responsiveness (default)
  gcOptimizeTime,             ## optimize for speed
  gcOptimizeSpace             ## optimize for memory footprint
The strategy the GC should use for the application.   ソース 編集
PFrame = ptr TFrame
Represents a runtime frame of the call stack; part of the debugger API.   ソース 編集
TFrame {...}{.importc, nodecl, final.} = object
  prev*: PFrame                ## Previous frame; used for chaining the call stack.
  procname*: cstring           ## Name of the proc that is currently executing.
  line*: int                   ## Line number of the proc that is currently executing.
  filename*: cstring           ## Filename of the proc that is currently executing.
  len*: int16                  ## Length of the inspectable slots.
  calldepth*: int16            ## Used for max call depth checking.
  
The frame itself.   ソース 編集
FileSeekPos = enum
  fspSet,                     ## Seek to absolute value
  fspCur,                     ## Seek relative to current position
  fspEnd                      ## Seek relative to end
Position relative to which seek should happen.   ソース 編集
ForeignCell = object
  data*: pointer
  owner: ptr GcHeap
  ソース 編集
BackwardsIndex = distinct int
Type that is constructed by ^ for reversed array accesses. (See ^ template)   Source Edit
NimNode {...}{.magic: "PNimrodNode".} = ref NimNodeObj
Represents a Nim AST node. Macros operate on this type.   ソース 編集
ForLoopStmt {...}{.compilerproc.} = object
A special type that marks a macro as a for-loop macro. See "For Loop Macro".   ソース 編集

変数

programResult: int
deprecated, prefer quit   Source Edit
globalRaiseHook: proc (e: ref Exception): bool {...}{.nimcall, gcsafe, locks: 0.}

With this hook you can influence exception handling on a global level. If not nil, every 'raise' statement ends up calling this hook.

Warning: Ordinary application code should never set this hook! You better know what you do when setting this.

If globalRaiseHook returns false, the exception is caught and does not propagate further through the call stack.

  ソース 編集
localRaiseHook: proc (e: ref Exception): bool {...}{.nimcall, gcsafe, locks: 0.}

With this hook you can influence exception handling on a thread local level. If not nil, every 'raise' statement ends up calling this hook.

Warning: Ordinary application code should never set this hook! You better know what you do when setting this.

If localRaiseHook returns false, the exception is caught and does not propagate further through the call stack.

  ソース 編集
outOfMemHook: proc () {...}{.nimcall, tags: [], gcsafe, locks: 0, raises: [].}

Set this variable to provide a procedure that should be called in case of an out of memory event. The standard handler writes an error message and terminates the program.

outOfMemHook can be used to raise an exception in case of OOM like so:

var gOutOfMem: ref EOutOfMemory
new(gOutOfMem) # need to be allocated *before* OOM really happened!
gOutOfMem.msg = "out of memory"

proc handleOOM() =
  raise gOutOfMem

system.outOfMemHook = handleOOM

If the handler does not raise an exception, ordinary control flow continues and the program is terminated.

  ソース 編集
errorMessageWriter: (proc (msg: string) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0,
                                      nimcall.})
Function that will be called instead of stdmsg.write when printing stacktrace. この API は不安定です。  ソース 編集
onUnhandledException: (proc (errorMsg: string) {...}{.nimcall.})

Set this error handler to override the existing behaviour on an unhandled exception.

The default is to write a stacktrace to stderr and then call quit(1). この API は不安定です。

  ソース 編集

Lets

nimvm: bool = false
May be used only in when expression. It is true in Nim VM context and false otherwise.   ソース 編集

定数

on = true
Alias for true.   ソース 編集
off = false
Alias for false.   ソース 編集
appType: string = ""
A string that describes the application type. Possible values: "console", "gui", "lib".   ソース 編集
NoFakeVars = false
true if the backend doesn't support "fake variables" like var EBADF {.importc.}: cint.   ソース 編集
isMainModule: bool = false
True only when accessed in the main module. This works thanks to compiler magic. It is useful to embed testing code in a module.   ソース 編集
CompileDate: string = "0000-00-00"
The date (in UTC) of compilation as a string of the form YYYY-MM-DD. This works thanks to compiler magic.   ソース 編集
CompileTime: string = "00:00:00"
The time (in UTC) of compilation as a string of the form HH:MM:SS. This works thanks to compiler magic.   ソース 編集
cpuEndian: Endianness = littleEndian
The endianness of the target CPU. This is a valuable piece of information for low-level code only. This works thanks to compiler magic.   ソース 編集
hostOS: string = ""

A string that describes the host operating system.

Possible values: "windows", "macosx", "linux", "netbsd", "freebsd", "openbsd", "solaris", "aix", "haiku", "standalone".

  ソース 編集
hostCPU: string = ""

A string that describes the host CPU.

Possible values: "i386", "alpha", "powerpc", "powerpc64", "powerpc64el", "sparc", "amd64", "mips", "mipsel", "arm", "arm64", "mips64", "mips64el", "riscv64".

  ソース 編集
nimEnableCovariance = false
  ソース 編集
QuitSuccess = 0
is the value that should be passed to quit to indicate success.   ソース 編集
QuitFailure = 1
is the value that should be passed to quit to indicate failure.   ソース 編集
Inf = 0x0000000000000000'f64
Contains the IEEE floating point value of positive infinity.   ソース 編集
NegInf = 0x0000000000000000'f64
Contains the IEEE floating point value of negative infinity.   ソース 編集
NaN = 0x0000000000000000'f64

Contains an IEEE floating point value of Not A Number.

Note that you cannot compare a floating point value to this value and expect a reasonable result - use the classify procedure in the math module for checking for NaN.

  ソース 編集
nimCoroutines = false
  ソース 編集
NimMajor: int = 1
is the major number of Nim's version.   ソース 編集
NimMinor: int = 0
is the minor number of Nim's version.   ソース 編集
NimPatch: int = 6
is the patch number of Nim's version.   ソース 編集
NimVersion: string = "1.0.6"
is the version of Nim as a string.   ソース 編集
nativeStackTraceSupported = false
  ソース 編集

プロシージャ

proc `or`(a, b: typedesc): typedesc {...}{.magic: "TypeTrait", noSideEffect.}
Constructs an or meta class.   ソース 編集
proc `and`(a, b: typedesc): typedesc {...}{.magic: "TypeTrait", noSideEffect.}
Constructs an and meta class.   ソース 編集
proc `not`(a: typedesc): typedesc {...}{.magic: "TypeTrait", noSideEffect.}
Constructs an not meta class.   ソース 編集
proc defined(x: untyped): bool {...}{.magic: "Defined", noSideEffect, compileTime.}

Special compile-time procedure that checks whether x is defined.

x is an external symbol introduced through the compiler's -d:x switch to enable build time conditionals:

when not defined(release):
  # Do here programmer friendly expensive sanity checks.
# Put here the normal code
  ソース 編集
proc runnableExamples(body: untyped) {...}{.magic: "RunnableExamples".}
A section you should use to mark runnable example code with.
  • In normal debug and release builds code within a runnableExamples section is ignored.
  • The documentation generator is aware of these examples and considers them part of the ## doc comment. As the last step of documentation generation each runnableExample is put in its own file $file_examples$i.nim, compiled and tested. The collected examples are put into their own module to ensure the examples do not refer to non-exported symbols.

用法:

proc double*(x: int): int =
  ## This proc doubles a number.
  runnableExamples:
    ## at module scope
    assert double(5) == 10
    block: ## at block scope
      defer: echo "done"
  
  result = 2 * x
  ソース 編集
proc declared(x: untyped): bool {...}{.magic: "Defined", noSideEffect, compileTime.}

Special compile-time procedure that checks whether x is declared. x has to be an identifier or a qualified identifier.

関連:

This can be used to check whether a library provides a certain feature or not:

when not declared(strutils.toUpper):
  # provide our own toUpper proc here, because strutils is
  # missing it.
  ソース 編集
proc declaredInScope(x: untyped): bool {...}{.magic: "DefinedInScope", noSideEffect,
                                     compileTime.}
Special compile-time procedure that checks whether x is declared in the current scope. x has to be an identifier.   ソース 編集
proc `addr`[T](x: var T): ptr T {...}{.magic: "Addr", noSideEffect.}

Builtin addr operator for taking the address of a memory location. Cannot be overloaded.

関連:

var
  buf: seq[char] = @['a','b','c']
  p = buf[1].addr
echo p.repr # ref 0x7faa35c40059 --> 'b'
echo p[]    # b
  ソース 編集
proc unsafeAddr[T](x: T): ptr T {...}{.magic: "Addr", noSideEffect.}

Builtin addr operator for taking the address of a memory location. This works even for let variables or parameters for better interop with C and so it is considered even more unsafe than the ordinary addr.

Note: When you use it to write a wrapper for a C library, you should always check that the original library does never write to data behind the pointer that is returned from this procedure.

Cannot be overloaded.

  ソース 編集
proc typeof(x: untyped; mode = typeOfIter): typedesc {...}{.magic: "TypeOf", noSideEffect,
    compileTime.}
Builtin typeof operation for accessing the type of an expression. Since version 0.20.0.   ソース 編集
proc `not`(x: bool): bool {...}{.magic: "Not", noSideEffect.}
Boolean not; returns true if x == false.   ソース 編集
proc `and`(x, y: bool): bool {...}{.magic: "And", noSideEffect.}

Boolean and; returns true if x == y == true (if both arguments are true).

Evaluation is lazy: if x is false, y will not even be evaluated.

  ソース 編集
proc `or`(x, y: bool): bool {...}{.magic: "Or", noSideEffect.}

Boolean or; returns true if not (not x and not y) (if any of the arguments is true).

Evaluation is lazy: if x is true, y will not even be evaluated.

  ソース 編集
proc `xor`(x, y: bool): bool {...}{.magic: "Xor", noSideEffect.}
Boolean exclusive or; returns true if x != y (if either argument is true while the other is false).   ソース 編集
proc internalNew[T](a: var ref T) {...}{.magic: "New", noSideEffect.}
Leaked implementation detail. Do not use.   ソース 編集
proc new[T](a: var ref T; finalizer: proc (x: ref T) {...}{.nimcall.}) {...}{.magic: "NewFinalize",
    noSideEffect.}

Creates a new object of type T and returns a safe (traced) reference to it in a.

When the garbage collector frees the object, finalizer is called. The finalizer may not keep a reference to the object pointed to by x. The finalizer cannot prevent the GC from freeing the object.

Note: The finalizer refers to the type T, not to the object! This means that for each object of type T the finalizer will be called!

  ソース 編集
proc reset[T](obj: var T) {...}{.magic: "Reset", noSideEffect.}

Old runtime target: Resets an object obj to its initial (binary zero) value.

New runtime target: An alias for =destroy.

  ソース 編集
proc wasMoved[T](obj: var T) {...}{.magic: "WasMoved", noSideEffect.}
Resets an object obj to its initial (binary zero) value to signify it was "moved" and to signify its destructor should do nothing and ideally be optimized away.   ソース 編集
proc move[T](x: var T): T {...}{.magic: "Move", noSideEffect.}
  ソース 編集
proc high[T: Ordinal | enum | range](x: T): T {...}{.magic: "High", noSideEffect.}

Returns the highest possible value of an ordinal value x.

As a special semantic rule, x may also be a type identifier.

関連:

high(2) # => 9223372036854775807
  ソース 編集
proc high[T: Ordinal | enum | range](x: typedesc[T]): T {...}{.magic: "High", noSideEffect.}

Returns the highest possible value of an ordinal or enum type.

high(int) is Nim's way of writing INT_MAX or MAX_INT.

関連:

high(int) # => 9223372036854775807
  ソース 編集
proc high[T](x: openArray[T]): int {...}{.magic: "High", noSideEffect.}

Returns the highest possible index of a sequence x.

関連:

var s = @[1, 2, 3, 4, 5, 6, 7]
high(s) # => 6
for i in low(s)..high(s):
  echo s[i]
  ソース 編集
proc high[I, T](x: array[I, T]): I {...}{.magic: "High", noSideEffect.}

Returns the highest possible index of an array x.

関連:

var arr = [1, 2, 3, 4, 5, 6, 7]
high(arr) # => 6
for i in low(arr)..high(arr):
  echo arr[i]
  ソース 編集
proc high[I, T](x: typedesc[array[I, T]]): I {...}{.magic: "High", noSideEffect.}

Returns the highest possible index of an array type.

関連:

high(array[7, int]) # => 6
  ソース 編集
proc high(x: cstring): int {...}{.magic: "High", noSideEffect.}

Returns the highest possible index of a compatible string x. This is sometimes an O(n) operation.

関連:

  ソース 編集
proc high(x: string): int {...}{.magic: "High", noSideEffect.}

Returns the highest possible index of a string x.

関連:

var str = "Hello world!"
high(str) # => 11
  ソース 編集
proc low[T: Ordinal | enum | range](x: T): T {...}{.magic: "Low", noSideEffect.}

Returns the lowest possible value of an ordinal value x. As a special semantic rule, x may also be a type identifier.

関連:

low(2) # => -9223372036854775808
  ソース 編集
proc low[T: Ordinal | enum | range](x: typedesc[T]): T {...}{.magic: "Low", noSideEffect.}

Returns the lowest possible value of an ordinal or enum type.

low(int) is Nim's way of writing INT_MIN or MIN_INT.

関連:

low(int) # => -9223372036854775808
  ソース 編集
proc low[T](x: openArray[T]): int {...}{.magic: "Low", noSideEffect.}

Returns the lowest possible index of a sequence x.

関連:

var s = @[1, 2, 3, 4, 5, 6, 7]
low(s) # => 0
for i in low(s)..high(s):
  echo s[i]
  ソース 編集
proc low[I, T](x: array[I, T]): I {...}{.magic: "Low", noSideEffect.}

Returns the lowest possible index of an array x.

関連:

var arr = [1, 2, 3, 4, 5, 6, 7]
low(arr) # => 0
for i in low(arr)..high(arr):
  echo arr[i]
  ソース 編集
proc low[I, T](x: typedesc[array[I, T]]): I {...}{.magic: "Low", noSideEffect.}

Returns the lowest possible index of an array type.

関連:

low(array[7, int]) # => 0
  ソース 編集
proc low(x: cstring): int {...}{.magic: "Low", noSideEffect.}

Returns the lowest possible index of a compatible string x.

関連:

  ソース 編集
proc low(x: string): int {...}{.magic: "Low", noSideEffect.}

Returns the lowest possible index of a string x.

関連:

var str = "Hello world!"
low(str) # => 0
  ソース 編集
proc shallowCopy[T](x: var T; y: T) {...}{.noSideEffect, magic: "ShallowCopy".}

Use this instead of = for a shallow copy.

The shallow copy only changes the semantics for sequences and strings (and types which contain those).

Be careful with the changed semantics though! There is a reason why the default assignment does a deep copy of sequences and strings.

  ソース 編集
proc `[]`[I: Ordinal; T](a: T; i: I): T {...}{.noSideEffect, magic: "ArrGet".}
  ソース 編集
proc `[]=`[I: Ordinal; T, S](a: T; i: I; x: S) {...}{.noSideEffect, magic: "ArrPut".}
  ソース 編集
proc `=`[T](dest: var T; src: T) {...}{.noSideEffect, magic: "Asgn".}
  ソース 編集
proc `=destroy`[T](x: var T) {...}{.inline, magic: "Destroy".}
Generic destructor implementation that can be overridden.   ソース 編集
proc `=sink`[T](x: var T; y: T) {...}{.inline, magic: "Asgn".}
Generic sink implementation that can be overridden.   ソース 編集
proc `..`[T, U](a: T; b: U): HSlice[T, U] {...}{.noSideEffect, inline, magic: "DotDot".}

Binary slice operator that constructs an interval [a, b], both a and b are inclusive.

Slices can also be used in the set constructor and in ordinal case statements, but then they are special-cased by the compiler.

let a = [10, 20, 30, 40, 50]
echo a[2 .. 3] # @[30, 40]
  ソース 編集
proc `..`[T](b: T): HSlice[int, T] {...}{.noSideEffect, inline, magic: "DotDot".}
Unary slice operator that constructs an interval [default(int), b].
let a = [10, 20, 30, 40, 50]
echo a[.. 2] # @[10, 20, 30]
  ソース 編集
proc `==`[Enum: enum](x, y: Enum): bool {...}{.magic: "EqEnum", noSideEffect.}
Checks whether values within the same enum have the same underlying value.
type
  Enum1 = enum
    Field1 = 3, Field2
  Enum2 = enum
    Place1, Place2 = 3
var
  e1 = Field1
  e2 = Enum1(Place2)
echo (e1 == e2) # true
echo (e1 == Place2) # raises error
  ソース 編集
proc `==`(x, y: pointer): bool {...}{.magic: "EqRef", noSideEffect.}
var # this is a wildly dangerous example
  a = cast[pointer](0)
  b = cast[pointer](nil)
echo (a == b) # true due to the special meaning of `nil`/0 as a pointer
  ソース 編集
proc `==`(x, y: string): bool {...}{.magic: "EqStr", noSideEffect.}
Checks for equality between two string variables.   ソース 編集
proc `==`(x, y: char): bool {...}{.magic: "EqCh", noSideEffect.}
Checks for equality between two char variables.   ソース 編集
proc `==`(x, y: bool): bool {...}{.magic: "EqB", noSideEffect.}
Checks for equality between two bool variables.   ソース 編集
proc `==`[T](x, y: set[T]): bool {...}{.magic: "EqSet", noSideEffect.}
Checks for equality between two variables of type set.
var a = {1, 2, 2, 3} # duplication in sets is ignored
var b = {1, 2, 3}
echo (a == b) # true
  ソース 編集
proc `==`[T](x, y: ref T): bool {...}{.magic: "EqRef", noSideEffect.}
Checks that two ref variables refer to the same item.   ソース 編集
proc `==`[T](x, y: ptr T): bool {...}{.magic: "EqRef", noSideEffect.}
Checks that two ptr variables refer to the same item.   ソース 編集
proc `==`[T: proc](x, y: T): bool {...}{.magic: "EqProc", noSideEffect.}
Checks that two proc variables refer to the same procedure.   ソース 編集
proc `<=`[Enum: enum](x, y: Enum): bool {...}{.magic: "LeEnum", noSideEffect.}
  ソース 編集
proc `<=`(x, y: string): bool {...}{.magic: "LeStr", noSideEffect.}
Compares two strings and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).
let
  a = "abc"
  b = "abd"
  c = "ZZZ"
assert a <= b
assert a <= a
assert (a <= c) == false
  ソース 編集
proc `<=`(x, y: char): bool {...}{.magic: "LeCh", noSideEffect.}
Compares two chars and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).
let
  a = 'a'
  b = 'b'
  c = 'Z'
assert a <= b
assert a <= a
assert (a <= c) == false
  ソース 編集
proc `<=`[T](x, y: set[T]): bool {...}{.magic: "LeSet", noSideEffect.}

Returns true if x is a subset of y.

A subset x has all of its members in y and y doesn't necessarily have more members than x. That is, x can be equal to y.

let
  a = {3, 5}
  b = {1, 3, 5, 7}
  c = {2}
assert a <= b
assert a <= a
assert (a <= c) == false
  ソース 編集
proc `<=`(x, y: bool): bool {...}{.magic: "LeB", noSideEffect.}
  ソース 編集
proc `<=`[T](x, y: ref T): bool {...}{.magic: "LePtr", noSideEffect.}
  ソース 編集
proc `<=`(x, y: pointer): bool {...}{.magic: "LePtr", noSideEffect.}
  ソース 編集
proc `<`[Enum: enum](x, y: Enum): bool {...}{.magic: "LtEnum", noSideEffect.}
  ソース 編集
proc `<`(x, y: string): bool {...}{.magic: "LtStr", noSideEffect.}
Compares two strings and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).
let
  a = "abc"
  b = "abd"
  c = "ZZZ"
assert a < b
assert (a < a) == false
assert (a < c) == false
  ソース 編集
proc `<`(x, y: char): bool {...}{.magic: "LtCh", noSideEffect.}
Compares two chars and returns true if x is lexicographically before y (uppercase letters come before lowercase letters).
let
  a = 'a'
  b = 'b'
  c = 'Z'
assert a < b
assert (a < a) == false
assert (a < c) == false
  ソース 編集
proc `<`[T](x, y: set[T]): bool {...}{.magic: "LtSet", noSideEffect.}

Returns true if x is a strict or proper subset of y.

A strict or proper subset x has all of its members in y but y has more elements than y.

let
  a = {3, 5}
  b = {1, 3, 5, 7}
  c = {2}
assert a < b
assert (a < a) == false
assert (a < c) == false
  ソース 編集
proc `<`(x, y: bool): bool {...}{.magic: "LtB", noSideEffect.}
  ソース 編集
proc `<`[T](x, y: ref T): bool {...}{.magic: "LtPtr", noSideEffect.}
  ソース 編集
proc `<`[T](x, y: ptr T): bool {...}{.magic: "LtPtr", noSideEffect.}
  ソース 編集
proc `<`(x, y: pointer): bool {...}{.magic: "LtPtr", noSideEffect.}
  ソース 編集
proc unsafeNew[T](a: var ref T; size: Natural) {...}{.magic: "New", noSideEffect.}

Creates a new object of type T and returns a safe (traced) reference to it in a.

This is unsafe as it allocates an object of the passed size. This should only be used for optimization purposes when you know what you're doing!

関連:

  ソース 編集
proc sizeof[T](x: T): int {...}{.magic: "SizeOf", noSideEffect.}

Returns the size of x in bytes.

Since this is a low-level proc, its usage is discouraged - using new for the most cases suffices that one never needs to know x's size.

As a special semantic rule, x may also be a type identifier (sizeof(int) is valid).

Limitations: If used for types that are imported from C or C++, sizeof should fallback to the sizeof in the C compiler. The result isn't available for the Nim compiler and therefore can't be used inside of macros.

sizeof('A') # => 1
sizeof(2) # => 8
  ソース 編集
proc alignof[T](x: T): int {...}{.magic: "AlignOf", noSideEffect.}
  ソース 編集
proc alignof(x: typedesc): int {...}{.magic: "AlignOf", noSideEffect.}
  ソース 編集
proc sizeof(x: typedesc): int {...}{.magic: "SizeOf", noSideEffect.}
  ソース 編集
proc `<`[T](x: Ordinal[T]): T {...}{.magic: "UnaryLt", noSideEffect, deprecated.}
廃止予定

Deprecated since version 0.18.0. For the common excluding range write 0 ..< 10 instead of 0 .. < 10 (look at the spacing). For <x write pred(x).

Unary < that can be used for excluding ranges. Semantically this is the same as pred.

for i in 0 .. <10: echo i # => 0 1 2 3 4 5 6 7 8 9
  ソース 編集
proc succ[T: Ordinal](x: T; y = 1): T {...}{.magic: "Succ", noSideEffect.}

Returns the y-th successor (default: 1) of the value x. T has to be an ordinal type.

If such a value does not exist, OverflowError is raised or a compile time error occurs.

let x = 5
echo succ(5)    # => 6
echo succ(5, 3) # => 8
  ソース 編集
proc pred[T: Ordinal](x: T; y = 1): T {...}{.magic: "Pred", noSideEffect.}

Returns the y-th predecessor (default: 1) of the value x. T has to be an ordinal type.

If such a value does not exist, OverflowError is raised or a compile time error occurs.

let x = 5
echo pred(5)    # => 4
echo pred(5, 3) # => 2
  ソース 編集
proc inc[T: Ordinal | uint | uint64](x: var T; y = 1) {...}{.magic: "Inc", noSideEffect.}

Increments the ordinal x by y.

If such a value does not exist, OverflowError is raised or a compile time error occurs. This is a short notation for: x = succ(x, y).

var i = 2
inc(i)    # i <- 3
inc(i, 3) # i <- 6
  ソース 編集
proc dec[T: Ordinal | uint | uint64](x: var T; y = 1) {...}{.magic: "Dec", noSideEffect.}

Decrements the ordinal x by y.

If such a value does not exist, OverflowError is raised or a compile time error occurs. This is a short notation for: x = pred(x, y).

var i = 2
dec(i)    # i <- 1
dec(i, 3) # i <- -2
  ソース 編集
proc newSeq[T](s: var seq[T]; len: Natural) {...}{.magic: "NewSeq", noSideEffect.}

Creates a new sequence of type seq[T] with length len.

This is equivalent to s = @[]; setlen(s, len), but more efficient since no reallocation is needed.

Note that the sequence will be filled with zeroed entries. After the creation of the sequence you should assign entries to the sequence instead of adding them. 用例:

var inputStrings : seq[string]
newSeq(inputStrings, 3)
assert len(inputStrings) == 3
inputStrings[0] = "The fourth"
inputStrings[1] = "assignment"
inputStrings[2] = "would crash"
#inputStrings[3] = "out of bounds"
  ソース 編集
proc newSeq[T](len = 0.Natural): seq[T]

Creates a new sequence of type seq[T] with length len.

Note that the sequence will be filled with zeroed entries. After the creation of the sequence you should assign entries to the sequence instead of adding them.

関連:

var inputStrings = newSeq[string](3)
assert len(inputStrings) == 3
inputStrings[0] = "The fourth"
inputStrings[1] = "assignment"
inputStrings[2] = "would crash"
#inputStrings[3] = "out of bounds"
  ソース 編集
proc newSeqOfCap[T](cap: Natural): seq[T] {...}{.magic: "NewSeqOfCap", noSideEffect.}
Creates a new sequence of type seq[T] with length zero and capacity cap.
var x = newSeqOfCap[int](5)
assert len(x) == 0
x.add(10)
assert len(x) == 1
  ソース 編集
proc newSeqUninitialized[T: SomeNumber](len: Natural): seq[T]

Creates a new sequence of type seq[T] with length len.

Only available for numbers types. Note that the sequence will be uninitialized. After the creation of the sequence you should assign entries to the sequence instead of adding them.

var x = newSeqUninitialized[int](3)
assert len(x) == 3
x[0] = 10
  ソース 編集
proc len[TOpenArray: openArray | varargs](x: TOpenArray): int {...}{.
    magic: "LengthOpenArray", noSideEffect.}
Returns the length of an openArray.
var s = [1, 1, 1, 1, 1]
echo len(s) # => 5
  ソース 編集
proc len(x: string): int {...}{.magic: "LengthStr", noSideEffect.}
Returns the length of a string.
var str = "Hello world!"
echo len(str) # => 12
  ソース 編集
proc len(x: cstring): int {...}{.magic: "LengthStr", noSideEffect.}
Returns the length of a compatible string. This is sometimes an O(n) operation.
var str: cstring = "Hello world!"
len(str) # => 12
  ソース 編集
proc len(x: (type array) | array): int {...}{.magic: "LengthArray", noSideEffect.}
Returns the length of an array or an array type. This is roughly the same as high(T)-low(T)+1.
var arr = [1, 1, 1, 1, 1]
echo len(arr) # => 5
echo len(array[3..8, int]) # => 6
  ソース 編集
proc len[T](x: seq[T]): int {...}{.magic: "LengthSeq", noSideEffect.}
Returns the length of a sequence.
var s = @[1, 1, 1, 1, 1]
echo len(s) # => 5
  ソース 編集
proc incl[T](x: var set[T]; y: T) {...}{.magic: "Incl", noSideEffect.}

Includes element y in the set x.

This is the same as x = x + {y}, but it might be more efficient.

var a = {1, 3, 5}
a.incl(2) # a <- {1, 2, 3, 5}
a.incl(4) # a <- {1, 2, 3, 4, 5}
  ソース 編集
proc excl[T](x: var set[T]; y: T) {...}{.magic: "Excl", noSideEffect.}

Excludes element y from the set x.

This is the same as x = x - {y}, but it might be more efficient.

var b = {2, 3, 5, 6, 12, 545}
b.excl(5)  # b <- {2, 3, 6, 12, 545}
  ソース 編集
proc card[T](x: set[T]): int {...}{.magic: "Card", noSideEffect.}
Returns the cardinality of the set x, i.e. the number of elements in the set.
var a = {1, 3, 5, 7}
echo card(a) # => 4
  ソース 編集
proc len[T](x: set[T]): int {...}{.magic: "Card", noSideEffect.}
An alias for card(x).   ソース 編集
proc ord[T: Ordinal | enum](x: T): int {...}{.magic: "Ord", noSideEffect.}
Returns the internal int value of an ordinal value x.
echo ord('A') # => 65
echo ord('a') # => 97
  ソース 編集
proc chr(u: range[0 .. 255]): char {...}{.magic: "Chr", noSideEffect.}
Converts an int in the range 0..255 to a character.
echo chr(65) # => A
echo chr(97) # => a
  ソース 編集
proc ze(x: int8): int {...}{.deprecated, raises: [], tags: [].}
廃止予定
zero extends a smaller integer type to int. This treats x as unsigned. Deprecated since version 0.19.9: Use unsigned integers instead.   Source Edit
proc ze(x: int16): int {...}{.deprecated, raises: [], tags: [].}
廃止予定
zero extends a smaller integer type to int. This treats x as unsigned. Deprecated since version 0.19.9: Use unsigned integers instead.   Source Edit
proc ze64(x: int8): int64 {...}{.deprecated, raises: [], tags: [].}
廃止予定
zero extends a smaller integer type to int64. This treats x as unsigned. Deprecated since version 0.19.9: Use unsigned integers instead.   Source Edit
proc ze64(x: int16): int64 {...}{.deprecated, raises: [], tags: [].}
廃止予定
zero extends a smaller integer type to int64. This treats x as unsigned. Deprecated since version 0.19.9: Use unsigned integers instead.   Source Edit
proc ze64(x: int32): int64 {...}{.deprecated, raises: [], tags: [].}
廃止予定
zero extends a smaller integer type to int64. This treats x as unsigned. Deprecated since version 0.19.9: Use unsigned integers instead.   Source Edit
proc ze64(x: int): int64 {...}{.deprecated, raises: [], tags: [].}
廃止予定
zero extends a smaller integer type to int64. This treats x as unsigned. Does nothing if the size of an int is the same as int64. (This is the case on 64 bit processors.) Deprecated since version 0.19.9: Use unsigned integers instead.   Source Edit
proc toU8(x: int): int8 {...}{.deprecated, raises: [], tags: [].}
廃止予定
treats x as unsigned and converts it to a byte by taking the last 8 bits from x. Deprecated since version 0.19.9: Use unsigned integers instead.   Source Edit
proc toU16(x: int): int16 {...}{.deprecated, raises: [], tags: [].}
廃止予定
treats x as unsigned and converts it to an int16 by taking the last 16 bits from x. Deprecated since version 0.19.9: Use unsigned integers instead.   Source Edit
proc toU32(x: int64): int32 {...}{.deprecated, raises: [], tags: [].}
廃止予定
treats x as unsigned and converts it to an int32 by taking the last 32 bits from x. Deprecated since version 0.19.9: Use unsigned integers instead.   Source Edit
proc `+`(x: int): int {...}{.magic: "UnaryPlusI", noSideEffect.}
Unary + operator for an integer. Has no effect.   ソース 編集
proc `+`(x: int8): int8 {...}{.magic: "UnaryPlusI", noSideEffect.}
  ソース 編集
proc `+`(x: int16): int16 {...}{.magic: "UnaryPlusI", noSideEffect.}
  ソース 編集
proc `+`(x: int32): int32 {...}{.magic: "UnaryPlusI", noSideEffect.}
  ソース 編集
proc `+`(x: int64): int64 {...}{.magic: "UnaryPlusI", noSideEffect.}
  ソース 編集
proc `-`(x: int): int {...}{.magic: "UnaryMinusI", noSideEffect.}
Unary - operator for an integer. Negates x.   ソース 編集
proc `-`(x: int8): int8 {...}{.magic: "UnaryMinusI", noSideEffect.}
  ソース 編集
proc `-`(x: int16): int16 {...}{.magic: "UnaryMinusI", noSideEffect.}
  ソース 編集
proc `-`(x: int32): int32 {...}{.magic: "UnaryMinusI", noSideEffect.}
  ソース 編集
proc `-`(x: int64): int64 {...}{.magic: "UnaryMinusI64", noSideEffect.}
  ソース 編集
proc `not`(x: int): int {...}{.magic: "BitnotI", noSideEffect.}
Computes the bitwise complement of the integer x.
var
  a = 0'u8
  b = 0'i8
  c = 1000'u16
  d = 1000'i16

echo not a # => 255
echo not b # => -1
echo not c # => 64535
echo not d # => -1001
  ソース 編集
proc `not`(x: int8): int8 {...}{.magic: "BitnotI", noSideEffect.}
  ソース 編集
proc `not`(x: int16): int16 {...}{.magic: "BitnotI", noSideEffect.}
  ソース 編集
proc `not`(x: int32): int32 {...}{.magic: "BitnotI", noSideEffect.}
  ソース 編集
proc `not`(x: int64): int64 {...}{.magic: "BitnotI", noSideEffect.}
  ソース 編集
proc `+`(x, y: int): int {...}{.magic: "AddI", noSideEffect.}
Binary + operator for an integer.   ソース 編集
proc `+`(x, y: int8): int8 {...}{.magic: "AddI", noSideEffect.}
  ソース 編集
proc `+`(x, y: int16): int16 {...}{.magic: "AddI", noSideEffect.}
  ソース 編集
proc `+`(x, y: int32): int32 {...}{.magic: "AddI", noSideEffect.}
  ソース 編集
proc `+`(x, y: int64): int64 {...}{.magic: "AddI", noSideEffect.}
  ソース 編集
proc `-`(x, y: int): int {...}{.magic: "SubI", noSideEffect.}
Binary - operator for an integer.   ソース 編集
proc `-`(x, y: int8): int8 {...}{.magic: "SubI", noSideEffect.}
  ソース 編集
proc `-`(x, y: int16): int16 {...}{.magic: "SubI", noSideEffect.}
  ソース 編集
proc `-`(x, y: int32): int32 {...}{.magic: "SubI", noSideEffect.}
  ソース 編集
proc `-`(x, y: int64): int64 {...}{.magic: "SubI", noSideEffect.}
  ソース 編集
proc `*`(x, y: int): int {...}{.magic: "MulI", noSideEffect.}
Binary * operator for an integer.   ソース 編集
proc `*`(x, y: int8): int8 {...}{.magic: "MulI", noSideEffect.}
  ソース 編集
proc `*`(x, y: int16): int16 {...}{.magic: "MulI", noSideEffect.}
  ソース 編集
proc `*`(x, y: int32): int32 {...}{.magic: "MulI", noSideEffect.}
  ソース 編集
proc `*`(x, y: int64): int64 {...}{.magic: "MulI", noSideEffect.}
  ソース 編集
proc `div`(x, y: int): int {...}{.magic: "DivI", noSideEffect.}

Computes the integer division.

This is roughly the same as trunc(x/y).

( 1 div  2) ==  0
( 2 div  2) ==  1
( 3 div  2) ==  1
( 7 div  3) ==  2
(-7 div  3) == -2
( 7 div -3) == -2
(-7 div -3) ==  2
  ソース 編集
proc `div`(x, y: int8): int8 {...}{.magic: "DivI", noSideEffect.}
  ソース 編集
proc `div`(x, y: int16): int16 {...}{.magic: "DivI", noSideEffect.}
  ソース 編集
proc `div`(x, y: int32): int32 {...}{.magic: "DivI", noSideEffect.}
  ソース 編集
proc `div`(x, y: int64): int64 {...}{.magic: "DivI", noSideEffect.}
  ソース 編集
proc `mod`(x, y: int): int {...}{.magic: "ModI", noSideEffect.}

Computes the integer modulo operation (remainder).

This is the same as x - (x div y) * y.

( 7 mod  5) ==  2
(-7 mod  5) == -2
( 7 mod -5) ==  2
(-7 mod -5) == -2
  ソース 編集
proc `mod`(x, y: int8): int8 {...}{.magic: "ModI", noSideEffect.}
  ソース 編集
proc `mod`(x, y: int16): int16 {...}{.magic: "ModI", noSideEffect.}
  ソース 編集
proc `mod`(x, y: int32): int32 {...}{.magic: "ModI", noSideEffect.}
  ソース 編集
proc `mod`(x, y: int64): int64 {...}{.magic: "ModI", noSideEffect.}
  ソース 編集
proc `shr`(x: int; y: SomeInteger): int {...}{.magic: "AshrI", noSideEffect.}

Computes the shift right operation of x and y, filling vacant bit positions with the sign bit.

Note: Operator precedence is different than in C.

関連:

0b0001_0000'i8 shr 2 == 0b0000_0100'i8
0b0000_0001'i8 shr 1 == 0b0000_0000'i8
0b1000_0000'i8 shr 4 == 0b1111_1000'i8
-1 shr 5 == -1
1 shr 5 == 0
16 shr 2 == 4
-16 shr 2 == -4
  ソース 編集
proc `shr`(x: int8; y: SomeInteger): int8 {...}{.magic: "AshrI", noSideEffect.}
  ソース 編集
proc `shr`(x: int16; y: SomeInteger): int16 {...}{.magic: "AshrI", noSideEffect.}
  ソース 編集
proc `shr`(x: int32; y: SomeInteger): int32 {...}{.magic: "AshrI", noSideEffect.}
  ソース 編集
proc `shr`(x: int64; y: SomeInteger): int64 {...}{.magic: "AshrI", noSideEffect.}
  ソース 編集
proc `shl`(x: int; y: SomeInteger): int {...}{.magic: "ShlI", noSideEffect.}

Computes the shift left operation of x and y.

Note: Operator precedence is different than in C.

1'i32 shl 4 == 0x0000_0010
1'i64 shl 4 == 0x0000_0000_0000_0010
  ソース 編集
proc `shl`(x: int8; y: SomeInteger): int8 {...}{.magic: "ShlI", noSideEffect.}
  ソース 編集
proc `shl`(x: int16; y: SomeInteger): int16 {...}{.magic: "ShlI", noSideEffect.}
  ソース 編集
proc `shl`(x: int32; y: SomeInteger): int32 {...}{.magic: "ShlI", noSideEffect.}
  ソース 編集
proc `shl`(x: int64; y: SomeInteger): int64 {...}{.magic: "ShlI", noSideEffect.}
  ソース 編集
proc ashr(x: int; y: SomeInteger): int {...}{.magic: "AshrI", noSideEffect.}

Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.

Note that ashr is not an operator so use the normal function call syntax for it.

関連:

ashr(0b0001_0000'i8, 2) == 0b0000_0100'i8
ashr(0b1000_0000'i8, 8) == 0b1111_1111'i8
ashr(0b1000_0000'i8, 1) == 0b1100_0000'i8
  ソース 編集
proc ashr(x: int8; y: SomeInteger): int8 {...}{.magic: "AshrI", noSideEffect.}
  ソース 編集
proc ashr(x: int16; y: SomeInteger): int16 {...}{.magic: "AshrI", noSideEffect.}
  ソース 編集
proc ashr(x: int32; y: SomeInteger): int32 {...}{.magic: "AshrI", noSideEffect.}
  ソース 編集
proc ashr(x: int64; y: SomeInteger): int64 {...}{.magic: "AshrI", noSideEffect.}
  ソース 編集
proc `and`(x, y: int): int {...}{.magic: "BitandI", noSideEffect.}
Computes the bitwise and of numbers x and y.
(0b0011 and 0b0101) == 0b0001
(0b0111 and 0b1100) == 0b0100
  ソース 編集
proc `and`(x, y: int8): int8 {...}{.magic: "BitandI", noSideEffect.}
  ソース 編集
proc `and`(x, y: int16): int16 {...}{.magic: "BitandI", noSideEffect.}
  ソース 編集
proc `and`(x, y: int32): int32 {...}{.magic: "BitandI", noSideEffect.}
  ソース 編集
proc `and`(x, y: int64): int64 {...}{.magic: "BitandI", noSideEffect.}
  ソース 編集
proc `or`(x, y: int): int {...}{.magic: "BitorI", noSideEffect.}
Computes the bitwise or of numbers x and y.
(0b0011 or 0b0101) == 0b0111
(0b0111 or 0b1100) == 0b1111
  ソース 編集
proc `or`(x, y: int8): int8 {...}{.magic: "BitorI", noSideEffect.}
  ソース 編集
proc `or`(x, y: int16): int16 {...}{.magic: "BitorI", noSideEffect.}
  ソース 編集
proc `or`(x, y: int32): int32 {...}{.magic: "BitorI", noSideEffect.}
  ソース 編集
proc `or`(x, y: int64): int64 {...}{.magic: "BitorI", noSideEffect.}
  ソース 編集
proc `xor`(x, y: int): int {...}{.magic: "BitxorI", noSideEffect.}
Computes the bitwise xor of numbers x and y.
(0b0011 xor 0b0101) == 0b0110
(0b0111 xor 0b1100) == 0b1011
  ソース 編集
proc `xor`(x, y: int8): int8 {...}{.magic: "BitxorI", noSideEffect.}
  ソース 編集
proc `xor`(x, y: int16): int16 {...}{.magic: "BitxorI", noSideEffect.}
  ソース 編集
proc `xor`(x, y: int32): int32 {...}{.magic: "BitxorI", noSideEffect.}
  ソース 編集
proc `xor`(x, y: int64): int64 {...}{.magic: "BitxorI", noSideEffect.}
  ソース 編集
proc `==`(x, y: int): bool {...}{.magic: "EqI", noSideEffect.}
Compares two integers for equality.   ソース 編集
proc `==`(x, y: int8): bool {...}{.magic: "EqI", noSideEffect.}
  ソース 編集
proc `==`(x, y: int16): bool {...}{.magic: "EqI", noSideEffect.}
  ソース 編集
proc `==`(x, y: int32): bool {...}{.magic: "EqI", noSideEffect.}
  ソース 編集
proc `==`(x, y: int64): bool {...}{.magic: "EqI", noSideEffect.}
  ソース 編集
proc `<=`(x, y: int): bool {...}{.magic: "LeI", noSideEffect.}
Returns true if x is less than or equal to y.   ソース 編集
proc `<=`(x, y: int8): bool {...}{.magic: "LeI", noSideEffect.}
  ソース 編集
proc `<=`(x, y: int16): bool {...}{.magic: "LeI", noSideEffect.}
  ソース 編集
proc `<=`(x, y: int32): bool {...}{.magic: "LeI", noSideEffect.}
  ソース 編集
proc `<=`(x, y: int64): bool {...}{.magic: "LeI", noSideEffect.}
  ソース 編集
proc `<`(x, y: int): bool {...}{.magic: "LtI", noSideEffect.}
Returns true if x is less than y.   ソース 編集
proc `<`(x, y: int8): bool {...}{.magic: "LtI", noSideEffect.}
  ソース 編集
proc `<`(x, y: int16): bool {...}{.magic: "LtI", noSideEffect.}
  ソース 編集
proc `<`(x, y: int32): bool {...}{.magic: "LtI", noSideEffect.}
  ソース 編集
proc `<`(x, y: int64): bool {...}{.magic: "LtI", noSideEffect.}
  ソース 編集
proc `+%`(x, y: IntMax32): IntMax32 {...}{.magic: "AddU", noSideEffect.}
  ソース 編集
proc `+%`(x, y: int64): int64 {...}{.magic: "AddU", noSideEffect.}

Treats x and y as unsigned and adds them.

The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.

  ソース 編集
proc `-%`(x, y: IntMax32): IntMax32 {...}{.magic: "SubU", noSideEffect.}
  ソース 編集
proc `-%`(x, y: int64): int64 {...}{.magic: "SubU", noSideEffect.}

Treats x and y as unsigned and subtracts them.

The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.

  ソース 編集
proc `*%`(x, y: IntMax32): IntMax32 {...}{.magic: "MulU", noSideEffect.}
  ソース 編集
proc `*%`(x, y: int64): int64 {...}{.magic: "MulU", noSideEffect.}

Treats x and y as unsigned and multiplies them.

The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.

  ソース 編集
proc `/%`(x, y: IntMax32): IntMax32 {...}{.magic: "DivU", noSideEffect.}
  ソース 編集
proc `/%`(x, y: int64): int64 {...}{.magic: "DivU", noSideEffect.}

Treats x and y as unsigned and divides them.

The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.

  ソース 編集
proc `%%`(x, y: IntMax32): IntMax32 {...}{.magic: "ModU", noSideEffect.}
  ソース 編集
proc `%%`(x, y: int64): int64 {...}{.magic: "ModU", noSideEffect.}

Treats x and y as unsigned and compute the modulo of x and y.

The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible.

  ソース 編集
proc `<=%`(x, y: IntMax32): bool {...}{.magic: "LeU", noSideEffect.}
  ソース 編集
proc `<=%`(x, y: int64): bool {...}{.magic: "LeU64", noSideEffect.}
Treats x and y as unsigned and compares them. Returns true if unsigned(x) <= unsigned(y).   ソース 編集
proc `<%`(x, y: IntMax32): bool {...}{.magic: "LtU", noSideEffect.}
  ソース 編集
proc `<%`(x, y: int64): bool {...}{.magic: "LtU64", noSideEffect.}
Treats x and y as unsigned and compares them. Returns true if unsigned(x) < unsigned(y).   ソース 編集
proc `not`[T: SomeUnsignedInt](x: T): T {...}{.magic: "BitnotI", noSideEffect.}
Computes the bitwise complement of the integer x.   ソース 編集
proc `shr`[T: SomeUnsignedInt](x: T; y: SomeInteger): T {...}{.magic: "ShrI", noSideEffect.}
Computes the shift right operation of x and y.   ソース 編集
proc `shl`[T: SomeUnsignedInt](x: T; y: SomeInteger): T {...}{.magic: "ShlI", noSideEffect.}
Computes the shift left operation of x and y.   ソース 編集
proc `and`[T: SomeUnsignedInt](x, y: T): T {...}{.magic: "BitandI", noSideEffect.}
Computes the bitwise and of numbers x and y.   ソース 編集
proc `or`[T: SomeUnsignedInt](x, y: T): T {...}{.magic: "BitorI", noSideEffect.}
Computes the bitwise or of numbers x and y.   ソース 編集
proc `xor`[T: SomeUnsignedInt](x, y: T): T {...}{.magic: "BitxorI", noSideEffect.}
Computes the bitwise xor of numbers x and y.   ソース 編集
proc `==`[T: SomeUnsignedInt](x, y: T): bool {...}{.magic: "EqI", noSideEffect.}
Compares two unsigned integers for equality.   ソース 編集
proc `+`[T: SomeUnsignedInt](x, y: T): T {...}{.magic: "AddU", noSideEffect.}
Binary + operator for unsigned integers.   ソース 編集
proc `-`[T: SomeUnsignedInt](x, y: T): T {...}{.magic: "SubU", noSideEffect.}
Binary - operator for unsigned integers.   ソース 編集
proc `*`[T: SomeUnsignedInt](x, y: T): T {...}{.magic: "MulU", noSideEffect.}
Binary * operator for unsigned integers.   ソース 編集
proc `div`[T: SomeUnsignedInt](x, y: T): T {...}{.magic: "DivU", noSideEffect.}
Computes the integer division for unsigned integers. This is roughly the same as trunc(x/y).   ソース 編集
proc `mod`[T: SomeUnsignedInt](x, y: T): T {...}{.magic: "ModU", noSideEffect.}
Computes the integer modulo operation (remainder) for unsigned integers. This is the same as x - (x div y) * y.   ソース 編集
proc `<=`[T: SomeUnsignedInt](x, y: T): bool {...}{.magic: "LeU", noSideEffect.}
Returns true if x <= y.   ソース 編集
proc `<`[T: SomeUnsignedInt](x, y: T): bool {...}{.magic: "LtU", noSideEffect.}
Returns true if unsigned(x) < unsigned(y).   ソース 編集
proc `+`(x: float32): float32 {...}{.magic: "UnaryPlusF64", noSideEffect.}
  ソース 編集
proc `-`(x: float32): float32 {...}{.magic: "UnaryMinusF64", noSideEffect.}
  ソース 編集
proc `+`(x, y: float32): float32 {...}{.magic: "AddF64", noSideEffect.}
  ソース 編集
proc `-`(x, y: float32): float32 {...}{.magic: "SubF64", noSideEffect.}
  ソース 編集
proc `*`(x, y: float32): float32 {...}{.magic: "MulF64", noSideEffect.}
  ソース 編集
proc `/`(x, y: float32): float32 {...}{.magic: "DivF64", noSideEffect.}
  ソース 編集
proc `+`(x: float): float {...}{.magic: "UnaryPlusF64", noSideEffect.}
  ソース 編集
proc `-`(x: float): float {...}{.magic: "UnaryMinusF64", noSideEffect.}
  ソース 編集
proc `+`(x, y: float): float {...}{.magic: "AddF64", noSideEffect.}
  ソース 編集
proc `-`(x, y: float): float {...}{.magic: "SubF64", noSideEffect.}
  ソース 編集
proc `*`(x, y: float): float {...}{.magic: "MulF64", noSideEffect.}
  ソース 編集
proc `/`(x, y: float): float {...}{.magic: "DivF64", noSideEffect.}
  ソース 編集
proc `==`(x, y: float32): bool {...}{.magic: "EqF64", noSideEffect.}
  ソース 編集
proc `<=`(x, y: float32): bool {...}{.magic: "LeF64", noSideEffect.}
  ソース 編集
proc `<`(x, y: float32): bool {...}{.magic: "LtF64", noSideEffect.}
  ソース 編集
proc `==`(x, y: float): bool {...}{.magic: "EqF64", noSideEffect.}
  ソース 編集
proc `<=`(x, y: float): bool {...}{.magic: "LeF64", noSideEffect.}
  ソース 編集
proc `<`(x, y: float): bool {...}{.magic: "LtF64", noSideEffect.}
  ソース 編集
proc `*`[T](x, y: set[T]): set[T] {...}{.magic: "MulSet", noSideEffect.}
This operator computes the intersection of two sets.
let
  a = {1, 2, 3}
  b = {2, 3, 4}
echo a * b # => {2, 3}
  ソース 編集
proc `+`[T](x, y: set[T]): set[T] {...}{.magic: "PlusSet", noSideEffect.}
This operator computes the union of two sets.
let
  a = {1, 2, 3}
  b = {2, 3, 4}
echo a + b # => {1, 2, 3, 4}
  ソース 編集
proc `-`[T](x, y: set[T]): set[T] {...}{.magic: "MinusSet", noSideEffect.}
This operator computes the difference of two sets.
let
  a = {1, 2, 3}
  b = {2, 3, 4}
echo a - b # => {1}
  ソース 編集
proc contains[T](x: set[T]; y: T): bool {...}{.magic: "InSet", noSideEffect.}

One should overload this proc if one wants to overload the in operator.

The parameters are in reverse order! a in b is a template for contains(b, a). This is because the unification algorithm that Nim uses for overload resolution works from left to right. But for the in operator that would be the wrong direction for this piece of code:

var s: set[range['a'..'z']] = {'a'..'c'}
assert s.contains('c')
assert 'b' in s

If in had been declared as [T](elem: T, s: set[T]) then T would have been bound to char. But s is not compatible to type set[char]! The solution is to bind T to range['a'..'z']. This is achieved by reversing the parameters for contains; in then passes its arguments in reverse order.

  ソース 編集
proc contains[U, V, W](s: HSlice[U, V]; value: W): bool {...}{.noSideEffect, inline.}
Checks if value is within the range of s; returns true if value >= s.a and value <= s.b
assert((1..3).contains(1) == true)
assert((1..3).contains(2) == true)
assert((1..3).contains(4) == false)
  ソース 編集
proc `is`[T, S](x: T; y: S): bool {...}{.magic: "Is", noSideEffect.}

Checks if T is of the same type as S.

For a negated version, use isnot.

assert 42 is int
assert @[1, 2] is seq

proc test[T](a: T): int =
  when (T is int):
    return a
  else:
    return 0

assert(test[int](3) == 3)
assert(test[string]("xyz") == 0)
  ソース 編集
proc new[T](a: var ref T) {...}{.magic: "New", noSideEffect.}
Creates a new object of type T and returns a safe (traced) reference to it in a.   ソース 編集
proc new(t: typedesc): auto

Creates a new object of type T and returns a safe (traced) reference to it as result value.

When T is a ref type then the resulting type will be T, otherwise it will be ref T.

  ソース 編集
proc `of`[T, S](x: typedesc[T]; y: typedesc[S]): bool {...}{.magic: "Of", noSideEffect.}
  ソース 編集
proc `of`[T, S](x: T; y: typedesc[S]): bool {...}{.magic: "Of", noSideEffect.}
  ソース 編集
proc `of`[T, S](x: T; y: S): bool {...}{.magic: "Of", noSideEffect.}
Checks if x has a type of y.
assert(FloatingPointError of Exception)
assert(DivByZeroError of Exception)
  ソース 編集
proc cmp[T](x, y: T): int {...}{.procvar.}

Generic compare proc.

Returns:

  • a value less than zero, if x < y
  • a value greater than zero, if x > y
  • zero, if x == y

This is useful for writing generic algorithms without performance loss. This generic implementation uses the == and < operators.

import algorithm
echo sorted(@[4, 2, 6, 5, 8, 7], cmp[int])
  ソース 編集
proc `@`[IDX, T](a: sink array[IDX, T]): seq[T] {...}{.magic: "ArrToSeq", noSideEffect.}

Turns an array into a sequence.

This most often useful for constructing sequences with the array constructor: @[1, 2, 3] has the type seq[int], while [1, 2, 3] has the type array[0..2, int].

let
  a = [1, 3, 5]
  b = "foo"

echo @a # => @[1, 3, 5]
echo @b # => @['f', 'o', 'o']
  ソース 編集
proc default(T: typedesc): T:type {...}{.magic: "Default", noSideEffect.}
returns the default value of the type T.   ソース 編集
proc setLen[T](s: var seq[T]; newlen: Natural) {...}{.magic: "SetLengthSeq", noSideEffect.}

Sets the length of seq s to newlen. T may be any sequence type.

If the current length is greater than the new length, s will be truncated.

var x = @[10, 20]
x.setLen(5)
x[4] = 50
assert x == @[10, 20, 0, 0, 50]
x.setLen(1)
assert x == @[10]
  ソース 編集
proc setLen(s: var string; newlen: Natural) {...}{.magic: "SetLengthStr", noSideEffect.}

Sets the length of string s to newlen.

If the current length is greater than the new length, s will be truncated.

var myS = "Nim is great!!"
myS.setLen(3) # myS <- "Nim"
echo myS, " is fantastic!!"
  ソース 編集
proc newString(len: Natural): string {...}{.magic: "NewString", importc: "mnewString",
                                   noSideEffect.}

Returns a new string of length len but with uninitialized content. One needs to fill the string character after character with the index operator s[i].

This procedure exists only for optimization purposes; the same effect can be achieved with the & operator or with add.

  ソース 編集
proc newStringOfCap(cap: Natural): string {...}{.magic: "NewStringOfCap",
                                        importc: "rawNewString", noSideEffect.}

Returns a new string of length 0 but with capacity cap.

This procedure exists only for optimization purposes; the same effect can be achieved with the & operator or with add.

  ソース 編集
proc `&`(x: string; y: char): string {...}{.magic: "ConStrStr", noSideEffect, merge.}
Concatenates x with y.
assert("ab" & 'c' == "abc")
  ソース 編集
proc `&`(x, y: char): string {...}{.magic: "ConStrStr", noSideEffect, merge.}
Concatenates characters x and y into a string.
assert('a' & 'b' == "ab")
  ソース 編集
proc `&`(x, y: string): string {...}{.magic: "ConStrStr", noSideEffect, merge.}
Concatenates strings x and y.
assert("ab" & "cd" == "abcd")
  ソース 編集
proc `&`(x: char; y: string): string {...}{.magic: "ConStrStr", noSideEffect, merge.}
Concatenates x with y.
assert('a' & "bc" == "abc")
  ソース 編集
proc add(x: var string; y: char) {...}{.magic: "AppendStrCh", noSideEffect.}
Appends y to x in place.
var tmp = ""
tmp.add('a')
tmp.add('b')
assert(tmp == "ab")
  ソース 編集
proc add(x: var string; y: string) {...}{.magic: "AppendStrStr", noSideEffect.}
Concatenates x and y in place.
var tmp = ""
tmp.add("ab")
tmp.add("cd")
assert(tmp == "abcd")
  ソース 編集
proc compileOption(option: string): bool {...}{.magic: "CompileOption", noSideEffect.}
Can be used to determine an on|off compile-time option. 用例:
when compileOption("floatchecks"):
  echo "compiled with floating point NaN and Inf checks"
  ソース 編集
proc compileOption(option, arg: string): bool {...}{.magic: "CompileOptionArg", noSideEffect.}
Can be used to determine an enum compile-time option. 用例:
when compileOption("opt", "size") and compileOption("gc", "boehm"):
  echo "compiled with optimization for size and uses Boehm's GC"
  ソース 編集
proc quit(errorcode: int = QuitSuccess) {...}{.magic: "Exit", noreturn.}

Stops the program immediately with an exit code.

Before stopping the program the "quit procedures" are called in the opposite order they were added with addQuitProc. quit never returns and ignores any exception that may have been raised by the quit procedures. It does not call the garbage collector to free all the memory, unless a quit procedure calls GC_fullCollect.

The proc quit(QuitSuccess) is called implicitly when your nim program finishes without incident for platforms where this is the expected behavior. A raised unhandled exception is equivalent to calling quit(QuitFailure).

Note that this is a runtime call and using quit inside a macro won't have any compile time effect. If you need to stop the compiler inside a macro, use the error or fatal pragmas.

  ソース 編集
proc add[T](x: var seq[T]; y: T) {...}{.magic: "AppendSeqElem", noSideEffect.}

Generic proc for adding a data item y to a container x.

For containers that have an order, add means append. New generic containers should also call their adding proc add for consistency. Generic code becomes much easier to write if the Nim naming scheme is respected.

  ソース 編集
proc add[T](x: var seq[T]; y: openArray[T]) {...}{.noSideEffect.}

Generic proc for adding a container y to a container x.

For containers that have an order, add means append. New generic containers should also call their adding proc add for consistency. Generic code becomes much easier to write if the Nim naming scheme is respected.

関連:

var s: seq[string] = @["test2","test2"]
s.add("test") # s <- @[test2, test2, test]
  ソース 編集
proc del[T](x: var seq[T]; i: Natural) {...}{.noSideEffect.}

Deletes the item at index i by putting x[high(x)] into position i.

This is an O(1) operation.

関連:

  • delete for preserving the order
var i = @[1, 2, 3, 4, 5]
i.del(2) # => @[1, 2, 5, 4]
  ソース 編集
proc delete[T](x: var seq[T]; i: Natural) {...}{.noSideEffect.}

Deletes the item at index i by moving all x[i+1..] items by one position.

This is an O(n) operation.

関連:

  • del for O(1) operation
var i = @[1, 2, 3, 4, 5]
i.delete(2) # => @[1, 2, 4, 5]
  ソース 編集
proc insert[T](x: var seq[T]; item: T; i = 0.Natural) {...}{.noSideEffect.}
Inserts item into x at position i.
var i = @[1, 3, 5]
i.insert(99, 0) # i <- @[99, 1, 3, 5]
  ソース 編集
proc repr[T](x: T): string {...}{.magic: "Repr", noSideEffect.}

Takes any Nim variable and returns its string representation.

It works even for complex data graphs with cycles. This is a great debugging tool.

var s: seq[string] = @["test2", "test2"]
var i = @[1, 2, 3, 4, 5]
echo repr(s) # => 0x1055eb050[0x1055ec050"test2", 0x1055ec078"test2"]
echo repr(i) # => 0x1055ed050[1, 2, 3, 4, 5]
  ソース 編集
proc toFloat(i: int): float {...}{.noSideEffect, inline, raises: [], tags: [].}

Converts an integer i into a float.

If the conversion fails, ValueError is raised. However, on most platforms the conversion cannot fail.

let
  a = 2
  b = 3.7

echo a.toFloat + b # => 5.7
  ソース 編集
proc toBiggestFloat(i: BiggestInt): BiggestFloat {...}{.noSideEffect, inline, raises: [],
    tags: [].}
Same as toFloat but for BiggestInt to BiggestFloat.   Source Edit
proc toInt(f: float): int {...}{.noSideEffect, raises: [], tags: [].}

Converts a floating point number f into an int.

Conversion rounds f half away from 0, see Round half away from zero.

Note that some floating point numbers (e.g. infinity or even 1e19) cannot be accurately converted.

doAssert toInt(0.49) == 0
doAssert toInt(0.5) == 1
doAssert toInt(-0.5) == -1 # rounding is symmetrical
  ソース 編集
proc toBiggestInt(f: BiggestFloat): BiggestInt {...}{.noSideEffect, raises: [], tags: [].}
Same as toInt but for BiggestFloat to BiggestInt.   Source Edit
proc addQuitProc(quitProc: proc () {...}{.noconv.}) {...}{.importc: "atexit",
    header: "<stdlib.h>".}

Adds/registers a quit procedure.

Each call to addQuitProc registers another quit procedure. Up to 30 procedures can be registered. They are executed on a last-in, first-out basis (that is, the last function registered is the first to be executed). addQuitProc raises an EOutOfIndex exception if quitProc cannot be registered.

  ソース 編集
proc createU(T: typedesc; size = 1.Positive): ptr T:type {...}{.inline, gcsafe, locks: 0,
    raises: [].}

Allocates a new memory block with at least T.sizeof * size bytes.

The block has to be freed with resize(block, 0) or dealloc(block). The block is not initialized, so reading from it before writing to it is undefined behaviour!

The allocated memory belongs to its allocating thread! Use createSharedU to allocate from a shared heap.

関連:

  ソース 編集
proc create(T: typedesc; size = 1.Positive): ptr T:type {...}{.inline, gcsafe, locks: 0,
    raises: [].}

Allocates a new memory block with at least T.sizeof * size bytes.

The block has to be freed with resize(block, 0) or dealloc(block). The block is initialized with all bytes containing zero, so it is somewhat safer than createU.

The allocated memory belongs to its allocating thread! Use createShared to allocate from a shared heap.

  ソース 編集
proc resize[T](p: ptr T; newSize: Natural): ptr T {...}{.inline, gcsafe, locks: 0, raises: [].}

Grows or shrinks a given memory block.

If p is nil then a new memory block is returned. In either way the block has at least T.sizeof * newSize bytes. If newSize == 0 and p is not nil resize calls dealloc(p). In other cases the block has to be freed with free.

The allocated memory belongs to its allocating thread! Use resizeShared to reallocate from a shared heap.

  ソース 編集
proc createSharedU(T: typedesc; size = 1.Positive): ptr T:type {...}{.inline, gcsafe, locks: 0,
    raises: [].}

Allocates a new memory block on the shared heap with at least T.sizeof * size bytes.

The block has to be freed with resizeShared(block, 0) or freeShared(block).

The block is not initialized, so reading from it before writing to it is undefined behaviour!

関連:

  ソース 編集
proc createShared(T: typedesc; size = 1.Positive): ptr T:type {...}{.inline.}

Allocates a new memory block on the shared heap with at least T.sizeof * size bytes.

The block has to be freed with resizeShared(block, 0) or freeShared(block).

The block is initialized with all bytes containing zero, so it is somewhat safer than createSharedU.

  ソース 編集
proc resizeShared[T](p: ptr T; newSize: Natural): ptr T {...}{.inline, raises: [].}

Grows or shrinks a given memory block on the heap.

If p is nil then a new memory block is returned. In either way the block has at least T.sizeof * newSize bytes. If newSize == 0 and p is not nil resizeShared calls freeShared(p). In other cases the block has to be freed with freeShared.

  ソース 編集
proc freeShared[T](p: ptr T) {...}{.inline, gcsafe, locks: 0, raises: [].}

Frees the memory allocated with createShared, createSharedU or resizeShared.

This procedure is dangerous! If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted.

  ソース 編集
proc swap[T](a, b: var T) {...}{.magic: "Swap", noSideEffect.}

Swaps the values a and b.

This is often more efficient than tmp = a; a = b; b = tmp. Particularly useful for sorting algorithms.

var
  a = 5
  b = 9

swap(a, b)

assert a == 9
assert b == 5
  ソース 編集
proc getRefcount[T](x: ref T): int {...}{.importc: "getRefcount", noSideEffect, deprecated: "the refcount was never reliable, the GC does not use traditional refcounting".}
Deprecated: the refcount was never reliable, the GC does not use traditional refcounting
  ソース 編集
proc getRefcount(x: string): int {...}{.importc: "getRefcount", noSideEffect, deprecated: "the refcount was never reliable, the GC does not use traditional refcounting".}
Deprecated: the refcount was never reliable, the GC does not use traditional refcounting
  ソース 編集
proc getRefcount[T](x: seq[T]): int {...}{.importc: "getRefcount", noSideEffect, deprecated: "the refcount was never reliable, the GC does not use traditional refcounting".}
Deprecated: the refcount was never reliable, the GC does not use traditional refcounting

Retrieves the reference count of an heap-allocated object. The value is implementation-dependent.

  ソース 編集
proc `|`(a, b: typedesc): typedesc
  ソース 編集
proc min(x, y: int): int {...}{.magic: "MinI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc min(x, y: int8): int8 {...}{.magic: "MinI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc min(x, y: int16): int16 {...}{.magic: "MinI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc min(x, y: int32): int32 {...}{.magic: "MinI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc min(x, y: int64): int64 {...}{.magic: "MinI", noSideEffect, raises: [], tags: [].}
The minimum value of two integers.   ソース 編集
proc min[T](x: openArray[T]): T
The minimum value of x. T needs to have a < operator.   ソース 編集
proc max(x, y: int): int {...}{.magic: "MaxI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc max(x, y: int8): int8 {...}{.magic: "MaxI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc max(x, y: int16): int16 {...}{.magic: "MaxI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc max(x, y: int32): int32 {...}{.magic: "MaxI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc max(x, y: int64): int64 {...}{.magic: "MaxI", noSideEffect, raises: [], tags: [].}
The maximum value of two integers.   ソース 編集
proc max[T](x: openArray[T]): T
The maximum value of x. T needs to have a < operator.   ソース 編集
proc abs(x: float64): float64 {...}{.noSideEffect, inline, raises: [], tags: [].}
  ソース 編集
proc abs(x: float32): float32 {...}{.noSideEffect, inline, raises: [], tags: [].}
  ソース 編集
proc min(x, y: float32): float32 {...}{.noSideEffect, inline, raises: [], tags: [].}
  ソース 編集
proc min(x, y: float64): float64 {...}{.noSideEffect, inline, raises: [], tags: [].}
  ソース 編集
proc max(x, y: float32): float32 {...}{.noSideEffect, inline, raises: [], tags: [].}
  ソース 編集
proc max(x, y: float64): float64 {...}{.noSideEffect, inline, raises: [], tags: [].}
  ソース 編集
proc min[T: not SomeFloat](x, y: T): T {...}{.inline.}
  ソース 編集
proc max[T: not SomeFloat](x, y: T): T {...}{.inline.}
  ソース 編集
proc high(T: typedesc[SomeFloat]): T:type
  ソース 編集
proc low(T: typedesc[SomeFloat]): T:type
  ソース 編集
proc clamp[T](x, a, b: T): T
Limits the value x within the interval [a, b].
assert((1.4).clamp(0.0, 1.0) == 1.0)
assert((0.5).clamp(0.0, 1.0) == 0.5)
  ソース 編集
proc len[U: Ordinal; V: Ordinal](x: HSlice[U, V]): int {...}{.noSideEffect, inline.}
Length of ordinal slice. When x.b < x.a returns zero length.
assert((0..5).len == 6)
assert((5..2).len == 0)
  ソース 編集
proc isNil[T](x: seq[T]): bool {...}{.noSideEffect, magic: "IsNil", error.}

Requires --nilseqs:on since 0.19.

Seqs are no longer nil by default, but set and empty. Check for zero length instead.

関連:

  ソース 編集
proc isNil[T](x: ref T): bool {...}{.noSideEffect, magic: "IsNil".}
  ソース 編集
proc isNil(x: string): bool {...}{.noSideEffect, magic: "IsNil", error.}

Requires --nilseqs:on.

関連:

  ソース 編集
proc isNil[T](x: ptr T): bool {...}{.noSideEffect, magic: "IsNil".}
  ソース 編集
proc isNil(x: pointer): bool {...}{.noSideEffect, magic: "IsNil".}
  ソース 編集
proc isNil(x: cstring): bool {...}{.noSideEffect, magic: "IsNil".}
  ソース 編集
proc isNil[T: proc](x: T): bool {...}{.noSideEffect, magic: "IsNil".}
Fast check whether x is nil. This is sometimes more efficient than == nil.   ソース 編集
proc `==`[I, T](x, y: array[I, T]): bool
  ソース 編集
proc `==`[T](x, y: openArray[T]): bool
  ソース 編集
proc `@`[T](a: openArray[T]): seq[T]

Turns an openArray into a sequence.

This is not as efficient as turning a fixed length array into a sequence as it always copies every element of a.

  ソース 編集
proc `&`[T](x, y: seq[T]): seq[T] {...}{.noSideEffect.}

Concatenates two sequences.

Requires copying of the sequences.

関連:

assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6])
  ソース 編集
proc `&`[T](x: seq[T]; y: T): seq[T] {...}{.noSideEffect.}

Appends element y to the end of the sequence.

Requires copying of the sequence.

関連:

assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4])
  ソース 編集
proc `&`[T](x: T; y: seq[T]): seq[T] {...}{.noSideEffect.}

Prepends the element x to the beginning of the sequence.

Requires copying of the sequence.

assert(1 & @[2, 3, 4] == @[1, 2, 3, 4])
  ソース 編集
proc `==`[T](x, y: seq[T]): bool {...}{.noSideEffect.}
Generic equals operator for sequences: relies on a equals operator for the element type T.   ソース 編集
proc astToStr[T](x: T): string {...}{.magic: "AstToStr", noSideEffect.}
Converts the AST of x into a string representation. This is very useful for debugging.   ソース 編集
proc instantiationInfo(index = -1; fullPaths = false): tuple[filename: string, line: int,
    column: int] {...}{.magic: "InstantiationInfo", noSideEffect.}

Provides access to the compiler's instantiation stack line information of a template.

While similar to the caller info of other languages, it is determined at compile time.

This proc is mostly useful for meta programming (eg. assert template) to retrieve information about the current filename and line number. 用例:

import strutils

template testException(exception, code: untyped): typed =
  try:
    let pos = instantiationInfo()
    discard(code)
    echo "Test failure at $1:$2 with '$3'" % [pos.filename,
      $pos.line, astToStr(code)]
    assert false, "A test expecting failure succeeded?"
  except exception:
    discard

proc tester(pos: int): int =
  let
    a = @[1, 2, 3]
  result = a[pos]

when isMainModule:
  testException(IndexError, tester(30))
  testException(IndexError, tester(1))
  # --> Test failure at example.nim:20 with 'tester(1)'
  ソース 編集
proc compiles(x: untyped): bool {...}{.magic: "Compiles", noSideEffect, compileTime,
                              raises: [], tags: [].}
Special compile-time procedure that checks whether x can be compiled without any semantic error. This can be used to check whether a type supports some operation:
when compiles(3 + 4):
  echo "'+' for integers is available"
  ソース 編集
proc atomicInc(memLoc: var int; x: int = 1): int {...}{.inline, discardable, gcsafe, locks: 0,
    raises: [], tags: [].}
Atomic increment of memLoc. Returns the value after the operation.   ソース 編集
proc atomicDec(memLoc: var int; x: int = 1): int {...}{.inline, discardable, gcsafe, locks: 0,
    raises: [], tags: [].}
Atomic decrement of memLoc. Returns the value after the operation.   ソース 編集
proc addAndFetch(p: ptr int; val: int): int {...}{.inline, raises: [], tags: [].}
  ソース 編集
proc cas[T: bool | int | ptr](p: ptr T; oldValue, newValue: T): bool {...}{.
    importc: "__sync_bool_compare_and_swap", nodecl.}
  ソース 編集
proc cpuRelax() {...}{.inline, raises: [], tags: [].}
  ソース 編集
proc find[T, S](a: T; item: S): int {...}{.inline.}
Returns the first index of item in a or -1 if not found. This requires appropriate items and == operations to work.   Source Edit
proc contains[T](a: openArray[T]; item: T): bool {...}{.inline.}

Returns true if item is in a or false if not found. This is a shortcut for find(a, item) >= 0.

This allows the in operator: a.contains(item) is the same as item in a.

var a = @[1, 3, 5]
assert a.contains(5)
assert 3 in a
assert 99 notin a
  ソース 編集
proc pop[T](s: var seq[T]): T {...}{.inline, noSideEffect.}
Returns the last item of s and decreases s.len by one. This treats s as a stack and implements the common pop operation.

用例:

var a = @[1, 3, 5, 7]
let b = pop(a)
assert b == 7
assert a == @[1, 3, 5]
  ソース 編集
proc `==`[T: tuple |
    object](x, y: T): bool
Generic == operator for tuples that is lifted from the components. of x and y.   ソース 編集
proc `<=`[T: tuple](x, y: T): bool
Generic lexicographic <= operator for tuples that is lifted from the components of x and y. This implementation uses cmp.   Source Edit
proc `<`[T: tuple](x, y: T): bool
Generic lexicographic < operator for tuples that is lifted from the components of x and y. This implementation uses cmp.   Source Edit
proc GC_ref[T](x: ref T) {...}{.magic: "GCref", gcsafe, locks: 0.}
  ソース 編集
proc GC_ref[T](x: seq[T]) {...}{.magic: "GCref", gcsafe, locks: 0.}
  ソース 編集
proc GC_ref(x: string) {...}{.magic: "GCref", gcsafe, locks: 0.}
Marks the object x as referenced, so that it will not be freed until it is unmarked via GC_unref. If called n-times for the same object x, n calls to GC_unref are needed to unmark x.   Source Edit
proc GC_unref[T](x: ref T) {...}{.magic: "GCunref", gcsafe, locks: 0.}
  ソース 編集
proc GC_unref[T](x: seq[T]) {...}{.magic: "GCunref", gcsafe, locks: 0.}
  ソース 編集
proc GC_unref(x: string) {...}{.magic: "GCunref", gcsafe, locks: 0.}
See the documentation of GC_ref.   ソース 編集
proc add(x: var string; y: cstring) {...}{.raises: [], tags: [].}
  ソース 編集
proc echo(x: varargs[typed, `$`]) {...}{.magic: "Echo", tags: [WriteIOEffect], gcsafe,
                                locks: 0, sideEffect.}

Writes and flushes the parameters to the standard output.

Special built-in that takes a variable number of arguments. Each argument is converted to a string via $, so it works for user-defined types that have an overloaded $ operator. It is roughly equivalent to writeLine(stdout, x); flushFile(stdout), but available for the JavaScript target too.

Unlike other IO operations this is guaranteed to be thread-safe as echo is very often used for debugging convenience. If you want to use echo inside a proc without side effects you can use debugEcho instead.

  ソース 編集
proc debugEcho(x: varargs[typed, `$`]) {...}{.magic: "Echo", noSideEffect, tags: [],
                                     raises: [].}
Same as echo, but as a special semantic rule, debugEcho pretends to be free of side effects, so that it can be used for debugging routines marked as noSideEffect.   ソース 編集
proc getTypeInfo[T](x: T): pointer {...}{.magic: "GetTypeInfo", gcsafe, locks: 0.}

Get type information for x.

Ordinary code should not use this, but the typeinfo module instead.

  ソース 編集
proc abs(x: int): int {...}{.magic: "AbsI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc abs(x: int8): int8 {...}{.magic: "AbsI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc abs(x: int16): int16 {...}{.magic: "AbsI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc abs(x: int32): int32 {...}{.magic: "AbsI", noSideEffect, raises: [], tags: [].}
  ソース 編集
proc abs(x: int64): int64 {...}{.magic: "AbsI", noSideEffect, raises: [], tags: [].}

Returns the absolute value of x.

If x is low(x) (that is -MININT for its type), an overflow exception is thrown (if overflow checking is turned on).

  ソース 編集
proc zeroMem(p: pointer; size: Natural) {...}{.inline, noSideEffect, tags: [], locks: 0,
                                     raises: [].}

Overwrites the contents of the memory at p with the value 0.

Exactly size bytes will be overwritten. Like any procedure dealing with raw memory this is unsafe.

  ソース 編集
proc copyMem(dest, source: pointer; size: Natural) {...}{.inline, gcsafe, locks: 0, tags: [],
    locks: 0, raises: [].}
Copies the contents from the memory at source to the memory at dest. Exactly size bytes will be copied. The memory regions may not overlap. Like any procedure dealing with raw memory this is unsafe.   Source Edit
proc moveMem(dest, source: pointer; size: Natural) {...}{.inline, gcsafe, locks: 0, tags: [],
    locks: 0, raises: [].}

Copies the contents from the memory at source to the memory at dest.

Exactly size bytes will be copied. The memory regions may overlap, moveMem handles this case appropriately and is thus somewhat more safe than copyMem. Like any procedure dealing with raw memory this is still unsafe, though.

  ソース 編集
proc equalMem(a, b: pointer; size: Natural): bool {...}{.inline, noSideEffect, tags: [],
    locks: 0, raises: [].}

Compares the memory blocks a and b. size bytes will be compared.

If the blocks are equal, true is returned, false otherwise. Like any procedure dealing with raw memory this is unsafe.

  ソース 編集
proc cmp(x, y: string): int {...}{.noSideEffect, procvar, raises: [], tags: [].}

Compare proc for strings. More efficient than the generic version.

Note: The precise result values depend on the used C runtime library and can differ between operating systems!

  ソース 編集
proc cstringArrayToSeq(a: cstringArray; len: Natural): seq[string] {...}{.raises: [],
    tags: [].}
Converts a cstringArray to a seq[string]. a is supposed to be of length len.   Source Edit
proc cstringArrayToSeq(a: cstringArray): seq[string] {...}{.raises: [], tags: [].}
Converts a cstringArray to a seq[string]. a is supposed to be terminated by nil.   Source Edit
proc allocCStringArray(a: openArray[string]): cstringArray {...}{.raises: [], tags: [].}
Creates a NULL terminated cstringArray from a. The result has to be freed with deallocCStringArray after it's not needed anymore.   ソース 編集
proc deallocCStringArray(a: cstringArray) {...}{.raises: [], tags: [].}
Frees a NULL terminated cstringArray.   ソース 編集
proc setControlCHook(hook: proc () {...}{.noconv.}) {...}{.raises: [Exception],
    tags: [RootEffect].}
Allows you to override the behaviour of your application when CTRL+C is pressed. Only one such hook is supported.   ソース 編集
proc unsetControlCHook() {...}{.raises: [Exception], tags: [RootEffect, WriteIOEffect].}
Reverts a call to setControlCHook.   ソース 編集
proc writeStackTrace() {...}{.tags: [], gcsafe, raises: [Exception].}
Writes the current stack trace to stderr. This is only works for debug builds. Since it's usually used for debugging, this is proclaimed to have no IO effect!  ソース 編集
proc getStackTrace(): string {...}{.gcsafe, raises: [], tags: [].}
Gets the current stack trace. This only works for debug builds.   ソース 編集
proc getStackTrace(e: ref Exception): string {...}{.gcsafe, raises: [], tags: [].}
Gets the stack trace associated with e, which is the stack that lead to the raise statement. This only works for debug builds.   ソース 編集
proc getFrameState(): FrameState {...}{.compilerproc, inline, raises: [], tags: [].}
  ソース 編集
proc setFrameState(state: FrameState) {...}{.compilerproc, inline, raises: [], tags: [].}
  ソース 編集
proc getFrame(): PFrame {...}{.compilerproc, inline, raises: [], tags: [].}
  ソース 編集
proc setFrame(s: PFrame) {...}{.compilerproc, inline, raises: [], tags: [].}
  ソース 編集
proc getGcFrame(): GcFrame {...}{.compilerproc, inline, raises: [], tags: [].}
  ソース 編集
proc popGcFrame() {...}{.compilerproc, inline, raises: [], tags: [].}
  ソース 編集
proc setGcFrame(s: GcFrame) {...}{.compilerproc, inline, raises: [], tags: [].}
  ソース 編集
proc pushGcFrame(s: GcFrame) {...}{.compilerproc, inline, raises: [], tags: [].}
  ソース 編集
proc stackTraceAvailable(): bool {...}{.raises: [], tags: [].}
  ソース 編集
proc getStackTraceEntries(e: ref Exception): seq[StackTraceEntry] {...}{.raises: [],
    tags: [].}
Returns the attached stack trace to the exception e as a seq. This is not yet available for the JS backend.   ソース 編集
proc getStackTraceEntries(): seq[StackTraceEntry] {...}{.raises: [], tags: [].}
Returns the stack trace entries for the current stack trace. This is not yet available for the JS backend.   ソース 編集
proc iterToProc(iter: typed; envType: typedesc; procName: untyped) {...}{.magic: "Plugin",
    compileTime.}
  ソース 編集
proc alloc(size: Natural): pointer {...}{.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [].}

Allocates a new memory block with at least size bytes.

The block has to be freed with realloc(block, 0) or dealloc(block). The block is not initialized, so reading from it before writing to it is undefined behaviour!

The allocated memory belongs to its allocating thread! Use allocShared to allocate from a shared heap.

関連:

  ソース 編集
proc alloc0(size: Natural): pointer {...}{.noconv, gcsafe, tags: [], gcsafe, locks: 0,
                                  raises: [].}

Allocates a new memory block with at least size bytes.

The block has to be freed with realloc(block, 0) or dealloc(block). The block is initialized with all bytes containing zero, so it is somewhat safer than alloc.

The allocated memory belongs to its allocating thread! Use allocShared0 to allocate from a shared heap.

  ソース 編集
proc dealloc(p: pointer) {...}{.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [].}

Frees the memory allocated with alloc, alloc0 or realloc.

This procedure is dangerous! If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted.

The freed memory must belong to its allocating thread! Use deallocShared to deallocate from a shared heap.

  ソース 編集
proc realloc(p: pointer; newSize: Natural): pointer {...}{.noconv, gcsafe, tags: [], gcsafe,
    locks: 0, raises: [].}

Grows or shrinks a given memory block.

If p is nil then a new memory block is returned. In either way the block has at least newSize bytes. If newSize == 0 and p is not nil realloc calls dealloc(p). In other cases the block has to be freed with dealloc(block).

The allocated memory belongs to its allocating thread! Use reallocShared to reallocate from a shared heap.

  ソース 編集
proc getFreeMem(): int {...}{.gcsafe, raises: [], tags: [].}
Returns the number of bytes that are owned by the process, but do not hold any meaningful data.   ソース 編集
proc getTotalMem(): int {...}{.gcsafe, raises: [], tags: [].}
Returns the number of bytes that are owned by the process.   ソース 編集
proc getOccupiedMem(): int {...}{.gcsafe, raises: [], tags: [].}
Returns the number of bytes that are owned by the process and hold data.   ソース 編集
proc getMaxMem(): int {...}{.raises: [], tags: [].}
  ソース 編集
proc allocShared(size: Natural): pointer {...}{.noconv, gcsafe, gcsafe, locks: 0, raises: [],
                                       tags: [].}

Allocates a new memory block on the shared heap with at least size bytes.

The block has to be freed with reallocShared(block, 0) or deallocShared(block).

The block is not initialized, so reading from it before writing to it is undefined behaviour!

See also: allocShared0.

  ソース 編集
proc allocShared0(size: Natural): pointer {...}{.noconv, gcsafe, gcsafe, locks: 0, raises: [],
                                        tags: [].}

Allocates a new memory block on the shared heap with at least size bytes.

The block has to be freed with reallocShared(block, 0) or deallocShared(block).

The block is initialized with all bytes containing zero, so it is somewhat safer than allocShared.

  ソース 編集
proc deallocShared(p: pointer) {...}{.noconv, gcsafe, gcsafe, locks: 0, raises: [], tags: [].}

Frees the memory allocated with allocShared, allocShared0 or reallocShared.

This procedure is dangerous! If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted.

  ソース 編集
proc reallocShared(p: pointer; newSize: Natural): pointer {...}{.noconv, gcsafe, gcsafe,
    locks: 0, raises: [], tags: [].}

Grows or shrinks a given memory block on the heap.

If p is nil then a new memory block is returned. In either way the block has at least newSize bytes. If newSize == 0 and p is not nil reallocShared calls deallocShared(p). In other cases the block has to be freed with deallocShared.

  ソース 編集
proc protect(x: pointer): ForeignCell {...}{.raises: [], tags: [].}
  ソース 編集
proc dispose(x: ForeignCell) {...}{.raises: [], tags: [].}
  ソース 編集
proc isNotForeign(x: ForeignCell): bool {...}{.raises: [], tags: [].}
returns true if 'x' belongs to the calling thread. No deep copy has to be performed then.   ソース 編集
proc setupForeignThreadGc() {...}{.gcsafe, raises: [], tags: [].}

Call this if you registered a callback that will be run from a thread not under your control. This has a cheap thread-local guard, so the GC for this thread will only be initialized once per thread, no matter how often it is called.

This function is available only when --threads:on and --tlsEmulation:off switches are used

  ソース 編集
proc tearDownForeignThreadGc() {...}{.gcsafe, raises: [], tags: [].}

Call this to tear down the GC, previously initialized by setupForeignThreadGc. If GC has not been previously initialized, or has already been torn down, the call does nothing.

This function is available only when --threads:on and --tlsEmulation:off switches are used

  ソース 編集
proc nimGC_setStackBottom(theStackBottom: pointer) {...}{.compilerproc, noinline, gcsafe,
    locks: 0, raises: [], tags: [].}
Expands operating GC stack range to theStackBottom. Does nothing if current stack bottom is already lower than theStackBottom.   ソース 編集
proc deallocHeap(runFinalizers = true; allowGcAfterwards = true) {...}{.raises: [Exception],
    tags: [RootEffect].}
Frees the thread local heap. Runs every finalizer if runFinalizers is true. If allowGcAfterwards is true, a minimal amount of allocation happens to ensure the GC can continue to work after the call to deallocHeap.   ソース 編集
proc gcInvariant() {...}{.raises: [], tags: [].}
  ソース 編集
proc GC_disable() {...}{.gcsafe, inline, gcsafe, locks: 0, raises: [], tags: [].}

Disables the GC. If called n times, n calls to GC_enable are needed to reactivate the GC.

Note that in most circumstances one should only disable the mark and sweep phase with GC_disableMarkAndSweep.

  ソース 編集
proc GC_enable() {...}{.gcsafe, inline, gcsafe, locks: 0, raises: [AssertionError], tags: [].}
Enables the GC again.   ソース 編集
proc GC_enableMarkAndSweep() {...}{.gcsafe, gcsafe, locks: 0, raises: [], tags: [].}
  ソース 編集
proc GC_disableMarkAndSweep() {...}{.gcsafe, gcsafe, locks: 0, raises: [], tags: [].}
The current implementation uses a reference counting garbage collector with a seldomly run mark and sweep phase to free cycles. The mark and sweep phase may take a long time and is not needed if the application does not create cycles. Thus the mark and sweep phase can be deactivated and activated separately from the rest of the GC.   ソース 編集
proc GC_fullCollect() {...}{.gcsafe, gcsafe, locks: 0, raises: [Exception],
                      tags: [RootEffect].}
Forces a full garbage collection pass. Ordinary code does not need to call this (and should not).   ソース 編集
proc GC_getStatistics(): string {...}{.gcsafe, gcsafe, locks: 0, raises: [], tags: [].}
Returns an informative string about the GC's activity. This may be useful for tweaking.   ソース 編集
proc addInt(result: var string; x: int64) {...}{.raises: [], tags: [].}
Converts integer to its string representation and appends it to result.
var
  a = "123"
  b = 45
a.addInt(b) # a <- "12345"
  ソース 編集
proc add(result: var string; x: int64) {...}{.deprecated: "Deprecated since v0.20, use \'addInt\'",
                                   raises: [], tags: [].}
Deprecated: Deprecated since v0.20, use 'addInt'
  ソース 編集
proc addFloat(result: var string; x: float) {...}{.raises: [], tags: [].}
Converts float to its string representation and appends it to result.
var
  a = "123"
  b = 45.67
a.addFloat(b) # a <- "12345.67"
  ソース 編集
proc add(result: var string; x: float) {...}{.deprecated: "Deprecated since v0.20, use \'addFloat\'",
                                   raises: [], tags: [].}
Deprecated: Deprecated since v0.20, use 'addFloat'
  ソース 編集
proc `$`(x: uint64): string {...}{.noSideEffect, raises: [], tags: [].}
The stringify operator for an unsigned integer argument. Returns x converted to a decimal string.   ソース 編集
proc getCurrentException(): ref Exception {...}{.compilerproc, inline, gcsafe, locks: 0,
                                        raises: [], tags: [].}
Retrieves the current exception; if there is none, nil is returned.   ソース 編集
proc getCurrentExceptionMsg(): string {...}{.inline, gcsafe, locks: 0, raises: [], tags: [].}
Retrieves the error message that was attached to the current exception; if there is none, "" is returned.   ソース 編集
proc onRaise(action: proc (e: ref Exception): bool {...}{.closure.}) {...}{.deprecated, raises: [],
    tags: [].}
廃止予定

Deprecated since version 0.18.1: No good usages of this feature are known.

Can be used in a try statement to setup a Lisp-like condition system: This prevents the 'raise' statement to raise an exception but instead calls action. If action returns false, the exception has been handled and does not propagate further through the call stack.

  ソース 編集
proc setCurrentException(exc: ref Exception) {...}{.inline, gcsafe, locks: 0, raises: [],
    tags: [].}

Sets the current exception.

Warning: Only use this if you know what you are doing.

  ソース 編集
proc rawProc[T: proc](x: T): pointer {...}{.noSideEffect, inline.}
Retrieves the raw proc pointer of the closure x. This is useful for interfacing closures with C.   Source Edit
proc rawEnv[T: proc](x: T): pointer {...}{.noSideEffect, inline.}
Retrieves the raw environment pointer of the closure x. This is useful for interfacing closures with C.   Source Edit
proc finished[T: proc](x: T): bool {...}{.noSideEffect, inline.}
can be used to determine if a first class iterator has finished.   ソース 編集
proc quit(errormsg: string; errorcode = QuitFailure) {...}{.noreturn, raises: [], tags: [].}
A shorthand for echo(errormsg); quit(errorcode).   ソース 編集
proc `/`(x, y: int): float {...}{.inline, noSideEffect, raises: [], tags: [].}

Division of integers that results in a float.

関連:

echo 7 / 5 # => 1.4
  ソース 編集
proc `[]`[T, U](s: string; x: HSlice[T, U]): string {...}{.inline.}
Slice operation for strings. Returns the inclusive range [s[x.a], s[x.b]]:
var s = "abcdef"
assert s[1..3] == "bcd"
  ソース 編集
proc `[]=`[T, U](s: var string; x: HSlice[T, U]; b: string)

Slice assignment for strings.

If b.len is not exactly the number of elements that are referred to by x, a splice is performed:

用例:

var s = "abcdefgh"
s[1 .. ^2] = "xyz"
assert s == "axyzh"
  ソース 編集
proc `[]`[Idx, T, U, V](a: array[Idx, T]; x: HSlice[U, V]): seq[T]
Slice operation for arrays. Returns the inclusive range [a[x.a], a[x.b]]:
var a = [1, 2, 3, 4]
assert a[0..2] == @[1, 2, 3]
  ソース 編集
proc `[]=`[Idx, T, U, V](a: var array[Idx, T]; x: HSlice[U, V]; b: openArray[T])
Slice assignment for arrays.
var a = [10, 20, 30, 40, 50]
a[1..2] = @[99, 88]
assert a == [10, 99, 88, 40, 50]
  ソース 編集
proc `[]`[T, U, V](s: openArray[T]; x: HSlice[U, V]): seq[T]
Slice operation for sequences. Returns the inclusive range [s[x.a], s[x.b]]:
var s = @[1, 2, 3, 4]
assert s[0..2] == @[1, 2, 3]
  ソース 編集
proc `[]=`[T, U, V](s: var seq[T]; x: HSlice[U, V]; b: openArray[T])

Slice assignment for sequences.

If b.len is not exactly the number of elements that are referred to by x, a splice is performed.

用例:

var s = @"abcdefgh"
s[1 .. ^2] = @"xyz"
assert s == @"axyzh"
  ソース 編集
proc `[]`[T](s: openArray[T]; i: BackwardsIndex): T {...}{.inline.}
  ソース 編集
proc `[]`[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T {...}{.inline.}
  ソース 編集
proc `[]`(s: string; i: BackwardsIndex): char {...}{.inline, raises: [], tags: [].}
  ソース 編集
proc `[]`[T](s: var openArray[T]; i: BackwardsIndex): var T {...}{.inline.}
  ソース 編集
proc `[]`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex): var T {...}{.inline.}
  ソース 編集
proc `[]=`[T](s: var openArray[T]; i: BackwardsIndex; x: T) {...}{.inline.}
  ソース 編集
proc `[]=`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T) {...}{.inline.}
  ソース 編集
proc `[]=`(s: var string; i: BackwardsIndex; x: char) {...}{.inline, raises: [], tags: [].}
  ソース 編集
proc slurp(filename: string): string {...}{.magic: "Slurp".}
This is an alias for staticRead.   ソース 編集
proc staticRead(filename: string): string {...}{.magic: "Slurp".}
Compile-time readFile proc for easy resource embedding:
const myResource = staticRead"mydatafile.bin"

slurp is an alias for staticRead.

  ソース 編集
proc gorge(command: string; input = ""; cache = ""): string {...}{.magic: "StaticExec",
    raises: [], tags: [].}
This is an alias for staticExec.   ソース 編集
proc staticExec(command: string; input = ""; cache = ""): string {...}{.magic: "StaticExec",
    raises: [], tags: [].}

Executes an external process at compile-time and returns its text output (stdout + stderr).

If input is not an empty string, it will be passed as a standard input to the executed program.

const buildInfo = "Revision " & staticExec("git rev-parse HEAD") &
                  "\nCompiled on " & staticExec("uname -v")

gorge is an alias for staticExec.

Note that you can use this proc inside a pragma like passc or passl.

If cache is not empty, the results of staticExec are cached within the nimcache directory. Use --forceBuild to get rid of this caching behaviour then. command & input & cache (the concatenated string) is used to determine whether the entry in the cache is still valid. You can use versioning information for cache:

const stateMachine = staticExec("dfaoptimizer", "input", "0.8.0")
  ソース 編集
proc gorgeEx(command: string; input = ""; cache = ""): tuple[output: string, exitCode: int] {...}{.
    raises: [], tags: [].}
Similar to gorge but also returns the precious exit code.   ソース 編集
proc `+=`[T: SomeInteger](x: var T; y: T) {...}{.magic: "Inc", noSideEffect.}
Increments an integer.   ソース 編集
proc `+=`[T: enum | bool](x: var T; y: T) {...}{.magic: "Inc", noSideEffect,
                                   deprecated: "use `inc` instead".}
Deprecated: use `inc` instead
Deprecated since v0.20: use inc instead.   Source Edit
proc `-=`[T: SomeInteger](x: var T; y: T) {...}{.magic: "Dec", noSideEffect.}
Decrements an integer.   ソース 編集
proc `-=`[T: enum | bool](x: var T; y: T) {...}{.magic: "Dec", noSideEffect,
                                   deprecated: "0.20.0, use `dec` instead".}
Deprecated: 0.20.0, use `dec` instead
Deprecated since v0.20: use dec instead.   Source Edit
proc `*=`[T: SomeInteger](x: var T; y: T) {...}{.inline, noSideEffect.}
Binary *= operator for integers.   ソース 編集
proc `+=`[T: float | float32 | float64](x: var T; y: T) {...}{.inline, noSideEffect.}
Increments in place a floating point number.   ソース 編集
proc `-=`[T: float | float32 | float64](x: var T; y: T) {...}{.inline, noSideEffect.}
Decrements in place a floating point number.   ソース 編集
proc `*=`[T: float | float32 | float64](x: var T; y: T) {...}{.inline, noSideEffect.}
Multiplies in place a floating point number.   ソース 編集
proc `/=`(x: var float64; y: float64) {...}{.inline, noSideEffect, raises: [], tags: [].}
Divides in place a floating point number.   ソース 編集
proc `/=`[T: float | float32](x: var T; y: T) {...}{.inline, noSideEffect.}
Divides in place a floating point number.   ソース 編集
proc `&=`(x: var string; y: string) {...}{.magic: "AppendStrStr", noSideEffect.}
Appends in place to a string.
var a = "abc"
a &= "de" # a <- "abcde"
  ソース 編集
proc shallow[T](s: var seq[T]) {...}{.noSideEffect, inline.}

Marks a sequence s as shallow. Subsequent assignments will not perform deep copies of s.

This is only useful for optimization purposes.

  ソース 編集
proc shallow(s: var string) {...}{.noSideEffect, inline, raises: [], tags: [].}

Marks a string s as shallow. Subsequent assignments will not perform deep copies of s.

This is only useful for optimization purposes.

  ソース 編集
proc insert(x: var string; item: string; i = 0.Natural) {...}{.noSideEffect, raises: [], tags: [].}
Inserts item into x at position i.
var a = "abc"
a.insert("zz", 0) # a <- "zzabc"
  ソース 編集
proc addEscapedChar(s: var string; c: char) {...}{.noSideEffect, inline, raises: [], tags: [].}
Adds a char to string s and applies the following escaping:
  • replaces any \ by \\
  • replaces any ' by \'
  • replaces any " by \"
  • replaces any \a by \\a
  • replaces any \b by \\b
  • replaces any \t by \\t
  • replaces any \n by \\n
  • replaces any \v by \\v
  • replaces any \f by \\f
  • replaces any \c by \\c
  • replaces any \e by \\e
  • replaces any other character not in the set {'\21..'\126'} by ``\xHH where HH is its hexadecimal value.

The procedure has been designed so that its output is usable for many different common syntaxes.

Note: This is not correct for producing Ansi C code!

  ソース 編集
proc addQuoted[T](s: var string; x: T)

Appends x to string s in place, applying quoting and escaping if x is a string or char.

See addEscapedChar for the escaping scheme. When x is a string, characters in the range {\128..\255} are never escaped so that multibyte UTF-8 characters are untouched (note that this behavior is different from addEscapedChar).

The Nim standard library uses this function on the elements of collections when producing a string representation of a collection. It is recommended to use this function as well for user-side collections. Users may overload addQuoted for custom (string-like) types if they want to implement a customized element representation.

var tmp = ""
tmp.addQuoted(1)
tmp.add(", ")
tmp.addQuoted("string")
tmp.add(", ")
tmp.addQuoted('c')
assert(tmp == """1, "string", 'c'""")
  ソース 編集
proc safeAdd[T](x: var seq[T]; y: T) {...}{.noSideEffect, deprecated.}
廃止予定
Adds y to x unless x is not yet initialized; in that case, x becomes @[y].   Source Edit
proc safeAdd(x: var string; y: char) {...}{.noSideEffect, deprecated, raises: [], tags: [].}
廃止予定
Adds y to x. If x is nil it is initialized to "".   Source Edit
proc safeAdd(x: var string; y: string) {...}{.noSideEffect, deprecated, raises: [], tags: [].}
廃止予定
Adds y to x unless x is not yet initialized; in that case, x becomes y.   Source Edit
proc locals(): RootObj {...}{.magic: "Plugin", noSideEffect, raises: [], tags: [].}

Generates a tuple constructor expression listing all the local variables in the current scope.

This is quite fast as it does not rely on any debug or runtime information. Note that in contrast to what the official signature says, the return type is not RootObj but a tuple of a structure that depends on the current scope. 用例:

proc testLocals() =
  var
    a = "something"
    b = 4
    c = locals()
    d = "super!"
  
  b = 1
  for name, value in fieldPairs(c):
    echo "name ", name, " with value ", value
  echo "B is ", b
# -> name a with value something
# -> name b with value 4
# -> B is 1
  ソース 編集
proc deepCopy[T](x: var T; y: T) {...}{.noSideEffect, magic: "DeepCopy".}

Performs a deep copy of y and copies it into x.

This is also used by the code generator for the implementation of spawn.

  ソース 編集
proc deepCopy[T](y: T): T
Convenience wrapper around deepCopy overload.   ソース 編集
proc procCall(x: untyped) {...}{.magic: "ProcCall", compileTime, raises: [], tags: [].}
Special magic to prohibit dynamic binding for method calls. This is similar to super in ordinary OO languages.
# 'someMethod' will be resolved fully statically:
procCall someMethod(a, b)
  ソース 編集
proc xlen(x: string): int {...}{.magic: "XLenStr", noSideEffect,
                        deprecated: "use len() instead", raises: [], tags: [].}
Deprecated: use len() instead
Deprecated since version 0.18.1. Use len() instead.   Source Edit
proc xlen[T](x: seq[T]): int {...}{.magic: "XLenSeq", noSideEffect,
                           deprecated: "use len() instead".}
Deprecated: use len() instead

Deprecated since version 0.18.1. Use len() instead.

Returns the length of a sequence or a string without testing for 'nil'. This is an optimization that rarely makes sense.

  ソース 編集
proc `==`(x, y: cstring): bool {...}{.magic: "EqCString", noSideEffect, inline, raises: [],
                            tags: [].}
Checks for equality between two cstring variables.   ソース 編集
proc `==`(x: string; y: type(nil) | type(nil)): bool {...}{.error: "\'nil\' is now invalid for \'string\'; compile with --nilseqs:on for a migration period".}
  ソース 編集
proc `==`(x: type(nil) | type(nil); y: string): bool {...}{.error: "\'nil\' is now invalid for \'string\'; compile with --nilseqs:on for a migration period".}
  ソース 編集
proc substr(s: string; first, last: int): string {...}{.raises: [], tags: [].}

Copies a slice of s into a new string and returns this new string.

The bounds first and last denote the indices of the first and last characters that shall be copied. If last is omitted, it is treated as high(s). If last >= s.len, s.len is used instead: This means substr can also be used to cut or limit a string's length.

用例:

let a = "abcdefgh"
assert a.substr(2, 5) == "cdef"
assert a.substr(2) == "cdefgh"
assert a.substr(5, 99) == "fgh"
  ソース 編集
proc substr(s: string; first = 0): string {...}{.raises: [], tags: [].}
  ソース 編集
proc toOpenArray[T](x: ptr UncheckedArray[T]; first, last: int): openArray[T] {...}{.
    magic: "Slice".}
  ソース 編集
proc toOpenArray(x: cstring; first, last: int): openArray[char] {...}{.magic: "Slice".}
  ソース 編集
proc toOpenArrayByte(x: cstring; first, last: int): openArray[byte] {...}{.magic: "Slice".}
  ソース 編集
proc toOpenArray[T](x: seq[T]; first, last: int): openArray[T] {...}{.magic: "Slice".}
  ソース 編集
proc toOpenArray[T](x: openArray[T]; first, last: int): openArray[T] {...}{.magic: "Slice".}
  ソース 編集
proc toOpenArray[I, T](x: array[I, T]; first, last: I): openArray[T] {...}{.magic: "Slice".}
  ソース 編集
proc toOpenArray(x: string; first, last: int): openArray[char] {...}{.magic: "Slice".}
  ソース 編集
proc toOpenArrayByte(x: string; first, last: int): openArray[byte] {...}{.magic: "Slice".}
  ソース 編集
proc toOpenArrayByte(x: openArray[char]; first, last: int): openArray[byte] {...}{.
    magic: "Slice".}
  ソース 編集
proc toOpenArrayByte(x: seq[char]; first, last: int): openArray[byte] {...}{.magic: "Slice".}
  ソース 編集

イテレータ

iterator countdown[T](a, b: T; step: Positive = 1): T {...}{.inline.}

Counts from ordinal value a down to b (inclusive) with the given step count.

T may be any ordinal type, step may only be positive.

Note: This fails to count to low(int) if T = int for efficiency reasons.

for i in countdown(7, 3):
  echo i # => 7; 6; 5; 4; 3

for i in countdown(9, 2, 3):
  echo i # => 9; 6; 3
  ソース 編集
iterator countup[T](a, b: T; step: Positive = 1): T {...}{.inline.}

Counts from ordinal value a to b (inclusive) with the given step count.

T may be any ordinal type, step may only be positive.

Note: This fails to count to high(int) if T = int for efficiency reasons.

for i in countup(3, 7):
  echo i # => 3; 4; 5; 6; 7

for i in countup(2, 9, 3):
  echo i # => 2; 5; 8
  ソース 編集
iterator `..`[T](a, b: T): T {...}{.inline.}

An alias for countup(a, b, 1).

関連:

for i in 3 .. 7:
  echo i # => 3; 4; 5; 6; 7
  ソース 編集
iterator `..`(a, b: int64): int64 {...}{.inline, raises: [], tags: [].}

A type specialized version of .. for convenience so that mixing integer types works better.

関連:

  ソース 編集
iterator `..`(a, b: int32): int32 {...}{.inline, raises: [], tags: [].}

A type specialized version of .. for convenience so that mixing integer types works better.

関連:

  ソース 編集
iterator `..`(a, b: uint64): uint64 {...}{.inline, raises: [], tags: [].}

A type specialized version of .. for convenience so that mixing integer types works better.

関連:

  ソース 編集
iterator `..`(a, b: uint32): uint32 {...}{.inline, raises: [], tags: [].}

A type specialized version of .. for convenience so that mixing integer types works better.

関連:

  ソース 編集
iterator `..<`[T](a, b: T): T {...}{.inline.}
  ソース 編集
iterator `..<`(a, b: int64): int64 {...}{.inline, raises: [], tags: [].}
A type specialized version of ..< for convenience so that mixing integer types works better.   ソース 編集
iterator `..<`(a, b: int32): int32 {...}{.inline, raises: [], tags: [].}
A type specialized version of ..< for convenience so that mixing integer types works better.   ソース 編集
iterator `..<`(a, b: uint64): uint64 {...}{.inline, raises: [], tags: [].}
A type specialized version of ..< for convenience so that mixing integer types works better.   ソース 編集
iterator `..<`(a, b: uint32): uint32 {...}{.inline, raises: [], tags: [].}
A type specialized version of ..< for convenience so that mixing integer types works better.   ソース 編集
iterator `||`[S, T](a: S; b: T; annotation: static string = "parallel for"): T {...}{.inline,
    magic: "OmpParFor", sideEffect.}

OpenMP parallel loop iterator. Same as .. but the loop may run in parallel.

annotation is an additional annotation for the code generator to use. The default annotation is parallel for. Please refer to the OpenMP Syntax Reference for further information.

Note that the compiler maps that to the #pragma omp parallel for construct of OpenMP and as such isn't aware of the parallelism in your code! Be careful! Later versions of || will get proper support by Nim's code generator and GC.

  ソース 編集
iterator `||`[S, T](a: S; b: T; step: Positive;
                  annotation: static string = "parallel for"): T {...}{.inline,
    magic: "OmpParFor", sideEffect.}

OpenMP parallel loop iterator with stepping.  Same as countup but the loop may run in parallel.

annotation is an additional annotation for the code generator to use. The default annotation is parallel for. Please refer to the OpenMP Syntax Reference for further information.

Note that the compiler maps that to the #pragma omp parallel for construct of OpenMP and as such isn't aware of the parallelism in your code! Be careful! Later versions of || will get proper support by Nim's code generator and GC.

  ソース 編集

テンプレート

template `!=`(x, y: untyped): untyped
Unequals operator. This is a shorthand for not (x == y).   ソース 編集
template `>=`(x, y: untyped): untyped
"is greater or equals" operator. This is the same as y <= x.   ソース 編集
template `>`(x, y: untyped): untyped
"is greater" operator. This is the same as y < x.   ソース 編集
template offsetOf[T; ](t: typedesc[T]; member: untyped): int
  ソース 編集
template offsetOf[T](value: T; member: untyped): int
  ソース 編集
template incl[T](x: var set[T]; y: set[T])
Includes the set y in the set x.
var a = {1, 3, 5, 7}
var b = {4, 5, 6}
a.incl(b)  # a <- {1, 3, 4, 5, 6, 7}
  ソース 編集
template excl[T](x: var set[T]; y: set[T])
Excludes the set y from the set x.
var a = {1, 3, 5, 7}
var b = {3, 4, 5}
a.excl(b)  # a <- {1, 7}
  ソース 編集
template `>=%`(x, y: untyped): untyped
Treats x and y as unsigned and compares them. Returns true if unsigned(x) >= unsigned(y).   ソース 編集
template `>%`(x, y: untyped): untyped
Treats x and y as unsigned and compares them. Returns true if unsigned(x) > unsigned(y).   ソース 編集
template `in`(x, y: untyped): untyped {...}{.dirty.}
Sugar for contains.
assert(1 in (1..3) == true)
assert(5 in (1..3) == false)
  ソース 編集
template `notin`(x, y: untyped): untyped {...}{.dirty.}
Sugar for not contains.
assert(1 notin (1..3) == false)
assert(5 notin (1..3) == true)
  ソース 編集
template `isnot`(x, y: untyped): untyped
Negated version of is. Equivalent to not(x is y).
assert 42 isnot float
assert @[1, 2] isnot enum
  ソース 編集
template unown(x: typed): untyped
  ソース 編集
template `<//>`(t: untyped): untyped
  ソース 編集
template disarm(x: typed)
Useful for disarming dangling pointers explicitly for the
--newruntime. Regardless of whether --newruntime is used or not

this sets the pointer or callback x to nil. This is an experimental API!

  ソース 編集
template accumulateResult(iter: untyped) {...}{.deprecated: "use `sequtils.toSeq` instead (more hygienic, sometimes more efficient)".}
Deprecated: use `sequtils.toSeq` instead (more hygienic, sometimes more efficient)

Deprecated since v0.19.2: use sequtils.toSeq instead.

Helps to convert an iterator to a proc. sequtils.toSeq is more hygienic and efficient.

  ソース 編集
template newException(exceptn: typedesc; message: string;
                     parentException: ref Exception = nil): untyped
Creates an exception object of type exceptn and sets its msg field to message. Returns the new exception object.   ソース 編集
template likely(val: bool): bool

Hints the optimizer that val is likely going to be true.

You can use this template to decorate a branch condition. On certain platforms this can help the processor predict better which branch is going to be run. 用例:

for value in inputValues:
  if likely(value <= 100):
    process(value)
  else:
    echo "Value too big!"

On backends without branch prediction (JS and the nimscript VM), this template will not affect code execution.

  ソース 編集
template unlikely(val: bool): bool

Hints the optimizer that val is likely going to be false.

You can use this proc to decorate a branch condition. On certain platforms this can help the processor predict better which branch is going to be run. 用例:

for value in inputValues:
  if unlikely(value > 100):
    echo "Value too big!"
  else:
    process(value)

On backends without branch prediction (JS and the nimscript VM), this template will not affect code execution.

  ソース 編集
template formatErrorIndexBound[T](i, a, b: T): string
  ソース 編集
template formatErrorIndexBound[T](i, n: T): string
  ソース 編集
template `^`(x: int): BackwardsIndex
Builtin roof operator that can be used for convenient array access. a[^x] is a shortcut for a[a.len-x].
let
  a = [1, 3, 5, 7, 9]
  b = "abcdefgh"

echo a[^1] # => 9
echo b[^2] # => g
  ソース 編集
template `..^`(a, b: untyped): untyped
A shortcut for .. ^ to avoid the common gotcha that a space between '..' and '^' is required.   ソース 編集
template `..<`(a, b: untyped): untyped
A shortcut for a .. pred(b).
for i in 5 ..< 9:
  echo i # => 5; 6; 7; 8
  ソース 編集
template `[]`(s: string; i: int): char
  ソース 編集
template `[]=`(s: string; i: int; val: char)
  ソース 編集
template `&=`(x, y: typed)

Generic 'sink' operator for Nim.

For files an alias for write. If not specialized further, an alias for add.

  ソース 編集
template currentSourcePath(): string

Returns the full file-system path of the current source.

To get the directory containing the current source, use it with os.parentDir() as currentSourcePath.parentDir().

The path returned by this template is set at compile time.

See the docstring of macros.getProjectPath() for an example to see the distinction between the currentSourcePath and getProjectPath.

関連:

  ソース 編集
template rangeCheck(cond)
Helper for performing user-defined range checks. Such checks will be performed only when the rangechecks compile-time option is enabled.   ソース 編集
template closureScope(body: untyped): untyped
Useful when creating a closure in a loop to capture local loop variables by their current iteration values. 用例:
var myClosure : proc()
# without closureScope:
for i in 0 .. 5:
  let j = i
  if j == 3:
    myClosure = proc() = echo j
myClosure() # outputs 5. `j` is changed after closure creation
# with closureScope:
for i in 0 .. 5:
  closureScope: # Everything in this scope is locked after closure creation
    let j = i
    if j == 3:
      myClosure = proc() = echo j
myClosure() # outputs 3
  ソース 編集
template once(body: untyped): untyped
Executes a block of code only once (the first time the block is reached).
proc draw(t: Triangle) =
  once:
    graphicsInit()
  line(t.p1, t.p2)
  line(t.p2, t.p3)
  line(t.p3, t.p1)
  ソース 編集