8 Only Saves Tables, Numbers and Strings
9 Insides Table References are saved
10 Does not save Userdata, Metatables, Functions and indices of these
11 ----------------------------------------------------
12 table.save( table , filename )
14 on failure: returns an error msg
16 ----------------------------------------------------
17 table.load( filename or stringtable )
19 Loads a table that has been saved via the table.save function
21 on success: returns a previously saved table
22 on failure: returns as second argument an error msg
23 ----------------------------------------------------
25 Licensed under the same terms as Lua itself.
28 -- declare local variables
29 --// exportstring( string )
30 --// returns a "Lua" portable version of the string
31 local function exportstring( s )
32 return string.format("%q", s)
35 --// The Save Function
36 function table.save( tbl,filename )
37 local charS,charE = " ","\n"
38 local file,err = io.open( filename, "wb" )
39 if err then return err end
41 -- initiate variables for save procedure
42 local tables,lookup = { tbl },{ [tbl] = 1 }
43 file:write( "return {"..charE )
45 for idx,t in ipairs( tables ) do
46 file:write( "-- Table: {"..idx.."}"..charE )
47 file:write( "{"..charE )
50 for i,v in ipairs( t ) do
52 local stype = type( v )
54 if stype == "table" then
56 table.insert( tables, v )
59 file:write( charS.."{"..lookup[v].."},"..charE )
60 elseif stype == "string" then
61 file:write( charS..exportstring( v )..","..charE )
62 elseif stype == "number" then
63 file:write( charS..tostring( v )..","..charE )
67 for i,v in pairs( t ) do
68 -- escape handled values
69 if (not thandled[i]) then
72 local stype = type( i )
74 if stype == "table" then
76 table.insert( tables,i )
79 str = charS.."[{"..lookup[i].."}]="
80 elseif stype == "string" then
81 str = charS.."["..exportstring( i ).."]="
82 elseif stype == "number" then
83 str = charS.."["..tostring( i ).."]="
89 if stype == "table" then
91 table.insert( tables,v )
94 file:write( str.."{"..lookup[v].."},"..charE )
95 elseif stype == "string" then
96 file:write( str..exportstring( v )..","..charE )
97 elseif stype == "number" then
98 file:write( str..tostring( v )..","..charE )
103 file:write( "},"..charE )
109 --// The Load Function
110 function table.load( sfile )
111 local ftables,err = loadfile( sfile )
112 if err then return _,err end
113 local tables = ftables()
114 for idx = 1,#tables do
116 for i,v in pairs( tables[idx] ) do
117 if type( v ) == "table" then
118 tables[idx][i] = tables[v[1]]
120 if type( i ) == "table" and tables[i[1]] then
121 table.insert( tolinki,{ i,tables[i[1]] } )
125 for _,v in ipairs( tolinki ) do
126 tables[idx][v[2]],tables[idx][v[1]] = tables[idx][v[1]],nil