Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --Concise Object Notation - SpiderString - TheINCGI
- local CON = {}
- local function exportObj( file, obj, indent, name )
- indent = indent or 0
- file.write((" "):rep(indent)..name)
- if type(obj)~="table" then
- file.writeLine((type(name)=="number" and " = " or ": ").. (type(obj)=="string" and ('"'..obj..'"') or tostring(obj)))
- else
- file.writeLine("")
- for k,v in pairs( obj ) do
- exportObj( file, v, indent+1, k )
- end
- end
- end
- local function importObj( file, out, line, indents )
- if not line then return end
- indents = indents or 0
- local name = line:gsub("^ *",""):gsub(" *$","")
- local t;
- if not name:match"^.+ ?[=:]" then
- t = {}
- out[ name ] = t
- if file.available() <= 0 then return end
- line = file.readLine():gsub(" *$","") --trim end
- else
- t = out
- line = " "..line
- end
- while line and #line:gmatch(" *")() / 2 == indents + 1 do
- local m = line:match"^ *%w+ ?[:=] "
- if m then --any spaces, var name, and a : space
- local keyIsNum = m:match"^ *-?%w+ =" and true or false
- local pName = line:match"^ *(-?%w+) ?[:=]"
- local v = line:sub(#m+1)
- local s = v:match"^%\"(.+)%\""
- if s then
- v = s
- else
- if v=="true" then
- v = true
- elseif v=="false" then
- v = false
- else
- local n = tonumber(v)
- if not n then error(string.format("Format exception for field '%s' with value '%s'",pName,v)) end
- v = n
- end
- end
- t[ keyIsNum and tonumber(pName) or pName ] = v
- line = file.readLine():gsub(" $","")
- else
- line = importObj( file, t, line, indents+1 )
- end
- end
- return line
- end
- function CON.import( path )
- local out = {}
- local file = filesystem.open( path, "r" )
- local line = file.readLine()
- while file.available() > 0 do
- line = importObj( file, out, line )
- end
- file.close()
- return out
- end
- function CON.export( path, obj )
- assert( type(path)=="string", "String path expected, got "..type(path) )
- assert( type(obj)=="table", "Table expected, got "..type(obj) )
- local file = filesystem.open( path, "w" )
- for k,v in pairs(obj) do
- --if type(v)=="table" then
- exportObj( file, v, 0, k )
- --end
- end
- file.close()
- end
- local test = {
- x = {
- p={},
- 1,2,3
- },
- y = {
- h="i"
- },
- z= {56},
- w= {"ok", toast="most"},
- l=100
- }
- CON.export( "test.con", test )
- log( CON.import( "test.con" ) )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement