Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local function serializeImpl( t, tTracking, sIndent )
- local sType = type(t)
- if sType == "table" then
- t = getmetatable( t ).origin
- if tTracking[t] ~= nil then
- error( "Cannot serialize table with recursive entries", 0 )
- end
- tTracking[t] = true
- if next(t) == nil then
- -- Empty tables are simple
- return "{}"
- else
- -- Other tables take more work
- local sResult = "{\n"
- local sSubIndent = sIndent .. " "
- local tSeen = {}
- for k,v in ipairs(t) do
- tSeen[k] = true
- sResult = sResult .. sSubIndent .. serializeImpl( v, tTracking, sSubIndent ) .. ",\n"
- end
- for k,v in pairs(t) do
- if not tSeen[k] then
- local sEntry
- if type(k) == "string" and string.match( k, "^[%a_][%a%d_]*$" ) then
- sEntry = k .. " = " .. serializeImpl( v, tTracking, sSubIndent ) .. ",\n"
- else
- sEntry = "[ " .. serializeImpl( k, tTracking, sSubIndent ) .. " ] = " .. serializeImpl( v, tTracking, sSubIndent ) .. ",\n"
- end
- sResult = sResult .. sSubIndent .. sEntry
- end
- end
- sResult = sResult .. sIndent .. "}"
- return sResult
- end
- elseif sType == "string" then
- return string.format( "%q", t )
- elseif sType == "number" or sType == "boolean" or sType == "nil" then
- return tostring(t)
- else
- error( "Cannot serialize type "..sType, 0 )
- end
- end
- local function serialize( t )
- local tTracking = {}
- return serializeImpl( t, tTracking, "" )
- end
- local function makeInternalSaving( tbl, save )
- for k, v in pairs( tbl ) do
- if type( v ) == "table" then
- tbl[ k ] = makeInternalSaving( v )
- end
- end
- return setmetatable( {}, {
- __index = tbl,
- __newindex = function( self, key, value )
- if type( value ) == "table" then
- tbl[ key ] = makeInternalSaving( value, save )
- else
- tbl[ key ] = value
- end
- save()
- end,
- __len = function() return #tbl end,
- __metatable = { origin = tbl },
- } )
- end
- function makeAutoSaving( tbl, file )
- for k, v in pairs( tbl ) do
- if type( v ) == "table" then
- tbl[ k ] = makeInternalSaving( v )
- end
- end
- local savable = {}
- local function save()
- local f = fs.open( file, "w" )
- f.write( serialize( savable ) )
- f.close()
- end
- return setmetatable( savable, {
- __index = tbl,
- __newindex = function( self, key, value )
- if type( value ) == "table" then
- tbl[ key ] = makeInternalSaving( value, save )
- else
- tbl[ key ] = value
- end
- save()
- end,
- __len = function( ... ) return #tbl end,
- __metatable = { origin = tbl },
- __call = function() return tbl end,
- } )
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement