Created
October 2, 2021 15:38
-
-
Save stevedonovan/4f73ba3269f67465b5833b12042d31d1 to your computer and use it in GitHub Desktop.
el is a Lua expression evaluator with shell-friendly shortcuts, like ^string and print[[]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/lua | |
-- Flatten ALL those tidy tables and add environment lookup | |
local tables = {math,io,os,string,bit32} | |
setmetatable(_G,{ | |
__index = function(t,key) | |
for _,m in ipairs(tables) do | |
local v = m[key] | |
if v ~= nil then return v end | |
end | |
return os.getenv(key) | |
end | |
}) | |
-- shell does NOT like print() so we have print[] | |
function bquote(a) | |
local verb,aa = a:match '([%w_]+)(%b[])$' | |
if verb then | |
aa = aa:sub(2,#aa-1) | |
return verb..'('..bquote(aa)..')' | |
end | |
return a | |
end | |
function quote(a) | |
-- help with quoting strings | |
local sa = a:match '^%^(.+)' | |
if sa then return '"'..sa..'"' end | |
return bquote(a) | |
end | |
-- f a b ... becomes f(a,b,...) | |
local expr = quote(arg[1]) | |
local args = {} | |
for i = 2,#arg do | |
args[i-1] = quote(arg[i]) | |
end | |
if #args > 1 or type(_G[expr]) == 'function' then | |
expr = expr..'('..table.concat(args,',')..')' | |
end | |
local f,e = load('return '..expr) | |
if e then | |
print('error',e) | |
os.exit(1) | |
end | |
-- not so easy to know if it's an error! | |
print(f()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment