In my init.lua I have:
require("base") -- general settings
require("highlights") -- colourscheme and other highlights
require("keymaps") -- keymaps
require("plugins") -- plugins
require("hop") -- hop
require("bootstrap") -- packer auto-installer
print("✔ nvim loaded")
print(vim.inspect(package.loaded['hop']))
In base.lua, I have:
local g = vim.g
local o = vim.o
local opt = vim.opt
-- Map <leader> to space
g.mapleader = ' '
g.maplocalleader = ' '
In keymaps.lua, I have:
map("n", "<leader>w", ":HopWord<cr>")
map("n", "<leader>W", ":HopWordMW<cr>")
map("n", "f", ":HopChar1<cr>")
map("n", "F", ":HopChar1CurrentLine<cr>")
In plugins.lua, I have:
-- ...packer setup
local status, packer = pcall(require, "packer")
if not status then
return
end
return packer.startup(function(use)
use {
'phaazon/hop.nvim',
branch = 'v2', -- optional but strongly recommended
-- config = [[require('hop')]],
-- config = function()
-- -- you can configure Hop the way you like here; see :h hop-config
-- require'hop'.setup {}
-- end
}
if packer_bootstrap then
require("packer").sync()
end
end)
And finally, in hop.lua I have:
local setup, hop = pcall(require, "hop")
if not setup then
return
end
hop.setup { keys = "etovxqpdygfblzhckisuran" }
When I load vscode, I see the following output:
✔ nvim loaded
true
nil
The true is from the init.lua and means that hop was loaded, however, when I then press <space>w, I get the error:
E492: Not an editor command: HopWord
which means the hop commands did not load? Please help. I would like an easymotion style navigation flow for vscode neovim where it annotates places to jump to after pressing the spacebar.
Look at my response this ticket. It seems to work native without much configuration other than binding keybinds as hop does not configure any by default.
Related
Hello I am making a roblox LUA script and I cant figure out how to make the script stop after a if sentence. Here my code.
if not newPlayer:GetRankInGroup(workspace.CoreValues.GroupID.Value) then
teamName = "Civilian"
(STOP)
end
Depending on how you structure your code, you could simply return.
local shouldEscape = true
if shouldEscape then
return
end
print("This line won't get hit")
But if you have set up event listeners, this won't stop those from firing. You'll need to clean those up, disable the Script, or delete the Script.
-- connect to a signal as an example
local connection = game.Players.PlayerAdded:Connect(function(player)
-- if the Script is still enabled, this line will print
print("Player Added : " .. player.Name)
end
local shouldEscape = true
if shouldEscape then
-- disable the script
script.Disabled = true
-- OR : disconnect the signals
--connection:Disconnect()
-- OR : delete the script entirely
--script:Destroy()
-- escape so that no other lines execute
return
end
print("This line won't get hit")
It's me again
I'm trying to make a Terminal program in Lua since it's my best language I know, I'm making the calculator program in it and I'm trying to make it so if the user types "exit" the program will restart and will go back to the terminal, but I don't know how to reset the program through the code. if anyone can help that be deeply appreciated.
This is the code:
io.write("Terminal is starting up --- done!")
io.write("Making sure everything works --- Done!")
cmd = io.read()
io.write(">")
if cmd == "" then
io.write(">\n")
end
if cmd == "cal"then
io.write("Calculator Terminal Program v1.0")
io.write("what operation?/n")
op = io.read()
if op == "exit"then
io.write("Exiting")
end
end
To answer your question directly, I don't think it's possible to "restart the program". However, by taking advantage of loops, you can achieve the same result.
For instance, this code probably does what you want:
print('Terminal is starting up --- done!')
print('Making sure everything works --- Done!')
repeat
io.write('>')
cmd = io.read()
if cmd == 'cal' then
print('Calculator Terminal Program v1.0')
repeat
io.write('Operation: ')
op = io.read()
until op == 'exit'
print('Exiting')
elseif cmd == 'command' then
--another command
else
print('Unknown command.')
end
until cmd == 'exit'
Other tips:
You should take advantage of elseif instead of writing multiple separate if statements to improve readability.
Consider using the print function when you want a new line after writing some text for a better Terminal experience. You could also use io.write('\n').
You probably want os.exit(), which terminates the entire program.
i think this might work through creative use of load() and coroutines
this gonna stop restarting itself when 3 total error has occured
if innerProgram == nil then --innerProgram will set to true when it load itself
local filename = nil
local errorLimit = 3 --Change this to any value to enable this code to restart itself when error occur until this amount of time set zero or below to exit instantly when error occur
local errors = 0
local filename = function()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("^.*/(.*)") or str
end
filename = filename()
local src_h = io.open(filename, "r") --open in read mode
local src = src_h:read("*a")
src_h:close()
local G = _G
local quit = false --set true when you want to exit instead restart
local code = nil
local request = false
local restart = false --set true when you want restart
local program
local yield = coroutine.yield --Incase when coroutine get removed in your calculator code for no reason
local running = coroutine.running
local exit = os.exit
function G.restart()
restart = true --Always refer to restart variable above
request = true
yield() --Always refer to yield above
end
function G.os.exit(exitcode) --Replace os.exit with this
quit = true --Always refer to quit variable above
reuqest = true
code = exitcode or nil
yield() --Always refer to yield above
end
function G.coroutine.yield()
if running() == program and request == false then --Emulating coroutine.yield when it not run inside coroutine
error("attempt to yield from outside a coroutine")
end
end
G.innerProgram = true --So the inner program not keep loading itself forever
function copy(obj, seen)
if type(obj) ~= 'table' then return obj end --got from https://stackoverflow.com/questions/640642/how-do-you-copy-a-lua-table-by-value for us to clone _G variable without reference to original _G thus we can do total restart without using same _G
if seen and seen[obj] then return seen[obj] end
local s = seen or {}
local res = setmetatable({}, getmetatable(obj))
s[obj] = res
for k, v in pairs(obj) do res[copy(k, s)] = copy(v, s) end
return res
end
print("Loading "..filename)
program = coroutine.create(load(src, filename, "bt", copy(G)))
while errors < errorLimit do
restart = false
local status, err = coroutine.resume(program)
if restart == true then
print("Restarting...")
program = coroutine.create(load(src, filename, "bt", copy(G)))
--Put errors = errors + 1 if you want errors counter to reset every time the program request restart
end
if status == false and restart ~= true then
print(filename.." errored with "..err.."\nRestarting...")
program = coroutine.create(load(src, filename, "bt", copy(G)))
errors = errors + 1
elseif restart ~= true then
print(filename.." done executing.")
exit()
end
end
return
else
innerProgram = nil --Nil-ing the variable
end
Features
Auto exit when 3 total errors has occur (configure errorLimit variable)
_G is not shared (same _G as start of the program but not linked with the actual _G)
Emulating yielding outside of coroutine
Replaced os.exit so it yield then the self-loader run the os.exit
How to use
put the code i give above to very first line of your code
Feature Number 1 and 3 test
it error with the a content the value will be different in each error restart
if a == nil then --Only set a when a equal nil so if _G was shared the error value will be same
a = math.random() --Set global a to a random value
end
error(a) --Error with number a
os.exit()
I'm having a problem where I can do every single function in a command line version of lua however, when I run the program it won't throw any errors it just ends.I'm not sure how to diagnose this but I have tried getting an error to be thrown a couple times for different things and it will error and print the error.
power = peripheral.wrap("bottom")
mon = peripheral.wrap("top")
x,y = mon.getSize()
clearTerm = function()
term.clear()
term.setCursorPos(1,1)
end
clearBoth = function()
clearMon()
clearTerm()
end
intLen = function(bar)
tab = tostring(bar)
tab = string.len(tab)
return tab
end
checkPower = function()
total = power.getMaxEnergyStored()
local til = intLen(total)
local yy = math.floor(y/2)
local tol = math.floor(x-til)
mon.setCursorPos(yy+0,tol/2)
for z=1,til do mon.write("-") end
mon.setCursorPos(yy-1,tol/2)
mon.write(total)
while true do
current = power.getEnergyStored()
local cil = intLen(current)
local col = math.floor(x-cil)
mon.setCursorPos(yy+1,col/2)
mon.write(current)
sleep(1)
end
end
I'll leave a link to the pastebin of the full program here too.
First of all, you can add some outputs to your code. Just add stuff like
print "1" -- debug output
...
print "2" -- debug output
...
-- don't forget to remove these after you're done debugging!
to your code and see how many of them you see when running the program, this way you can narrow down when exactly the program crashes.
Also, I cannot find where the function clearMon() is defined, might that be source the problem, or is it defined elsewhere?
Let's say I'm working with a lua library I installed using luarocks, and I want to see the definition of a function from that library. In ipython in could use
??function_name
to see the definition in the terminal, in matlab I could use
which function_name
then use my editor to look at the path returned by which. How could I do something similar to find the function definition for a lua library?
In 'plain' Lua/JIT, you can say debug.getinfo( func ) and will get a table containing (among others) the fields short_src, source and linedefined.
For Lua functions, short_src will be the filename or stdin if it was defined in the REPL. (source has a slightly different format, filenames are prefixed with an #, a = prefix is used for C functions or stuff defined interactively, and for loaded functions, it will be the actual string that was loaded.)
You can pack that up in a function like
function sourceof( f )
local info = debug.getinfo( f, "S" )
return info.short_src, info.linedefined
end
or maybe even start an editor and point it there, e.g. (for vim)
function viewsource( f )
-- get info & check it's actually from a file
local info = debug.getinfo( f, "S" )
local src, line = info.source, info.linedefined
if src == "=[C]" then return nil, "Is a C function." end
local path = src:match "^#(.*)$"
if path then
-- start vim (or an other editor if you adapt the format string)
return os.execute( ("vim -fR %q +%d"):format( path, line ) )
end
return nil, "Was defined at run time."
end
And just for fun, here's yet another version that returns the code if it can find it somewhere. (This will also work for functions that have been generated at run time, e.g. by calling load, and where no source file exists. You could also work in the other direction by dumping the loaded snippet into a temp file and opening that…)
-- helper to extract the source block defining the function
local function funclines( str, line1, lineN, filename )
-- if linedefined / lastlinedefined are 0, this is the main chunk's function
if line1 == 0 and lineN == 0 then
filename = filename and filename.." (main chunk)"
or "(chunk defined at runtime)"
return "-- "..filename.."\n"..str
end
-- add line info to file name or use placeholder
filename = filename and filename..":"..line1 or "(defined at runtime)"
-- get the source block
local phase, skip, grab = 1, line1-1, lineN-(line1-1)
local ostart, oend -- these will be the start/end offsets
if skip == 0 then phase, ostart = 2, 0 end -- starts at first line
for pos in str:gmatch "\n()" do
if phase == 1 then -- find offset of linedefined
skip = skip - 1 ; if skip == 0 then ostart, phase = pos, 2 end
else -- phase == 2, find offset of lastlinedefined+1
grab = grab - 1 ; if grab == 0 then oend = pos-2 ; break end
end
end
return "-- "..filename.."\n"..str:sub( ostart, oend )
end
function dumpsource( f )
-- get info & line numbers
local info = debug.getinfo( f, "S" )
local src, line, lastline = info.source, info.linedefined, info.lastlinedefined
-- can't do anything for a C function
if src == "=[C]" then return nil, "Is a C function." end
if src == "=stdin" then return nil, "Was defined interactively." end
-- for files, fetch the definition
local path = src:match "^#(.*)$"
if path then
local f = io.open( path )
local code = f:read '*a'
f:close( )
return funclines( code, line, lastline, path )
end
-- otherwise `load`ed, so `source`/`src` _is_ the source
return funclines( src, line, lastline )
end
A closing remark: If you paste code into a Lua/JIT REPL, locals disappear between definitions, because every line (or minimal complete group of lines) is its own chunk. The common fix (that you probably know) is to wrap everything into a block as do*paste*end, but an alternative is to load[[*paste*]]() (possibly with more =s like [===[ and ]===].) If you paste this way, the above dumpsource (or any other function using debug.getinfo) will then be able to get the source of the function(s). This also means that if you defined a nice function but it's gone from the history and the scroll buffer, you can recover it in this way (if you defined it by loading and not directly feeding the interpreter). Saving the source in a file will then also be possible without copy-pasting and not require editing out the >> prompts.
I've never liked the default window switching possibilities in Awesome, so I thought I'd implement Alt-Tab behavior that takes history into account (and does fancy opacity effects).
When Alt-Tab is pressed, the entire history is recorded in a table, and appended to that history are the minimized windows (within the same tag). When this table is generated, I instantiate a keygrabber that captures Tab-press events (to switch to the next client in the table) and Alt-release events (to abort entirely).
A flag keeps track of whether the user is in the process of Alt-tabbing, to prevent the table from being generated over and over again.
The code (it's a lot and you probably don't need to see it, but my experience tells me that when I don't post all the code, people will ask for it eventually):
altTabbing = false
altTabIndex = 1
altTabHistory = {}
clientOpacities = {}
function altTabSetOpacities(restore)
for i,c in pairs(altTabHistory) do
if not restore and i ~= altTabIndex then
c.opacity = 0.5
else
c.opacity = clientOpacities[i]
end
end
end
function myAltTab()
-- First check if the user is already alttabbing, in which case the history
-- should NOT be updated. If the user has just pressed alt-tab, generate a new
-- history-table
if not altTabbing then -- generate history-table
-- Clear Tables
for i in pairs(altTabHistory) do altTabHistory[i] = nil end
for i in pairs(clientOpacities) do clientOpacities[i] = nil end
-- Get focus history for current tag
local s = mouse.screen;
local idx = 0
local c = awful.client.focus.history.get(s, idx)
while c do
table.insert(altTabHistory, c)
table.insert(clientOpacities, c.opacity)
idx = idx + 1
c = awful.client.focus.history.get(s, idx)
end
-- Minimized clients will not appear in the focus history
-- Find them by cycling through all clients, and adding them to the list
-- if not already there.
-- This will preserve the history AND enable you to focus on minimized clients
local t = awful.tag.selected(s)
local all = client.get(s)
for i = 1, #all do
local c = all[i]
local ctags = c:tags();
-- check if the client is on the current tag
local isCurrentTag = false
for j = 1, #ctags do
if t == ctags[j] then
isCurrentTag = true
break
end
end
if isCurrentTag then
-- check if client is already in the history
-- if not, add it
local addToHistory = true
for k = 1, #altTabHistory do
if altTabHistory[k] == c then
addToHistory = false
break
end
end
if addToHistory then
table.insert(altTabHistory, c)
table.insert(clientOpacities, c.opacity)
end
end
end
-- reset current index and flag
altTabIndex = 1
altTabbing = true
-- Now that we have collected all windows, we should run a keygrabber
-- as long as the user is alt-tabbing:
keygrabber.run(
function (mod, key, event)
-- Stop alt-tabbing when the alt-key is released
if key == "Alt_L" and event == "release" then
altTabbing = false
altTabSetOpacities(true)
c = altTabHistory[altTabIndex]
client.focus = c
c:raise()
return false -- stop keygrabber
end
-- Move to next client on each Tab-press
if key == "Tab" and event == "press" then
myAltTab()
return true -- keep going
end
return true -- keep going
end
)
end -- if not altTabbing
-- at this point, the user is alt-tabbing, so we should raise
-- the next client in the history-table
if #altTabHistory < 2 then return end
-- Switch to next client
altTabIndex = altTabIndex + 1
if altTabIndex > #altTabHistory then
altTabIndex = 1 -- wrap around
end
-- focus on current client
local c = altTabHistory[altTabIndex]
c.minimized = false
c:raise()
-- make current client stand out
altTabSetOpacities(false)
end
I realize there's a lot of code, but the main thing is the keygrabber. For still unknown reasons, Awesome sometimes crashes while I'm Alt-Tabbing using this approach. I want to replace the keygrabber by connecting signals to the Alt and Tab keys, and disconnecting them as soon as the user is done. However, I'm not able to do this for some reason.
I instantiate a new key-object like this:
local altkey = awful.key({}, "Alt_L")[1]
I found out by trial and error that awful.key() actually returns a table of which I could query the first element for key, keysym etc, hence the [1]. However, when I try to connect a signal to this object, the LUA interpreter complains and tells me it's a nil object. So my question is: am I doing the right thing here? Is it even possible to replace the keygrabber in the way I intend to?
To use the Alt_L key in Awesome you should refer to "Mod1" in your rc.lua file, to make it mor readable I added the following line to the beginning of my configuration so Alt_L can be used.
Alt_L = "Mod1"