Cross-platform method to get user's configuration home in Lua - 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/

Related

Device depending neovim configuration

I have a short question.
Currently, I am spending (way too much time) modding my neovim setup.
I have multiple devices where I use my setup and sync those with git (second-best feature, after restoring my config every time I destroy everything) but there are some small differences in my configuration like plugins, which I don't need on my on-the-way-notebook.
Is there any way to differ in the lua configuration, on which device is currently running neovim?
Sure, multi-branching would be a way, but I'd like a more comfortable way.
Thanks for helping
You could use hostname to determine your device and use it to create configuration with conditions.
Lua code to get hostname :
local function get_hostname()
local f = io.popen ("/bin/hostname")
local hostname = f:read("*a") or ""
f:close()
hostname =string.gsub(hostname, "\n$", "")
return hostname
end
Neovim configuration :
if get_hostname() == "foo" then
do_something
else
do_otherthing
end

Lua script pc to sleep

So i got a new keyboard wit hG-keys. (hotkeys) And i'm not familiar with lua...
So could anybody give me a very simple command that sets my pc to sleep? please?
if gkey == 7 and mkey == 1 then
if event == "G_PRESSED" then
end
end
gkeys
so gkey is the key that is pressed, and mkey is the set it uses. i can have up to 54 differint scripts/macro's.
I want to know what i have to put after the last 'then' so my pc goes to sleep.
thx ahead
edit 1:
got this:
if gkey == 1 and mkey == 3 then
if event == "G_PRESSED" then
execute("rundll32.exe powrprof.dll,SetSuspendState 0,1,0");
end
end
error is: [string "LuaVM"]:40: attempt to call global 'execute'(a nil value)
and with os.execute i get this error:
[string "LuaVM"]:40: attempt to index global 'os'(a nil value)
final answer: not possible with gseries keyboard. use a shortcut
Given the reference to G-keys and the G_PRESSED in your code snippet, I am assuming you have one of the Logitech G-Series keyboards. These keyboards can be programmed so that certain keys run Lua scripts using a custom Lua 5.1 interpreter. The documentation is included with Logitech's Gaming Software program.
According to the documentation, only some of the standard library functions are supported: the string, math and table are available. However, the io, os and debug libraries are not available.
So I doubt you'll be able to make your PC go to sleep.
EDIT in response to OP edit: the Lua library you have access to has the os library removed, so you're probably not going to be able to make your computer sleep directly.
There might be an indirect way to do this by writing something that listens for debugging messages, which you can generate with OutputDebugMessage. There's a Team Speak plugin that does this. But it's probably beyond your programming ability right now and far beyond the scope of a Stackoverflow post to explain.
You can use os.execute to run an executable from Lua.
If you google "Windows sleep command line" you'll get another Stackoverflow post which shows two ways of doing it. One requires that you turn hibernation off, the other requires that you download an additional utility (PsShutdown).
Assuming you've downloaded PsShutdown and put it somewhere in your PATH, then you can use the following to sleep the computer:
os.execute('psshutdown -d -t 0')

open web browser using lua in a vlc extension

I am writing a VLC extension in which i would like to open some url in a web browser( in lua of course ). So far, I have not been able to find any relevant code for opening the web browser from a lua script. Is there any way in which I can perform this task (say for example a google search of the file playing)?
I am able to create a link to the url using a dialog box, but i would like to skip this step and make it open without any user input.
I am a beginner to lua and to making VLC extentions( just started a few days back ) and have been trying things out since then.
The exact command varies between operating systems:
On Windows:
start http://example.com/
On *nix (most portable option):
xdg-open "http://example.com/"
On OSX:
open http://example.com/
The following Lua sample should work on Windows, Linux, and OSX (Though I cannot test OSX).
It works by first checking Lua's package.config for the \\ directory separator (which, afaik, is only used on windows). That should only leave us with OSes that support uname. Then I take a flying leap and assume that Mac will identify as 'Darwin', and thus anything that doesn't is *nix.
Obviously, this is somewhat less than exhaustive.
-- Attempts to open a given URL in the system default browser, regardless of Operating System.
local open_cmd -- this needs to stay outside the function, or it'll re-sniff every time...
function open_url(url)
if not open_cmd then
if package.config:sub(1,1) == '\\' then -- windows
open_cmd = function(url)
-- Should work on anything since (and including) win'95
os.execute(string.format('start "%s"', url))
end
-- the only systems left should understand uname...
elseif (io.popen("uname -s"):read'*a') == "Darwin" then -- OSX/Darwin ? (I can not test.)
open_cmd = function(url)
-- I cannot test, but this should work on modern Macs.
os.execute(string.format('open "%s"', url))
end
else -- that ought to only leave Linux
open_cmd = function(url)
-- should work on X-based distros.
os.execute(string.format('xdg-open "%s"', url))
end
end
end
open_cmd(url)
end

