11-13-2023, 12:58 AM
Quote:btw: isYes and No. You set the length when you set 'cMAXELEMENTS'. If you want to change the length of the '_MEM' you have to create a new one with the length desired and copy the contents from the old one to the new one, and not forget '_MEMFREE ' the old memory location.
Code: (Select All)
Code: (Select All)array AS _MEM
variable length?
I updated this code a bit and it allows for resizing the array. BEWARE there is no error checking, so if you try to 'set' or 'get' a value outside of whats allocated then it will pop an error.
Code: (Select All)
' Program to create an array of Doubles in a UDT
DIM AS LONG i
DIM AS DOUBLE v
CONST cMAXELEMENTS = 10
TYPE tARRAY
array AS _MEM
END TYPE
DIM AS tARRAY object
SCREEN 12: _FONT 8
' initialize the array
createObject object, cMAXELEMENTS
' set the array to random values
PRINT "Create initial Values"
FOR i = 0 TO cMAXELEMENTS
v = INT(RND * 5)
setElement object, i, v
PRINT "index:"; i; "->"; v
NEXT
' retrieve values from array
PRINT "Retrieve Values"
FOR i = 0 TO cMAXELEMENTS
PRINT "index:"; i; "->"; getElement(object, i)
NEXT
'resize array
resizeObject object, cMAXELEMENTS * 2
' retrieve values from array
PRINT "Double the size of the array"
FOR i = 0 TO cMAXELEMENTS * 2
PRINT "index:"; i; "->"; getElement(object, i)
NEXT
'resize array
resizeObject object, cMAXELEMENTS / 2
' retrieve values from array
PRINT "Half the size of the array"
FOR i = 0 TO cMAXELEMENTS / 2
PRINT "index:"; i; "->"; getElement(object, i)
NEXT
SUB createObject (o AS tARRAY, size AS LONG)
' make array one larger than number of elements
o.array = _MEMNEW((size + 1) * 8) ' 8 is the number of bytes in a double
END SUB
SUB resizeObject (o AS tARRAY, size AS LONG)
DIM AS _MEM old
DIM AS _OFFSET l
DIM AS LONG iter
' Copy old _MEM to a temp _MEM
old = o.array
' Create new array of the new size
createObject o, size
' Copy data from old array to new array
iter = 0: DO WHILE iter < o.array.SIZE AND iter < old.SIZE
_MEMPUT o.array, o.array.OFFSET + iter, _MEMGET(old, old.OFFSET + iter, _BYTE) AS _BYTE
iter = iter + 1: LOOP
' free old array
_MEMFREE old
END SUB
FUNCTION getElement# (o AS tARRAY, element AS LONG)
getElement = _MEMGET(o.array, o.array.OFFSET + (element * 8), DOUBLE)
END FUNCTION
SUB setElement (o AS tARRAY, element AS LONG, v AS DOUBLE)
_MEMPUT o.array, o.array.OFFSET + (element * 8), v AS DOUBLE
END SUB
2D physics engine https://github.com/mechatronic3000/fzxNGN
Untitled Rouge-like https://github.com/mechatronic3000/Untitled-Rougelike
QB Pool https://github.com/mechatronic3000/QBPool
Untitled Rouge-like https://github.com/mechatronic3000/Untitled-Rougelike
QB Pool https://github.com/mechatronic3000/QBPool