Hi Nim-mancers : )

  * Is the code below with Unchecked array valid?
  * What will happen if my object has variables for managed stuff? Do I need to 
dispose/reset my object before freeing mem?


    
    
    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[]
    
    
    Run

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
    
    
    Run

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!

Reply via email to