Sourcing nvim.init does not source required Lua files - lua

I have neovim 0.7.0 running and my .vimrc is at ~/.config/nvim/init.vim
I also have the following file: ~/.config/nvim/lua/statusline.lua with one line of code:
print('message from statusline.lua')
Inside init.vim I have:
echo 'from init.vim'
lua require('statusline')
When I start nvim I get both messages printed out ('from init.vim' and 'message from statusline.lua') which is what I would expect.
When I run :source $MYVIMRC I only see 'from init.vim'. I would expect the other message ('message from statusline.lua') to appear as well.
I assume this means any changes I make in statusline.lua will not take effect when I run :source $MYVIMRC. How should I source my init.vim file plus any files it requires without closing and restarting neovim?

Either invalidate cache entry by appending return false to the end of a module.
Or don't use require at all, as you need neither cache nor path search anyway. E.g.
for k, v in ipairs(vim.fn.glob("~/.config/nvim/init.d/*.lua", false, true)) do
dofile(v)
end
P.S. Lua is not a "config tool". It is a full-featured programming language. If you don't like wasting your time by learning it properly (i.e. reading books and tutorials) you're highly suggested to use VimScript instead. It has some "dark corners" of its own but it is much better suited for writing config.

It depends on the design of your statusline.lua and knowledge about Lua' module loader system.
It looks, because i have to riddle about statusline.lua, that it nothing returns.
Because the return is going into package.loaded and same require in same session looks first there for statusline
So give following a try...
-- statusline.lua
print('message from statusline.lua')
return 'message from package.loaded.statusline'
I have tested above with...
$ lua -i
Lua 5.4.4 Copyright (C) 1994-2022 Lua.org, PUC-Rio
> require('statusline')
message from statusline.lua
message from package.loaded.statusline ./lua/statusline.lua
> require('statusline')
message from package.loaded.statusline
> require('statusline')
message from package.loaded.statusline
EDIT
Another design for doing something usefull...
-- ~.config/nvim/init.vim
lua print("init.vim")
lua dump = require("dump")
And...
-- ~/.config/nvim/lua/dump.lua
local dump = function(tab)
for key, value in pairs(tab) do
print(key, '=>', value)
end
end
return dump
Than you have a table viewer and you can see where the functions and tables come from with...
:lua dump(_G) -- The global environment table
:lua dump(vim) -- The nvim stuff (aka Module)
:lua dump(vim.api) -- The nvim API functions (aka Library)
:lua dump(jit) -- The Just In Time Compiler ;-)
:lua dump([Table Name]) -- Any table that looks interesting
:lua dump(package.loaded) -- The required or requireable stuff
Above function can be executed without defining dump first with: :lua require('dump')(_G)
So: First require loads dump.lua into package.loaded.dump and returning it and every further require returning: package.loaded.dump
If you have an sharp eye than take a look on _G.dump thats only a reference (pointer/link) to package.loaded.dump.
EDIT2
Preparing dump.lua for using it with vim.api.nvim_input()
-- ~/.config/nvim/lua/dump.lua
local dump = function(tab)
local tmp = ''
for key, value in pairs(tab) do
tmp = tmp .. ('%s %s %s\n'):format(key, '=>', value)
end
return tmp
end
return dump
Now the dump function returning a string and the output can be loaded into nvim with: :lua vim.api.nvim_input('i') vim.api.nvim_input(dump(vim.api))
Since many nvim API functions returning a table the dump function becomes handy with...

Related

Lua io.popen freezing after a while of reading a log file

I'm attempting to constantly read and parse a log file (Minecraft log file) by using io.popen in tandem with Ubuntu's tail command so that I can send some messages upon certain events.
Now, I have mostly everything working here, except one small issue. After a while of reading, the entire program just freezes.
Here is the relevant code:
-- Open the tail command, return a file handle for it.
local pop = io.popen(config.listen_command)
-- Simply read a single line, I've pulled this into its own
-- function so that if this ever needs changing I can do so
-- easily.
local function get_line()
logger:log(4, "READ LINE")
return pop:read("*l")
end
-- For each line in the log file, check if it matches any
-- of a list of patterns, return the matches and the
-- pattern information if so.
local function match_line()
local line = get_line()
logger:log(4, "Line: %s", line)
-- This all works, and I've tested that it's not freezing
-- here. I've just included it for completion of the call
-- -stack.
for event_type, data in pairs(config.message_patterns) do
for event_name, pattern in pairs(data) do
local matches = {line:match(pattern)}
if matches[1] then
return event_type, event_name, matches
end
end
end
end
-- The main loop, simply read a line and send a message
-- if there was a match.
logger:log(4, "Main loop begin.")
while true do
local event_type, event_name, matches = match_line()
-- ...
-- The rest of the code here is not relevant.
config.listen_command = "tail -F --lines=1 latest.log"
The issue is in the get_line function. After a while of reading the log file, it completely freezes on the pop:read("*l"). It prints the READ LINE message, but never prints the Line: <whatever data here> line.
This is a really strange issue that I've been getting really confused about. I've tried swapping to different distributions of Lua (Luvit, LuaJIT, Lua) and a very large amount of debugging, changing small things, rerunning, ... But I cannot think of anything that'd be causing this.
Perhaps there's something small I've missed.
So my question here is this: Why is pop:read("*l") freezing, even though more data is being outputted to the logfile? Is there a way to fix this? Perhaps to detect if the next read will freeze indefinitely, so I can try closing the popen'ed file and re-open it (or to preferably stop it happening altogether?)

