In Vimscript, the script scope s:
can be used to avoid name clashes between plugins. I'm writing a Vim plugin in Lua, and I noticed Vim runs all of its Lua code in a common scope. This means my plugin's Lua functions are visible to any other plugin using Lua, and seems like a name clash waiting to happen.
Although my example involves Lua, this question also applies when developing Vim plugins in Python or Ruby. I could just prefix all of my Lua functions with the plugin name, but is there more a reliable/standard way to encapsulate Vim plugin code when using these languages?
I don't have much experience with lua, but for python things are also similar, especially if you use 'pyfile' (luafile is probably very similar). The better, recommended approach, especially for python would look something like this :
if !exists('g:audiobox_py_loaded')
python import sys, vim
python if vim.eval('expand("<sfile>:p:h")') not in sys.path:
\ sys.path.append(vim.eval('expand("<sfile>:p:h")'))
python import audiobox
endif
This way, even if you have top level functions in the file audiobox.py, they will get namespaced in a way to 'audiobox' and hence can now be accessed via audiobox. I am sure similiar idioms should be available for lua as well.
For my plugin AudioBox, which I built in my spare time only to learn how I might be able to interface using python, I took that to the next level and wrapped my needed functionality into a class and exposed an object of the same through a setup() method. You can have a look at the code to get a better idea.
NOTE: I am not a python expert by any means so don't judge my code, this was more of a hobby project :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With