Author Topic: Dynamic arrays in a class.  (Read 1643 times)

0 Members and 1 Guest are viewing this topic.

Brian Alvarez

  • Guest
Dynamic arrays in a class.
« on: November 24, 2018, 10:51:08 AM »
 How can i do it? This doesnt work:

Code: [Select]
class some
  redim string dat(0)
end class

What im trying to do is create a resizable string array that is available in all the methods.
it is supposed to be resized in the constructor of the class.

« Last Edit: November 24, 2018, 01:34:24 PM by Brian Alvarez »

Charles Pegge

  • Guest
Re: Dynamic arrays in a class.
« Reply #1 on: November 24, 2018, 06:17:20 PM »
Hi Brian,

This is an example string array class which uses a dynamic buffer with its own redim. It also uses bstrings, so garbage collection is totally managed by the redim and destructor methods.

Code: [Select]

$filename "t.exe"
'uses rtl64

class Buffer
============
  sys bu 'buffer
  int bl 'buffer length bytes
  '
  function redim(int i)
  =====================
  sys nbu
  int nbl
  nbl=i*sizeof(sys)
  nbu=getmemory nbl
  int e=bl
  if bl
    if bl>nbl then e=nbl
    copy nbu,bu,e
    freememory bu
  endif
  bu=nbu
  bl=nbl
  end function
  '
  function constructor(int i)
  ===========================
  this.redim(i)
  end function
  '
  function destructor()
  ===================
  freememory bu
  bu=0
  bl=0
  end function
  '
end class

class ArrayString
=================
  '
  indexbase 0
  '
  has buffer b
  int ns 'number of strings
  '
  function redim(int i)
  =====================
  b.constructor(i+1)
  end function
  '
  function constructor(int i)
  ===========================
  b.constructor(i+1)
  int j
  bstring s at (b.bu)
  for j=0 to i
    s[i]=""
  next
  ns=i+1
  end function
  '
  function destructor()
  =====================
  int i
  bstring s at (b.bu)
  for i=0 to ns-1
    frees s[i]
  next
  b.destructor()
  end function
  '
  function vs(int i) as string
  ============================
  bstring s at (b.bu)
  if (i>=0)and(i<ns)
    return s(i)
  else
    'out of bounds error
  endif
  end function
  '
  function vs(int i,string t)
  ===========================
  bstring s at (b.bu)
  if (i>=0)and(i<ns)
    s(i)=t
  else
    'out of bounds error
  endif
  end function
  '
  function lbound() as int
  ========================
  return 0
  end function
  '
  function ubound() as int
  ========================
  return ns-1
  end function
  '
end class

'TESTS
======
new ArrayString ss(99)
ss.vs(50)="okay"
ss.redim(200)
ss.redim(70)
print ss.vs(50) ", " ss.ubound()
del ss

copy nbu,bu,e
Fixed!
« Last Edit: November 27, 2018, 04:29:55 AM by Charles Pegge »

Brian Alvarez

  • Guest
Re: Dynamic arrays in a class.
« Reply #2 on: November 24, 2018, 08:46:47 PM »
Thanks Charles, i will give it a try tomorrow. :)

Brian Alvarez

  • Guest
Re: Dynamic arrays in a class.
« Reply #3 on: November 25, 2018, 09:25:23 PM »
The trick worked flawlessly! Thanks Charles. :)