Has anyone got a good class that will flatten a table in to a string and vice versa? Thanks.
I blogged about one here
http://coolcodea.wordpress.com/2013/03/31/19-lessons-from-a-simple-board-game-part-2/
As part of an undo feature for a game. It handles a 2D table.
Thanks ignatz but I didn’t really go that route, I have one problem which is fixable so I’m going to root around for a solution, nice one anyone
I’d say use json (JavaScript Object Notation). Simply use json.encode(tbl) json.decode(str). It’s what AutoGist uses.
dkjson - https://gist.github.com/briarfox/34278e85f9767b653f2f
doesn’t that require linking to a big library file? If so, seems like overkill
@Diablo76 - yep, I know it can be done compactly. I’ve done it myself.
That’s why I was querying the use of JSON.
@Ignatz yeah good point but I’ve just been using json as a library a lot. Maybe It’s time to find something more compact
. @Luatee I’m not sure what kind of table you’re creating, so I created a mixed example for my table. The example table (tab1) has numeric and alphanumeric keys. It gets saved to a string (str) and then another table (tab2) is created from the string. I don’t know if this will help or not.
function setup()
tab1={}
tab1=createExampleTable()
printTable(tab1)
str=tableToString(tab1)
print(str)
tab2={}
stringToTable(str,tab2)
printTable(tab2)
end
function createExampleTable()
print("\
------ create example table ------")
t={}
for z=1,10 do
table.insert(t,"qwerty"..z) -- numeric key
t["qq+q"..z.."aa,aa"]="qwe-rty"..z -- alphanumeric key
end
return(t)
end
function tableToString(t)
print("\
------ table to string ------")
s=""
for a,b in pairs(t) do
s=s..a.."*"..b.."*" -- asterisk seperators between key and values
end
return(s)
end
function stringToTable(s,t)
print("\
------ string to table ------")
key=true
c=1
while true do
s1,e1=string.find(s,"*",c) -- find asterisk seperator
if s1==nil then
break -- end of string
else
val=string.sub(s,c,s1-1) -- get key or value
if key then
k=val -- val = key
else
t[k]=val -- val = value
end
key=not key
c=e1+1
end
end
end
function printTable(t)
print("\
------ print table ------")
for a,b in pairs(t) do
print(a,"=",b)
end
end
Thanks dave but its alright I’ve overcome the problem I was facing with the string loading but its done now
You could also check out: http://codeatuts.blogspot.com.au/2012/09/tutorial-16-convert-string-to-table-and.html