Cross-platform method to get user's configuration home in Lua

The major operating systems seem to have a designated place to store configuration files.
On Linux it would be something like $HOME/.myprogram/data or $HOME/.config/myprogram/data, or perhaps a better practice would be to read $XDG_CONFIG_HOME.
On macOS it would be $HOME/.myprogram/data or $HOME/Library/Preferences/myprogram/data.
On Windows it would be %appdata%/myprogram/data.
How to get such value in a portable manner in Lua?
Check the existence condition of a variable with...
if (os.getenv('XDG_CONFIG_HOME')) then
os.execute('ls ' .. os.getenv('XDG_CONFIG_HOME'))
else -- Or: elseif (nextcondition) then
print('XDG_CONFIG_HOME', 'Not exists')
-- Maybe next check here?
end
But be aware that a user could start Lua with only that environment that Lua needs.
Like...
lua ()
{
env -i DISPLAY=:0 LANG='de_DE.UTF-8' TERM='xterm-256color' LUA_PATH='./lua/?.lua' LUA_CPATH='./lua/?.so' /usr/local/bin/lua "${#}"
}
Then check for XDG_CONFIG_HOME will allways fail.
Because above environment knows nothing about HOME, USER and XDG_CONFIG_HOME.
PS: I know a place too where my linux system saves configs/savegames or whatever
${HOME}/.local/share/

How can I reload my Neovim config written in lua with a shortcut?

I want to reload my neovim configuration files with just a couple of keystrokes instead of having to restart the app. I was able to do this when using an init.vim with the following command:
nnoremap <leader>sv <cmd>source $MYVIMRC<CR>
$MYVIMRC points correctly to my config entry point.
The problem is that I switched to using lua, and now I can't do the same. I have read the docs and tried variants of the following without success:
util.nnoremap("<leader>sv", "<cmd>luafile $MYVIMRC<CR>")
Finally, I found a solution doing this:
function load(name)
local path = vim.fn.stdpath('config') .. '/lua/' .. name .. '.lua'
dofile(path)
end
load('plugins')
load('config/mapping')
load('lsp/init')
Which is buggy and feels wrong.
Is there any way to do this? I read the example in vimpeccable, but I want to see the other available options since I would rather not install another plugin.
I know that plenary includes a function to reload modules, but I don't understand how to use it. A complete example of that would be good too since I already use plenary in my config.
I am a new Neovim user, so I guess my solution may not work for some edge cases.
This function flushes the module of current buffer:
local cfg = vim.fn.stdpath('config')
Flush = function()
local s = vim.api.nvim_buf_get_name(0)
if string.match(s, '^' .. cfg .. '*') == nil then
return
end
s = string.sub(s, 6 + string.len(cfg), -5)
local val = string.gsub(s, '%/', '.')
package.loaded[val] = nil
end
You can call it whenever you write to a buffer with this autocommand:
autocmd BufWrite *.lua,*vim call v:lua.Flush()
This way, after you execute :source $MYVIMRC it will also reload changed Lua modules.

"attempt to call global 'tonumber' (a nil value)" in Lua, embedded (in VLC)

