Parsing Lua strings, more specifically newlines - parsing

I'm trying to parse Lua 5.3 strings. However, I encountered an issue. For example,
$ lua
Lua 5.3.4 Copyright (C) 1994-2017 Lua.org, PUC-Rio
> print(load('return "\\z \n\r \n\r \r\n \n \n \\x"', "#test"))
nil test:6: hexadecimal digit expected near '"\x"'
>
> print(load('return "\\z\n\r\n\r\r\n\n\n\\x"', "#test"))
nil test:6: hexadecimal digit expected near '"\x"'
Both of these error on line 6, and the logic behind that is pretty simple: eat newline characters (\r or \n) if they're different from the current one (I believe this to be an accurate description of how the lua lexer works, but I may be wrong).
I have this code, which should do it:
local ln = 1
local skip = false
local mode = 0
local prev
for at, crlf in eaten:gmatch('()[\r\n]') do
local last = eaten:sub(at-1, at-1)
if skip and prev == last and last ~= crlf then
skip = false
else
skip = true
ln = ln + 1
end
prev = crlf
end
It decides whether to eat newlines based on the previous char. Now, from what I can tell, this should work, but no matter what I do it doesn't seem to work. Other attempts have made it report 5 lines, while this one makes it report 9(!). What am I missing here? I'm running this on Lua 5.2.4.
This is part of a routine for parsing \z:
local function parse52(s)
local startChar = string.sub(s,1,1)
if startChar~="'" and startChar~='"' then
error("not a string", 0)
end
local c = 0
local ln = 1
local t = {}
local nj = 1
local eos = #s
local pat = "^(.-)([\\" .. startChar .. "\r\n])"
local mkerr = function(emsg, ...)
error(string.format('[%s]:%d: ' .. emsg, s, ln, ...), 0)
end
local lnj
repeat
lnj = nj
local i, j, part, k = string.find(s, pat, nj + 1, false)
if i then
c = c + 1
t[c] = part
if simpleEscapes[v] then
--[[ some code, some elseifs, some more code ]]
elseif v == "z" then
local eaten, np = s:match("^([\t\n\v\f\r ]*)%f[^\t\n\v\f\r ]()", nj+1)
local p=np
nj = p-1
--[[ the newline counting routine above ]]
--[[ some other elseifs ]]
end
else
nj = nil
end
until not nj
if s:sub(-1, -1) ~= startChar then
mkerr("unfinished string near <eof>")
end
return table.concat(t)
end

Compact code for iterating lines of Lua script:
local text = "First\n\r\n\r\r\n\n\nSixth"
local ln = 1
for line, newline in text:gmatch"([^\r\n]*)([\r\n]*)" do
print(ln, line)
ln = ln + #newline:gsub("\n+", "\0%0\0"):gsub(".%z.", "."):gsub("%z", "")
end
Efficient code for iterating lines of Lua script:
local text = "First\n\r\n\r\r\n\n\nSixth"
local sub = string.sub
local ln = 1
for line, newline in text:gmatch'([^\r\n]*)([\r\n]*)' do
print(ln, line)
local pos, max_pos = 1, #newline
while pos <= max_pos do
local crlf = sub(newline, pos, pos + 1)
if crlf == "\r\n" or crlf == "\n\r" then
pos = pos + 2
else
pos = pos + 1
end
ln = ln + 1
end
end

Related

How to store the current buffer filename with cursor position to register using neovim Lua API?

In vim I can use getcurpos() and expand('%:t'), but how does this work in lua? The solution should ideally only use the neovim api.
Without the neovim api:
function Fcolumn_noplenary()
local fname = vim.fn.expand('%:t')
local line_col_pair = vim.api.nvim_win_get_cursor(0) -- row is 1, column is 0 indexed
local fnamecol = fname .. ':' .. tostring(line_col_pair[1]) .. ':' .. tostring(line_col_pair[2])
vim.fn.setreg('+', fnamecol) -- register + has filename:row:column
end
And with plenary:
function Fcolumn_plenary()
local Path = require "plenary.path"
local path = Path.path
local fileAbs = vim.api.nvim_buf_get_name(0)
local p = Path:new fileAbs
local fname = p.filename
local line_col_pair = vim.api.nvim_win_get_cursor(0) -- row is 1, column is 0 indexed
local fnamecol = fname .. ':' .. tostring(line_col_pair[1]) .. ':' .. tostring(line_col_pair[2])
vim.fn.setreg('+', fnamecol) -- register + has filename:row:column
end
As of neovim 0.8, there is vim.fs which only leaves setting the register with vimscript (vim.fn) and no external dependencies:
function Fcolumn():
local fileAbs = vim.api.nvim_buf_get_name(0)
local fname = vim.fs.basename(fileAbs)
local line_col_pair = vim.api.nvim_win_get_cursor(0) -- row is 1, column is 0 indexed
local fnamecol = fname .. ':' .. tostring(line_col_pair[1]) .. ':' .. tostring(line_col_pair[2])
vim.fn.setreg('+', fnamecol) -- register + has filename:row:column
end

