Page 1 of 1

Read Structure from Data Section

Posted: Sun Sep 20, 2015 2:22 pm
by c4s
If we want to read a structure from a data section, we currently have to do something like this:

Code: Select all

Structure MyStruc
	String.s
	Integer.i
	Float.f
EndStructure

DataSection
	MyData:
	Data.i 2
	Data.s "Text 1" : Data.i 12 : Data.f 3.4
	Data.s "Text 2" : Data.i 56 : Data.f 7.8
EndDataSection


Define i, iMax, NewList Xs.MyStruc()

Restore MyData
Read.i iMax
For i = 1 To iMax
	AddElement(Xs())
	Read.s Xs()\String
	Read.i Xs()\Integer
	Read.f Xs()\Float
Next
This can obviously get very tiresome for larger structures. So how about allowing the following more intuitive way:

Code: Select all

Structure MyStruc
	String.s
	Integer.i
	Float.f
EndStructure

DataSection
	MyData:
	Data.i 2
	Data.MyStruc "Text 1", 12, 3.4  ; If absolutely necessary the default way of storing would be ok too (see first example)
	Data.MyStruc "Text 2", 56, 7.8
EndDataSection


Define i, iMax, NewList Xs.MyStruc()

Restore MyData
Read.i iMax
For i = 1 To iMax
	AddElement(Xs())
	Read.MyStruc Xs()  ; Here is the magic!
Next
...I figured that it probably wouldn't work for "complex structures" (those including lists). So just allow it for structures of basic types. I'd say it would still be a great improvement.

Re: Read Structure from Data Section

Posted: Sun Sep 20, 2015 3:07 pm
by Tenaja
+1, it would be handy to have this natively.


In the meantime, I have written a macro so the actual pseudo-datasection is cleaner:

Code: Select all

DataStruct("TextHere",		64)
The macro just creates two DataSections, but unfortunately, you still have to create a loop to read them.

Re: Read Structure from Data Section

Posted: Sun Sep 20, 2015 3:08 pm
by Tenaja
Oh, yeah...already requested, with complete workarounds:
http://purebasic.fr/english/viewtopic.p ... 66#p411422
(Using the last example eliminates the requirement for the loop.)

Re: Read Structure from Data Section

Posted: Sun Sep 20, 2015 4:12 pm
by c4s
Thanks for pointing me to that thread. It's interesting to see that KJ67 had the exact same idea. And you're right, bosker's workaround is quite clever. However, I think we all agree that a native solution would be even better... ;)

Re: Read Structure from Data Section

Posted: Thu Nov 26, 2015 8:08 am
by Maitre_Kanter
Use the following code @"string" instead of "string".

Code: Select all

Structure MyStruc
  String.s
  Integer.i
  Float.f
EndStructure

DataSection
  MyDataSize:
  Data.i 2
  MyDataStart:
  Data.i @"Text 1" : Data.i 12 : Data.f 3.4
  Data.i @"Text 2" : Data.i 56 : Data.f 7.8
EndDataSection

Restore MyDataSize
Read.i iMax
For i = 0 To iMax - 1
  AddElement(Xs2())
  CopyStructure( ?MyDataStart + SizeOf(MyStruc) * i , @Xs2() , MyStruc )
  Debug Xs2()\String
  Debug Xs2()\Integer
  Debug Xs2()\Float 
Next