type
Player = object
hp: int
attack: int
var
players = cast[ptr UncheckedArray[Player]](alloc(Player.sizeof*2))
players[1].hp = 30
# resize array
players = cast[ptr UncheckedArray[Player]](realloc(players, Player.sizeof * 4))
players[3].hp = 20
var pp = addr players[1]
echo pp[]
echo players[1]
echo players[3]
# just for fun
swap(players[1], players[3])
echo "-------------------"
# now its player 3
echo pp[]
echo players[1]
echo players[3]
# free, set pointer to nil
players = cast[ptr UncheckedArray[Player]](realloc(players, 0))
echo repr(players)
# bad, dangling pointer
echo pp[]
As a game developer I prefer to allocate memory for stuff I need and instead of creating/destroying objects just reuse allocated.
I'll try to explain what I want to achieve :
[ 1 2 4 5 | 3 ] real size: 5 elements, actual size: 4 elements
if I "add" new element here then instead of creating new one I take element 3 (unused) instead.
Only if my actual size equals to the real size I will resize the cap of a container
I guess in some ways it's similar to Nim sequences but they don't work for this scenario and arrays are strictly sized in Nim as far I understood.
( In C# I actually use arrays instead of lists but I have the ability to resize em by creating a new array of a new size and copying stuff from the previous one, but I realize that C# arrays are different from those in Nim )
Thanks!
You should be able to use a Nim seq for your task. Try it harder, and ask again when you really think that it is not possible.
UncheckedArray is generally used only for very low level stuff or when you get a C array from some library. Generally you should avoid using add() and cast, because only without Nim is really Memory safe.
I am not even sure if realloc() preserves the old content.
If You really like better to alloc your memory manually and use addr() often in ordinary code, then maybe languages like C or Zig are better for you. Well, I guess mratsim is using alloc(), cast and addr() too in all his libs, and maybe it is used in the compiler too. And it is used in languages bindings of course. But that are the low level parts of the Nim language then.
AHA!
seq.SetLen() do the job XD
Thanks, @Stefan_Salewski