Demonstrate how to dynamically add variables to an object (a class instance) at runtime.

This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.

 
'=================
class fleximembers
'=================
 
indexbase 0
bstring buf, *varl
sys     dp,en
 
method addVar(string name,dat)
  sys le=len buf
  if dp+16>le then
    buf+=nuls 0x100 : le+=0x100 :
  end if
  @varl=?buf
  varl[en]=name
  varl[en+1]=dat
  dp+=2*sizeof sys
  en+=2 'next slot
end method
 
method find(string name) as sys
  sys i
  for i=0 to <en step 2
    if name=varl[i] then return i+1
  next
end method
 
method vars(string name) as string
  sys f=find(name)
  if f then return varl[f]
end method
 
method VarF(string name) as double
  return vars(name)
end method
 
method VarI(string name) as sys
  return vars(name)
end method
 
method vars(string name,dat)
  bstring varl at buf
  sys f=find(name)
  if f then varl[f]=dat
end method
 
method delete()
  sys i
  sys v at buf
  for i=0 to <en
     freememory v[i]
  next
  freememory ?buf
  ? buf=0 : en=0 : dp=0
end method
 
end class
 
'TEST
 
fleximembers a
 
a.addVar "p",5
a.addVar "q",4.5
a.addVar "r","123456"
 
print a.Vars("q")+a.vars("q") 'result 4.54.5
print a.Varf("q")+a.varf("q") 'result 9
 
a.delete
 
 