如何在VimScript中序列化变量?

时间:2015-07-10 19:24:22

标签: file serialization vim binary save

我希望保存一个随机的Vim词典,让我们说:

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

到一个文件。有一个聪明的方法来做到这一点?我可以使用的东西:

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

或者我应该仅用文本文件构建一些东西吗?

2 个答案:

答案 0 :(得分:6)

您可以充分利用:string()功能。测试这些:

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文件。< / p>

答案 1 :(得分:4)

感谢VanLaser(干杯),我已经能够使用stringwritefilereadfile来实现这些功能。这不是二进制序列化,但它运行良好:)

function! SaveVariable(var, file)
    " turn the var to a string that vimscript understands
    let serialized = string(a:var)
    " dump this string to a file
    call writefile([serialized], a:file)
endfun

function! ReadVariable(file)
    " retrieve string from the file
    let serialized = readfile(a:file)[0]
    " turn it back to a vimscript variable
    execute "let result = " . serialized
    return result
endfun

以这种方式使用它们:

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

享受!