How to serialize a variable in VimScript?

I want to save some random letter lyrics, say:

let dico = {'a' : [[1,2], [3]], 'b' : {'in': "str", 'out' : 51}}

to file. Is there any reasonable way to do this? Something I could use, for example:

call SaveVariable(dico, "safe.vimData")
let recover = ReadVariable("safe.vimData")

Or should I create something with text files only?

+4
source share
2 answers

Thanks to VanLaser, I was able to implement this with the three vimScript functions string, writefileand readfile(better than source). It is not binary, but it works well :)

function! SaveVariable(var, file)
    call writefile([string(a:var)], a:file)
endfun
function! ReadVariable(file)
    let recover = readfile(a:file)[0]
    " it is so far just a string, make it what it should be:
    execute "let result = " . recover
    return result
endfun

Use it as follows:

call SaveVariable(anyvar, "safe.vimData")
let restore = ReadVariable("safe.vimData")

Thank!

+3
source

You can use the function :string(). Check them out:

let g:dico = {'a' : [[1,2], [3]], 'b' : {'in': "str", 'out' : 51}}
let str_dico = 'let g:dico_copy = ' . string(dico)
echo str_dico
execute str_dico
echo g:dico_copy

... str_dico vimscript (, writefile()), source vim .

+6

All Articles