-
This looks like a lua language issue but I cannot rule out that it is related to hammerspoon and/or metamethods or something. I have this code: local function findSessionFiles()
print("Finding session files...")
local sessionDir = home .. "/.local/share/nvim/sessions"
local sessions = {}
if hs.fs.attributes(sessionDir, "mode") == "directory" then
for file in hs.fs.dir(sessionDir) do
if file ~= "." and file ~= ".." then
print("Found file: " .. file, type(file))
local s = file:gsub("__", "/")
print("Converted to: " .. s)
table.insert(sessions, file:gsub("__", "/"))
end
end
else
print("Session directory not found: " .. sessionDir)
hs.alert.show("Session directory not found: " .. sessionDir)
end
print("Found " .. #sessions .. " file(s)")
return sessions
end The error I get is:
If I change this: --- i/hammerspoon/main-init.lua
+++ w/hammerspoon/main-init.lua
@@ -70,7 +70,7 @@ local function findSessionFiles()
print("Found file: " .. file, type(file))
local s = file:gsub("__", "/")
print("Converted to: " .. s)
- table.insert(sessions, file:gsub("__", "/"))
+ table.insert(sessions, s)
end
end
else The code runs fine. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
A simple failing test in lua 5.4 repl
indicates this is a standard lua behavior. Sorry, it's not a hammerspoon specific question then. But surely you Lua experts could school me (as well as the LLMs I've managed to stump with this). |
Beta Was this translation helpful? Give feedback.
-
This is one of those subtle lua quirks that crops up and bites everyone at least once... it has to do with functions that return multiple values and their position in an argument list.
a = "1, 2, 3, 4"
print(a:gsub(", ", "-"))
1-2-3-4 3 But, if the same function is not the final argument in the argument list, then only the first return value is used: print(a:gsub(", ", "-"), "is new")
1-2-3-4 is new The fix is to either capture the result you want into a local variable and use that, or to enclose the function which returns multiple arguments in an extra set of parenthesis: print((a:gsub(", ", "-")))
1-2-3-4 |
Beta Was this translation helpful? Give feedback.
This is one of those subtle lua quirks that crops up and bites everyone at least once... it has to do with functions that return multiple values and their position in an argument list.
gsub
returns two values -- the changed string and the number of changes made. If a function returns multiple values and is at the end of an argument list, all of the return values are appended to the list:But, if the same function is not the final argument in the argument list, then only the first return value is used:
The fix is to either capture the result you want into a local variable and use that, o…