Here is a program that will allow a string containing any values (0x00 to 0xff) to be saved in Global, Local, or Project data and read it back. The original problem with saving strings is that certain hex values would cause an error message or cause Codea to close when using the saveGlobalData etc commands. The 2 routines here (hexToAscii and asciiToHex) gets around that problem. hexToAscii will take 1 hex byte and convert it to 2 ASCII bytes. asciiToHex will take 2 ASCII bytes and convert them back to 1 hex byte. By converting 1 hex byte to 2 ASCII bytes allows you to save the string without problems. The only down side is the string being saved is twice the size of the original. When this program is run, it will show examples of the steps taken to convert the original string to ASCII, save the string, read it back, and convert it from ASCII back to the original. Slide the output pane all the way up to show more of the output. I added the command saveGlobalData(“str2”,nil) at the end to remove my example of str2 from your iPad.
function setup()
asciiTab={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}
str1=""
str2=""
str3=""
str4=""
--create string str1 with values from 0 to 255 (0x00 to 0xff)
for a = 0x00,0xff do
str1=str1..string.char(a)
end
--show the values and length of string str1
print("str1",string.byte(str1,1,string.len(str1)))
print("\
str1 length",string.len(str1))
--convert 1 hex byte to 2 ascii bytes
print("\
Convert 1 hex byte (str1)\
to 2 ascii bytes (str2)")
str2=hexToAscii(str1)
--show values and length of string str2
print("\
str2",str2)
print("\
str2 length",string.len(str2))
--save string str2 as global data
print("\
saving str2 as global data")
saveGlobalData("str2",str2)
--list global data
print("listing global data")
for x,y in pairs(listGlobalData()) do
print(x,y)
end
--read saved data into string str4
print("\
read global data into str4")
str4=readGlobalData("str2")
--show values and length of string str4
print("\
str4",str4)
print("\
str4 length",string.len(str4))
--convert 2 ascii bytes to 1 hex byte
print("\
Convert 2 ascii bytes (str4)\
to 1 hex byte (str3)")
str3=asciiToHex(str4)
--show values and length of string str3
print("\
str3",string.byte(str3,1,string.len(str3)))
print("\
str3 length",string.len(str3))
saveGlobalData("str2",nil) -- remove str2 from global data
end
function hexToAscii(in1) --convert 1 hex byte to 2 ascii bytes
local out1=""
for x=1,string.len(in1) do
z=string.byte(in1,x,x)
a=math.floor(z/16)
a1=asciiTab[a+1]
b=z%16
b1=asciiTab[b+1]
out1=out1..a1..b1
end
return(out1)
end
function asciiToHex(in1) --convert 2 ascii bytes to 1 hex byte
local out1=""
for x=1,string.len(in1),2 do
a=string.sub(in1,x,x)
a1=string.byte(a)
if a1>57 then
a1 = a1 - 87
else
a1 = a1 - 48
end
b=string.sub(in1,x+1,x+1)
b1=string.byte(b)
if b1>57 then
b1 = b1 - 87
else
b1 = b1 - 48
end
z=a1*16+b1
out1=out1..string.char(z)
end
return(out1)
end
function draw()
background(40,40,50)
end