OK, let's say I have a array-type variable.
Is it possible to set it to... nothing?
I mean let's say a function takes an array parameter, with some (or no) values. I could obviously declare it as a seq, but then we would deal with memory allocation. I can also declare it as an openArray, and then I can pass both an array with values and an empty one, e.g.
proc myFunc(a: openArray[int], b: openArray[int]) =
....
myFunc([1,2,3],[])
Now, the problem arises when this array is e.g. part of an object. E.g.
myobj = object
a: openArray[int]
(I'm not allowed to do that)
If I try to define it as a c-style array, the definition goes well, but I cannot find a way to be able to set it to empty too. E.g.
myobj = object
a: array[5,int]
b: array[5,int]
myobj(a: [1,2,3,4,5], b: [])
In the case of b, it complains because it keeps expecting - exactly - 5 items.
How can I circumvent that, so that I can set any number of arguments, from zero(0) to 5?
The value "nothing" does not really exist in computer science. Of course in C we have NULL and in Nim we have nil for ref and pointer types. NULL and nil are special well defined values, often binary zero, which have a special meaning by definition: The absence of a value.
In Nim we have the seq type which has additional to the content a len field which gives information about absence from data when len field is zero, and we have option types which works in a similar way (I have never used option types myself.)
If you want to use arrays, you may consider refs or ptrs to that arrays instead, then you can test for nil. Or, you can define your "nil" yourself. For an array of 4 ints, you are free to define [int.low, 0, 0, 0] as you nil value. Of course you can not use that value for real data content then, but that is generally no problem. You can pass such as special value as your nil.
Or learn about Nim's option types. I have to do myself. I would assume some overhead for that types, so I avoided them till now.
There are also uncheckedArray. See here:
https://nim-lang.github.io/Nim/manual.html#types-unchecked-arrays
You can trust the compiler a bit more. If you follow along with http://zevv.nl/nim-memory/#_lets_talk_about_seqs and use that technique to look under the hood of an empty seq, youll see it's a nil pointer until you add data
So really, just use a seq!
type
Bar = object
a,b:seq[int]
proc seqToPtr[T](x: seq[T]): pointer {.inline, noSideEffect.} =
when defined(nimSeqsV2):
result = cast[NimSeqV2[T]](x).p
else:
result = cast[pointer](x)
proc showPointers(b:Bar)=
echo seqToPtr(b.a).repr
echo seqToPtr(b.b).repr
var x = Bar(a: @[1,2,3],b: @[])
x.showPointers