Lua char spacing perfectly

Failed Spacing
I'm trying to get all of these names with a max char of 31 to line up all together in the same row by adding the number of spaces per player name that it needs. I've been trying to accomplish this for some time now and I just can't figure this out completely.
This is my current code which is a disaster I know..
local c = client.GetPlayerNameByIndex(i)
if c ~= nil and client.GetPlayerNameByIndex(i) ~= "nil" then
playerlist[i] = all_trim(client.GetPlayerNameByIndex(i))
local leve = 67
local namelength = #client.GetPlayerNameByIndex(i) --max 31 chars
local output = "" .. client.GetPlayerNameByIndex(i)
local newspace = ""
local neededspaces = 31 - #client.GetPlayerNameByIndex(i)
print(neededspaces)
for i=1, 31-#string.sub(client.GetPlayerNameByIndex(i), 1, 31) do
newspace = newspace .. " "
end
playerinfolist[i] = output .. newspace .. "a"
end
In simple terms I want all of the "a"s to line up with each string. Thanks for helping me!

Can anybody please tell me how to set or reset a bit in lua..?

I want to perform set and reset of particular bit in a number. As I'm using lua 5.1 I can't able to use APIs and shifting operators so it is becoming more and more complex so please help me finding this
bit library is shipped with the firmware.
Read the documentation: https://nodemcu.readthedocs.io/en/release/modules/bit/
You can do it without external libraries, if you know the position of the bit you wish to flip.
#! /usr/bin/env lua
local hex = 0xFF
local maxPos = 7
local function toggle( num, pos )
if pos < 0 or pos > maxPos then print( 'pick a valid pos, 0-' ..maxPos )
else
local bits = {} -- populate emtpy table
for i=1, maxPos do bits[i] = false end
for i = maxPos, pos +1, -1 do -- temporarily throw out the high bits
if num >= 2 ^i then
num = num -2 ^i
bits [i +1] = true
end
end
if num >= 2 ^pos then num = num -2 ^pos -- flip desired bit
else num = num +2 ^pos
end
for i = 1, #bits do -- add those high bits back in
if bits[i] then num = num +2 ^(i -1) end
end
end ; print( 'current value:', num )
return num
end
original value: 255
current value: 127
pick a valid pos, 0-7
current value: 127
current value: 255

How to print the result of calculation lua

Local cl = rendom - or +
Local a = rendom number
Local x = rendom number
Locol re = a..cl..x
Print (re) --output 5+8
I need to get the result 13
How to do that?
If you want the number 13 you can try:
Local cl = rendom "m" or "p" -- m for -, p for +
Local a = rendom number
Local x = rendom number
Local re = 0
if cl == "m" then re = a-x end
if cl == "p" then re = a+x end
Print (re) --output 13
or
Local cl = rendom "m" or "p" -- m for -, p for +
Local a = rendom number
Local x = rendom number
Local re = 0
if cl == "m" then re = a-x Print(a.."-"..x, re) end
if cl == "p" then re = a+x Print(a.."+"..x, re) end
Hope this helps!

Case-insensitive Lua pattern-matching

