Neovim lua how to use mutable variables in keymappings - lua

I'm using neovide (a graphical interface for nvim), so I lost ctrl+[-+] to change the font size. I'm trying to rewrite it in my lua config but I'm pretty new to lua so I'm struggling to implement the function. Here's my code :
vim.g.font_size = 11
vim.o.guifont='FantasqueSansMono Nerd Font Mono:h'..vim.g.font_size
vim.keymap.set('n', '<C-->',
':let g:font_size = (g:font_size - 1)<CR>:let &guifont = \'FantasqueSansMono Nerd Font Mono:h'..vim.g.font_size..'\'<CR>')
What I'm trying to do, is to have a variable font_size that I can increment or decrement, then use the new value to update the size of the font. The first two lines work perfectly, they always set the correct font size when launching a new instance of neovide. The keymap on the other hand will decrement / increment font_size like intended but the second command of the mapping will always use the value written at line 1.
For instance, if I start neovide and press ctrl+-, the status line will show :let &guifont = 'FantasqueSansMono Nerd Font Mono:h11', but if I enter the following command : echo g:font_size, I get 10. Is there a way to fix this problem ? (or a more elegant way to fix it haha)

This line:
':let g:font_size = (g:font_size - 1)<CR>:let &guifont = \'Consolas:h'..vim.g.font_size..'\'<CR>'
Is building a string that uses the current version of vim.g.font_size at the time the string is built. That ends up being this string:
':let g:font_size = (g:font_size - 1)<CR>:let &guifont = \'Consolas:h11\'<CR>'
So your mapping looks like this:
vim.keymap.set('n', '<C-->', ':let g:font_size = (g:font_size - 1)<CR>:let &guifont = \'Consolas:h11\'<CR>'
See what's happening now?
Side note, Lua supports several string delimeters ("x", 'x', or [[x]]), so you don't have to escape your internal strings if you use a different outer delimeter, like this:
":let g:font_size = (g:font_size - 1)<CR>:let &guifont = 'Consolas:h11'<CR>"
The binding yoiu really want is this:
vim.keymap.set('n', '<C-->', ":let g:font_size = (g:font_size - 1)<CR>:let &guifont = 'Consolas:h'.g:font_size<CR>"
But if you really want the binding to be Lua, you'd dot his:
vim.keymap.set('n', '<C-->', ":luado vim.g.font_size = vim.g.font_size - 1; vim.o.guifont='Consolas:h'..vim.g.font_size<CR>")

Related

lua tables - string representation

as a followup question to lua tables - allowed values and syntax:
I need a table that equates large numbers to strings. The catch seems to be that strings with punctuation are not allowed:
local Names = {
[7022003001] = fulsom jct, OH
[7022003002] = kennedy center, NY
}
but neither are quotes:
local Names = {
[7022003001] = "fulsom jct, OH"
[7022003002] = "kennedy center, NY"
}
I have even tried without any spaces:
local Names = {
[7022003001] = fulsomjctOH
[7022003002] = kennedycenterNY
}
When this module is loaded, wireshark complains "}" is expected to close "{" at line . How can I implement a table with a string that contains spaces and punctuation?
As per Lua Reference Manual - 3.1 - Lexical Conventions:
A short literal string can be delimited by matching single or double quotes, and can contain the (...) C-like escape sequences (...).
That means the short literal string in Lua is:
local foo = "I'm a string literal"
This matches your second example. The reason why it fails is because it lacks a separator between table members:
local Names = {
[7022003001] = "fulsom jct, OH",
[7022003002] = "kennedy center, NY"
}
You can also add a trailing separator after the last member.
The more detailed description of the table constructor can be found in 3.4.9 - Table Constructors. It could be summed up by the example provided there:
a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
I really, really recommend using the Lua Reference Manual, it is an amazing helper.
I also highly encourage you to read some basic tutorials e.g. Learn Lua in 15 minutes. They should give you an overview of the language you are trying to use.

lua dissector for a float variable returns zero

I'm trying to read a float variable from the buffer but i'm getting a zero value.
This is the code i used:
-- Create fields
str_format=string.format
p_Genie.fields = {}
local fields = p_Genie.fields
fields.number_field = ProtoField.float("p_Genie.number", "Number",base.DEC)
function addFloat32(tree, buf, start, name, floatSize)
local rang = buf(start, floatSize)
local ti = tree:add_le(fields.number_field, rang)
ti:set_text(str_format("%s %f", name, rang:le_float()))
return floatSize
end
What am i doing wrong?
Thanks.
I don't think your use of ProtoField.float is correct. According to Section 11.6.7.16 of the Wireshark Developer's Guide, the 3rd argument is an optional valuestring, not a base. Maybe start by fixing that and see if it resolves your problem.

Correct syntax for using custom methods with caret package

I get the following error in caret trainControl() using the custom methods syntax documented in the package vignette (pdf) on page 46. Does anyone know if this document out of date or incorrect? It seems at odds with the caret documentation page where the "custom" parameter is not used.
> fitControl <- trainControl(custom=list(parameters=lpgrnn$grid, model=lpgrnn$fit,
prediction=lpgrnn$predict, probability=NULL,
sort=lpgrnn$sort, method="cv"),
number=10)
Error in trainControl(custom = list(parameters = lpgrnn$grid, model = lpgrnn$fit, :
unused argument (custom = list(parameters = lpgrnn$grid, model = lpgrnn$fit,
prediction = lpgrnn$predict, probability = NULL, sort = lpgrnn$sort, method = "cv",
number = 10))
The cited pdf is out of date. The caret website is the canonical source of documentation.

How to replace many symbols with a single word in Lua?

I must replace all of these characters, "①②③④⑤⑥⑦⑧⑨⑩", with "\item".
I have used this code:
stra = string.gsub(text, "①", "\\item")
strb = string.gsub(stra, "②", "\\item")
strc = string.gsub(strb, "③", "\\item")
strd = string.gsub(strc, "④", "\\item")
stre = string.gsub(strd, "⑤", "\\item")
However, this is very verbose. Is there a simpler way to replace all of those items?
local symbols_trans = {
["\226\145\160"]--[[①]] = "\\item1",
["\226\145\161"]--[[②]] = "\\bananas",
["\226\145\162"]--[[③]] = "\\cactus",
["\226\145\163"]--[[④]] = "\\etc",
["\226\145\164"]--[[⑤]] = "\\item5",
["\226\145\165"]--[[⑥]] = "\\item6",
["\226\145\166"]--[[⑦]] = "\\item7",
["\226\145\167"]--[[⑧]] = "\\item8",
["\226\145\168"]--[[⑨]] = "\\item9",
["\226\145\169"]--[[⑩]] = "\\item10",
}
text = string.gsub(text, "(\266\145.)", symbol_trans)
Or if you want to replace them all with"\\item":
text = string.gsub(text,
"\266\145[\160-\169]",
"\\item"
)
[\160-\169] is equivalent to [\160\161\162\163\164\165\166\167\168\169].
See the Lua manual for information on ranges and, in general, Lua patterns.
You could also be fancy:
text = string.gsub(text,
"\266\145([\160-169])",
function(c)
return "\\item"..(string.byte(c)-160+1)
end
)
This will turn ① into \item1, ② into \item2, and so on.
Use a "set" as described in the tutorial: http://lua-users.org/wiki/PatternsTutorial
string.gsub(text, "[①②③④⑤⑥⑦⑧⑨⑩]", "\\item")
Is there a simpler way to replace all of those items?
Not without a Lua pattern matching library that knows what UTF-8 is. Lua is not Unicode aware; it has no idea how to search for Unicode symbols.
If you're using some non-multibyte encoding, then what John suggested might work. But not if it's UTF-8.
For your specific case, you could always do this:
local symbolsToChange { "①", "②", ...}
for i, sym in ipairs(symbolsToChange) do
string.gsub(text, sym, "\\item")
end

How Lua tables work

I am starting to learn Lua from Programming in Lua (2nd edition)
I didn't understand the following in the book. Its very vaguely explained.
a.) w={x=0,y=0,label="console"}
b.) x={math.sin(0),math.sin(1),math.sin(2)}
c.) w[1]="another field"
d.) x.f=w
e.) print (w["x"])
f.) print (w[1])
g.) print x.f[1]
When I do print(w[1]) after a.), why doesn't it print x=0
What does c.) do?
What is the difference between e.) and print (w.x)?
What is the role of b.) and g.)?
You have to realize that this:
t = {3, 4, "eggplant"}
is the same as this:
t = {}
t[1] = 3
t[2] = 4
t[3] = "eggplant"
And that this:
t = {x = 0, y = 2}
is the same as this:
t = {}
t["x"] = 0
t["y"] = 2
Or this:
t = {}
t.x = 0
t.y = 2
In Lua, tables are not just lists, they are associative arrays.
When you print w[1], then what really matters is line c.) In fact, w[1] is not defined at all until line c.).
There is no difference between e.) and print (w.x).
b.) creates a new table named x which is separate from w.
d.) places a reference to w inside of x. (NOTE: It does not actually make a copy of w, just a reference. If you've ever worked with pointers, it's similar.)
g.) Can be broken up in two parts. First we get x.f which is just another way to refer to w because of line d.). Then we look up the first element of that table, which is "another field" because of line c.)
There's another way of creating keys in in-line table declarations.
x = {["1st key has spaces!"] = 1}
The advantage here is that you can have keys with spaces and any extended ASCII character.
In fact, a key can be literally anything, even an instanced object.
function Example()
--example function
end
x = {[Example] = "A function."}
Any variable or value or data can go into the square brackets to work as a key. The same goes with the value.
Practically, this can replace features like the in keyword in python, as you can index the table by values to check if they are there.
Getting a value at an undefined part of the table will not cause an error. It will just give you nil. The same goes for using undefined variables.
local w = {
--[1] = "another field"; -- will be set this value
--["1"] = nil; -- not save to this place, different with some other language
x = 0;
y = 0;
label = "console";
}
local x = {
math.sin(0);
math.sin(1);
math.sin(2);
}
w[1] = "another field" --
x.f = w
print (w["x"])
-- because x.f = w
-- x.f and w point one talbe address
-- so value of (x.f)[1] and w[1] and x.f[1] is equal
print (w[1])
print ((x.f)[1])
print (x.f[1])
-- print (x.f)[1] this not follows lua syntax
-- only a function's has one param and type of is a string
-- you can use print "xxxx"
-- so you print x.f[1] will occuur error
-- in table you can use any lua internal type 's value to be a key
-- just like
local t_key = {v=123}
local f_key = function () print("f123") end
local t = {}
t[t_key] = 1
t[f_key] = 2
-- then t' key actualy like use t_key/f_key 's handle
-- when you user t[{}] = 123,
-- value 123 related to this no name table {} 's handle

Resources