Page 1 of 1

Declare Structure Shorthand

Posted: Sat Feb 25, 2017 2:03 pm
by eddy
Hi,

I propose an elegant way to declare and initialize structure variables.
PROS
- It supports PB auto-completion of structure
- It supports PB auto-completion of procedure
- It only needs a prepropcessor task for the implementation
CONS
- It doesn't support map, list and array

Code: Select all

Structure CustomSprite
   id.i
   x.i
   y.i
   p.i[2]
   txt$
   Map book$()
EndStructure

Declare CustomSprite(id, x, y)

Procedure CustomSprite(id, x, y)
   Protected *data.CustomSprite=AllocateStructure(CustomSprite)
   *data\id=id
   *data\x=x
   *data\y=y
   *data\p[1]=101
   *data\txt$="ok"
   *data\book$("secret")="secret is 42"
   ProcedureReturn *Data
EndProcedure

NewMap _map.CustomSprite()
NewList _list.CustomSprite()
Dim _array.CustomSprite(10)


Procedure test()
   CompilerIf 1
      Global *a.CustomSprite=CustomSprite(0, 11, 12)
      Define *b.CustomSprite=CustomSprite(1, 3, 4)
      Protected *c.CustomSprite=CustomSprite(7, 77, 777)
      v.CustomSprite : *v_CustomSprite=CustomSprite(8, 9, 10) : CopyStructure(*v_CustomSprite, @v, CustomSprite) : FreeStructure(*v_CustomSprite)
   CompilerElse
      Global *a.CustomSprite(0, 11, 12)        ;<------- shorthand version
      Define *b.CustomSprite(1, 3, 4)          ;<------- shorthand version
      Protected *c.CustomSprite(1, 3, 4)       ;<------- shorthand version
      v.CustomSprite(1, 3, 4)                  ;<------- shorthand version
   CompilerEndIf
   Debug *a\id
   Debug *b\x
   Debug *c\y
   Debug v\txt$ + " " + v\y + " " + v\p[1] + " " + v\book$("secret")
   
   FreeStructure(*a)
   FreeStructure(*b)
   FreeStructure(*c)
EndProcedure

test()

Re: Declare Structure Shorthand

Posted: Sat Feb 25, 2017 2:15 pm
by #NULL
once i used a macro for this purpose but its probably not worth it.

Code: Select all

Macro NewCustomSprite(p1, p2, p3)
    CustomSprite =  CustomSprite(p1, p2, p3)
EndMacro

Define *b.NewCustomSprite(1,3,4)          ;<------- shorthand version

Re: Declare Structure Shorthand

Posted: Sat Feb 25, 2017 2:23 pm
by eddy
#NULL wrote:once i used a macro for this purpose but its probably not worth it.
I know, but this solution breaks code autocompletion.