Skip to content

Instantly share code, notes, and snippets.

@sudo-give-me-coffee
Last active September 19, 2022 17:33
Show Gist options
  • Select an option

  • Save sudo-give-me-coffee/af7d799c673417859f629e6353698313 to your computer and use it in GitHub Desktop.

Select an option

Save sudo-give-me-coffee/af7d799c673417859f629e6353698313 to your computer and use it in GitHub Desktop.
Basic integration with pure Lua with system shell. This allows executing system commands as Lua functions. The command output is returned as a Lua string
-- Create a table to hook __index metamethod of _ENV
_ENV_mt = {}
function _ENV_mt:__index(key)
-- If requested index exists, return them
if rawget(_ENV,key) then
return rawget(_ENV,key)
end
-- If environment variable exists return them
if os.getenv(key) then
return os.getenv(key)
end
-- Check if executable exists in PATH variable
local separator = package.config:sub(1,1) == "/" and ":" or ";"
local found = false
for path in os.getenv("PATH"):gmatch("[^"..separator.."]+") do
local file_path = path..(separator == ":" and "/" or "\\")..key
local executable=io.open(file_path,"r")
if executable~=nil then
io.close(executable)
found = true
break
end
end
-- If not return nil
if found == false then
return nil
end
-- Let's create a memoize function (a function with properties)
local memoize = {} -- The memoize table
local memoize_mt = {__index = memoize} -- The memoize metatable
memoize.cmd=key -- Let's "memoize" requested cmd on key "cmd"
-- This allow to call a table as function
function memoize_mt:__call(args)
-- Since args may contains spaces we need to hold cmd and args with single quotes
local cmd_line = "'"..self.cmd.."'"
for _,arg in ipairs(args) do
cmd_line = cmd_line.." '"..arg.."'"
end
-- Do a simple popen read command output
local file = assert(io.popen(cmd_line, 'r'))
local output = file:read('*all')
file:close()
-- So return them
return output
end
-- At last step we return our memoize function
return setmetatable(memoize,memoize_mt)
end
setmetatable(_ENV, _ENV_mt) --And hook _ENV with created metatable
-- ls {"-la" ; "/"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment