LiveCode LessonsHow To - Step-By-Step Guides To Tasks In LiveCode LiveCode ArraysHow do I store an array in a text file and then retrieve it again?

How do I store an array in a text file and then retrieve it again?

Revolution enables you to convert an array into a format that can be stored in a file or sent to a URL using arrayEncode. Conversely, you can use arrayDecode to to convert data back into a Revolution array.

This lesson will show you an example of how to use arrayEncode/arrayDecode with the fillGradient property of a graphic.

Attached Files

The Example Stack

The Example Stack

In Revolution the fillgradient property of a graphic is an array containing all of the gradient information. The example stack demonstrates how to store the fillgradient array of the graphic in a file as well as load the fillgradient array from a file and assign it to the graphic.

Storing an Array in a File

Storing an Array in a File

This code snippet from the example stack demonstrates how to convert the fillGradient property (an array) of a graphic into a binary representation of the array using arrayEncode. This binary representation is stored in the variable theEncodedArray.

When storing the array in a file it is important that you write the data to the file in binary format otherwise the encoded array data will be corrupted. That is why the binfile: prefix is used.

Loading an Array From a File

Loading an Array From a File

To load the binary representation of the array from a file you just reverse the steps. Begin by reading the data from the file in binary format using the binfile: prefix. In this snippet the binary data is stored in the variable theEncodedArray.

You can then pass the binary data to arrayDecode which transforms the binary data back into a Revolution array variable, theFillGradientA in this case. At this point the array can be assigned to the fillgradient property of a graphic.

2 Comments

anonymous

Nice. But to save as a TEXT file, you must base64Encode the encoded BINARY data. To load it, just base64Decode.

To save as text:
if theFile is not empty then
put arrayEncode(the fillgradient of graphic 1) into theEncodedArray
put base64Encode(theEncodedArray) into URL ("file:" & theFile)
end if

To load the text and convert back to the gradient array:
if theFile is not empty then
put URL ("file:" & theFile) into theBase64Array
put base64Decode(theBase64Array) into theEncodedArray
put arrayDecode(theEncodedArray) into theFillGradientA
set the fillgradient of graphic 1 to theFillGradientA
end if

Björnke von Gierke

Note that the example given uses "binfile". That takes care of binary just fine. Altho your solution works as well as the example, yours will generate much bigger files.

Add your comment

E-Mail me when someone replies to this comment