Reboot a System through Lua Script

I need to reboot System through a Lua Script.
I need to write some string before the Reboot happens and need to write a string in a Lua
script once the Reboot is done.
Example :
print("Before Reboot System")
Reboot the System through Lua script
print("After Reboot System")
How would I accomplish this?
You can use os.execute to issue system commands. For Windows, it's shutdown -r, for Posix systems it's just reboot. Your Lua code will therefore look like this:
Be aware that part of the reboot command is stopping active programs, like your Lua script. That means that any data stored in RAM will be lost. You need to write any data you want to keep to disk, using, for instance, table serialization.
Unfortunately, without more knowledge of your environment, I can't tell you how to call the script again. You could be able to append a call to your script to the end of ~/.bashrc or similar.
Make sure that loading this data and starting at a point after you call your reboot function is the first thing that you do when you come back! You don't want to get stuck in an endless reboot loop where the first thing your computer does when it turns on is to turn itself off. Something like this should work:
local function is_rebooted()
-- Presence of file indicates reboot status
if io.open("Rebooted.txt", "r") then
os.remove("Rebooted.txt")
return true
else
return false
end
end
local function reboot_system()
local f = assert(io.open("Rebooted.txt", "w"))
f:write("Restarted! Call On_Reboot()")
-- Do something to make sure the script is called upon reboot here
-- First line of package.config is directory separator
-- Assume that '\' means it's Windows
local is_windows = string.find(_G.package.config:sub(1,1), "\\")
if is_windows then
os.execute("shutdown -r");
else
os.execute("reboot")
end
end
local function before_reboot()
print("Before Reboot System")
reboot_system()
end
local function after_reboot()
print("After Reboot System")
end
-- Execution begins here !
if not is_rebooted() then
before_reboot()
else
after_reboot()
end
(Warning - untested code. I didn't feel like rebooting. :)
There is no way to do what you are asking in Lua. You may be able to do this using os.execute depending on your system and set up but Lua's libraries only include what is possible in the standard c libraries which does not include operating system specific functionality like restart.

How can I determine the OS of the system from within a Lua script?

Ok I need to determine the system's OS from a Lua script, but Lua as such has no API for this, so I use os.getenv() and query enviromental variables. On Windows checking the enviromental variable "OS" gives me the name of the system's OS, but is there some variable that exists on both Windows and most flavors of Unix that can be checked?
You can try package.config:sub(1,1). It returns the path separator, which is '\\' on Windows and '/' on Unixes...
On a Unix system, try os.capture 'uname' where os.capture is defined below:
function os.capture(cmd, raw)
local f = assert(io.popen(cmd, 'r'))
local s = assert(f:read('*a'))
f:close()
if raw then return s end
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
This will help on all flavors of unix and on Mac OSX.
If it fails, you might be on a Windows system? Or check os.getenv 'HOME'.
When lua is compiled, it is configured slightly differently depending on what operating system it is compiled for.
Many of the strings which are set in the 'package' module can thus be used to distinguish which system it was compiled for.
For instance, when lua loads C-based modules which are distributed as dynamic libraries, it has to know the extension used for those libraries, which is different on each OS.
Thus, you can use a function like the following to determine the OS.
local BinaryFormat = package.cpath:match("%p[\\|/]?%p(%a+)")
if BinaryFormat == "dll" then
function os.name()
return "Windows"
end
elseif BinaryFormat == "so" then
function os.name()
return "Linux"
end
elseif BinaryFormat == "dylib" then
function os.name()
return "MacOS"
end
end
BinaryFormat = nil
I guess that if you just need Windows/Unix detection, you could check the filesystem for the existence of /etc or /bin or /boot directories. Aditionally, if you need to know which distro is it, most Linux distros have a little file in /etc showing the distro and version, sadly they all name it differently.
Unixes should have the $HOME variable (while Windows doesn't have that), so you can check it (after checking the OS variable is empty).
FWIW, the simplest function I can think of:
function MyScript:OS()
return package.config:sub(1,1) == "\\" and "win" or "unix"
end

Resources