Skip to content

Instantly share code, notes, and snippets.

@nrnrnr
Created February 18, 2022 21:53
Show Gist options
  • Save nrnrnr/b302db5c59c600dd75c38d460423cc3d to your computer and use it in GitHub Desktop.
Save nrnrnr/b302db5c59c600dd75c38d460423cc3d to your computer and use it in GitHub Desktop.
Lua code for association lists on the command line (for use with fish)
#!/usr/bin/env lua5.1
-- assocation list on the command line
--
-- rep is: key1 val1 key2 val2 ...
--
local function succeed(s)
if s ~= true then
io.stdout:write(s, '\n')
end
os.exit(0)
end
local function fail()
os.exit(1)
end
local function finish(answer)
if answer then
io.stdout:write(answer, '\n')
os.exit(0)
else
os.exit(1)
end
end
local funs = { }
function funs.index(key, ...)
local args = { ... }
for i = 1, #args, 2 do
if args[i] == key then
return i
end
end
end
function funs.get(key, ...)
local i = funs.index(key, ...)
if i then
return select(i+1, ...)
end
end
function funs.has(key, ...)
return funs.index(key, ...) and true or false
end
function funs.keys(...)
local args = { ... }
for i = 1, #args, 2 do
io.stdout:write(args[i], '\n')
end
os.exit(0)
end
function funs.set(key, value, ...)
local args = { ... }
local i = funs.index(key, ...)
if not i then
i = #args + 1
args[i] = key
end
args[i+1] = value
for _, s in ipairs(args) do
io.stdout:write(s, '\n')
end
os.exit(0)
end
local operation = assert(table.remove(arg, 1))
finish(assert(funs[operation])(unpack(arg)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment