Icon representing a recipe

Recipe: Cooks Only: Save/Load snips

created by Jean-Bob

Profile


Name
Cooks Only: Save/Load snips
ID
45154
Shared with
Public
Parent
None
Children
None
Created on
January 10, 2013 at 03:03 AM UTC
Updated on
January 10, 2013 at 03:03 AM UTC
Description

A set of functions to concatenate an array in a string and restore such a "stringed" array. See comments.

Best for


Code


function tobool(val) local res if type(val)=='number' then if val==0 then res=false elseif val==1 then res=true else res=nil end elseif type(val)=='string' then if val=='false' then res=false elseif val=='true' then res=true else res=nil end else res=nil end return res end function SetCleanType(val) if tonumber(val)~=nil then return tonumber(val) elseif tobool(val)~=nil then return tobool(val) else return val end end function ConcatArray(array, depth) local s='' local depth=depth or 1 local sep={' ',',','|'} for key, val in pairs(array) do if type(val)=='table' then s=s..key..sep[depth+1]..ConcatArray(val, depth+1)..sep[depth] else s=s..key..':'..tostring(val)..sep[depth] end end return s:sub(1,#s-1) end function RebuildArray(str, depth) local arr={} local depth=depth or 1 local sep={' ',',','|','%^'} local subpat='' for i=1, depth do subpat=subpat..sep[i] end pattern="([^"..subpat.."]+)" for entity in string.gmatch(str, pattern) do if entity:find(sep[depth+1]) then key=string.match(entity,"([^"..sep[depth+1].."]+)") local len=#key key=SetCleanType(key) arr[key]=RebuildArray(entity:sub(len+2,#entity), depth+1) else key, val=string.match(entity,"([%w]+):([^"..subpat.."]+)") arr[SetCleanType(key)]=SetCleanType(val) end end return arr end

Comments


Crashguard303 Lv 1

Dirty? Why?
PHP does the same, as it can paste variable-contents into the browser's address bar and fetch them back later (the $_GET-array), hehe ;)
It can also do this with HTML-formular-entries (the $_POST-array)
Moreover, it can move sign-separated strings back to an array via explode()

So, it's something similar you are doing here with Lua.
Nice work!