I'm writing a grep utility in Lua for our mobile devices running Windows CE 6/7, but I've run into some issues implementing case-insensitive match patterns. The obvious solution of converting everything to uppercase (or lower) does not work so simply due to the character classes.
The only other thing I can think of is converting the literals in the pattern itself to uppercase.
Here's what I have so far:
function toUpperPattern(instr)
-- Check first character
if string.find(instr, "^%l") then
instr = string.upper(string.sub(instr, 1, 1)) .. string.sub(instr, 2)
end
-- Check the rest of the pattern
while 1 do
local a, b, str = string.find(instr, "[^%%](%l+)")
if not a then break end
if str then
instr = string.sub(instr, 1, a) .. string.upper(string.sub(instr, a+1, b)) .. string.sub(instr, b + 1)
end
end
return instr
end
I hate to admit how long it took to get even that far, and I can still see right away there are going to be problems with things like escaped percent signs '%%'
I figured this must be a fairly common issue, but I can't seem to find much on the topic.
Are there any easier (or at least complete) ways to do this? I'm starting to go crazy here...
Hoping you Lua gurus out there can enlighten me!
Try something like this:
function case_insensitive_pattern(pattern)
-- find an optional '%' (group 1) followed by any character (group 2)
local p = pattern:gsub("(%%?)(.)", function(percent, letter)
if percent ~= "" or not letter:match("%a") then
-- if the '%' matched, or `letter` is not a letter, return "as is"
return percent .. letter
else
-- else, return a case-insensitive character class of the matched letter
return string.format("[%s%s]", letter:lower(), letter:upper())
end
end)
return p
end
print(case_insensitive_pattern("xyz = %d+ or %% end"))
which prints:
[xX][yY][zZ] = %d+ [oO][rR] %% [eE][nN][dD]
Lua 5.1, LPeg v0.12
do
local p = re.compile([[
pattern <- ( {b} / {escaped} / brackets / other)+
b <- "%b" . .
escaped <- "%" .
brackets <- { "[" ([^]%]+ / escaped)* "]" }
other <- [^[%]+ -> cases
]], {
cases = function(str) return (str:gsub('%a',function(a) return '['..a:lower()..a:upper()..']' end)) end
})
local pb = re.compile([[
pattern <- ( {b} / {escaped} / brackets / other)+
b <- "%b" . .
escaped <- "%" .
brackets <- {: {"["} ({escaped} / bcases)* {"]"} :}
bcases <- [^]%]+ -> bcases
other <- [^[%]+ -> cases
]], {
cases = function(str) return (str:gsub('%a',function(a) return '['..a:lower()..a:upper()..']' end)) end
, bcases = function(str) return (str:gsub('%a',function(a) return a:lower()..a:upper() end)) end
})
function iPattern(pattern,brackets)
('sanity check'):find(pattern)
return table.concat({re.match(pattern, brackets and pb or p)})
end
end
local test = '[ab%c%]d%%]+ o%%r %bnm'
print(iPattern(test)) -- [ab%c%]d%%]+ [oO]%%[rR] %bnm
print(iPattern(test,true)) -- [aAbB%c%]dD%%]+ [oO]%%[rR] %bnm
print(('qwe [%D]% O%r n---m asd'):match(iPattern(test, true))) -- %D]% O%r n---m
Pure Lua version:
It is necessary to analyze all the characters in the string to convert it into a correct pattern because Lua patterns do not have alternations like in regexps (abc|something).
function iPattern(pattern, brackets)
('sanity check'):find(pattern)
local tmp = {}
local i=1
while i <= #pattern do -- 'for' don't let change counter
local char = pattern:sub(i,i) -- current char
if char == '%' then
tmp[#tmp+1] = char -- add to tmp table
i=i+1 -- next char position
char = pattern:sub(i,i)
tmp[#tmp+1] = char
if char == 'b' then -- '%bxy' - add next 2 chars
tmp[#tmp+1] = pattern:sub(i+1,i+2)
i=i+2
end
elseif char=='[' then -- brackets
tmp[#tmp+1] = char
i = i+1
while i <= #pattern do
char = pattern:sub(i,i)
if char == '%' then -- no '%bxy' inside brackets
tmp[#tmp+1] = char
tmp[#tmp+1] = pattern:sub(i+1,i+1)
i = i+1
elseif char:match("%a") then -- letter
tmp[#tmp+1] = not brackets and char or char:lower()..char:upper()
else -- something else
tmp[#tmp+1] = char
end
if char==']' then break end -- close bracket
i = i+1
end
elseif char:match("%a") then -- letter
tmp[#tmp+1] = '['..char:lower()..char:upper()..']'
else
tmp[#tmp+1] = char -- something else
end
i=i+1
end
return table.concat(tmp)
end
local test = '[ab%c%]d%%]+ o%%r %bnm'
print(iPattern(test)) -- [ab%c%]d%%]+ [oO]%%[rR] %bnm
print(iPattern(test,true)) -- [aAbB%c%]dD%%]+ [oO]%%[rR] %bnm
print(('qwe [%D]% O%r n---m asd'):match(iPattern(test, true))) -- %D]% O%r n---m

Resources