I use VLC media player 1.1.9 on Ubuntu 11.04. I'm trying to experiment with lua extensions for VLC; so I've added the file test.lua in ~/.local/share/vlc/lua/extensions/, which has only these two lines:
fps="25.000"
frame_duration=1/tonumber(fps)
When I run vlc with verbose output for debugging, I get (edited to split on multiple lines:):
$ vlc --verbose 2
...
[0xa213874] lua generic warning: Error loading script
~/.local/share/vlc/lua/extensions/test.lua:
.../.local/share/vlc/lua/extensions/test.lua:2:
attempt to call global 'tonumber' (a nil value)
...
Now, as far as I know, tonumber as function is part of Lua5.1 proper (Lua 5.1 Reference Manual: tonumber) - and on my system:
$ locate --regex 'lua.*so.*' | head -4
/usr/lib/libipelua.so.7.0.10
/usr/lib/liblua5.1.so
/usr/lib/liblua5.1.so.0
/usr/lib/liblua5.1.so.0.0.0
... apparently I do have Lua 5.1 installed.
So, why do I get an error on using tonumber here - and how can I use this (and other) standard functions in a VLC lua extension properly?
Documentation is sparse for VLC Lua extensions to say the least but I did find an example in the github vlc repository here: https://github.com/videolan/vlc/blob/master/share/lua/extensions/VLSub.lua
Judging from that example it appears you need to supply some basic event functions for your addon for VLC to call into when certain events happen. Some of the obvious callback handlers I've noticed:
descriptor, this should return a table that contains fields describing your addon.
activate, this seems to get called when you activate it from view menubar.
deactivate, called when you deactivate the addon from view menubar.
plus a couple of other functions like close and input_change which you can guess what they're for.
From my brief testing done on VLC 2.0.8 under Win7 it appears VLC loads the lua extension using an empty sandbox environment. This is likely the reason you're getting nil for tonumber and I'm betting none of the other standard lua functions are accessible either when you try to perform computation at this global scope.
However, if I move that code into one of the event handling functions then all those standard functions are accessible again. For example:
function descriptor()
return
{
title = "Test Ext";
version = "0.1";
author = "";
shortdesc = "Testing Lua Extension";
capabilities = {};
description = "VLC Hello Test Addon";
}
end
function activate()
print "test activating"
local fps = tonumber "25.000"
local frame_duration = 1 / fps
print(frame_duration)
return true
end
-- ...
That prints out what you would expect in the console debug log. Now the documentation (what little there is) doesn't mention any of this but what's probably happening here is VLC is injecting the standard lua functions and vlc api table into the sandboxed environment when any of these event handlers get called. But during the extension loading phase, it is done in an empty sandbox environment which explains why all those lua function calls end up being nil when you try to use it at the outter most scope.
I recommend cloning the VLC source tree from github and then performing a grep on the C source that's embedding lua to see what VLC is really doing behind the scenes. Most of the relevant code will likely be here: https://github.com/videolan/vlc/tree/master/modules/lua
Probably some extension script installed in your system overwrites the function and the Lua interpreter instance is shared between all extension scripts, so you end up not being able to call the function if that script is called before yours.
As a quick workaround, Lua being dynamically typed, you can still do things like:
1 / "25.000"
and the string will be coerced to a number.
Alternatively, you can define a tonumber equivalent like:
string_to_num = function(s) return s + 0 end
This again relies on dynamic typing.

Getting return status AND program output

I need to use Lua to run a binary program that may write something in its stdout and also returns a status code (also known as "exit status").
I searched the web and couldn't find something that does what I need. However I found out that in Lua:
os.execute() returns the status code
io.popen() returns a file handler that can be used to read process output
However I need both. Writing a wrapper function that runs both functions behind the scene is not an option because of process overhead and possibly changes in result on consecutive runs. I need to write a function like this:
function run(binpath)
...
return output,exitcode
end
Does anyone has an idea how this problem can be solved?
PS. the target system rung Linux.
With Lua 5.2 I can do the following and it works
-- This will open the file
local file = io.popen('dmesg')
-- This will read all of the output, as always
local output = file:read('*all')
-- This will get a table with some return stuff
-- rc[1] will be true, false or nil
-- rc[3] will be the signal
local rc = {file:close()}
I hope this helps!
I can't use Lua 5.2, I use this helper function.
function execute_command(command)
local tmpfile = '/tmp/lua_execute_tmp_file'
local exit = os.execute(command .. ' > ' .. tmpfile .. ' 2> ' .. tmpfile .. '.err')
local stdout_file = io.open(tmpfile)
local stdout = stdout_file:read("*all")
local stderr_file = io.open(tmpfile .. '.err')
local stderr = stderr_file:read("*all")
stdout_file:close()
stderr_file:close()
return exit, stdout, stderr
end
This is how I do it.
local process = io.popen('command; echo $?') -- echo return code of last run command
local lastline
for line in process:lines() do
lastline = line
end
print(lastline) -- the return code is the last line of output
If the last line has fixed length you can read it directly using file:seek("end", -offset), offset should be the length of the last line in bytes.
This functionality is provided in C by pclose.
Upon successful return, pclose() shall return the termination status
of the command language interpreter.
The interpreter returns the termination status of its child.
But Lua doesn't do this right (io.close always returns true). I haven't dug into these threads but some people are complaining about this brain damage.
http://lua-users.org/lists/lua-l/2004-05/msg00005.html
http://lua-users.org/lists/lua-l/2011-02/msg00387.html
If you're running this code on Win32 or in a POSIX environment, you could try this Lua extension: http://code.google.com/p/lua-ex-api/
Alternatively, you could write a small shell script (assuming bash or similar is available) that:
executes the correct executable, capturing the exit code into a shell variable,
prints a newline and terminal character/string onto standard out
prints the shell variables value (the exit code) onto standard out
Then, capture all the output of io.popen and parse backward.
Full disclosure: I'm not a Lua developer.
yes , your are right that os.execute() has returns and it's very simple if you understand how to run your command with and with out lua
you also may want to know how many variables it returns , and it might take a while , but i think you can try
local a, b, c, d, e=os.execute(-what ever your command is-)
for my example a is an first returned argument , b is the second returned argument , and etc.. i think i answered your question right, based off of what you are asking.

Resources