pure.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Package pure provides Lua functions for running commands and listing files
  2. package pure
  3. import (
  4. log "github.com/sirupsen/logrus"
  5. lua "github.com/xyproto/gopher-lua"
  6. )
  7. // Extra Lua functions
  8. const luacode = `
  9. -- Given the name of a python script in the same directory,
  10. -- return the outputted lines as a table
  11. function py(filename)
  12. if filename == nil then
  13. return {}
  14. end
  15. local cmd = "python " .. scriptdir() .. "/" .. filename
  16. local f = assert(io.popen(cmd, 'r'))
  17. local a = {}
  18. for line in f:lines() do
  19. table.insert(a, line)
  20. end
  21. f:close()
  22. return a
  23. end
  24. -- Given the name of an executable (or executable script) in the same directory,
  25. -- return the outputted lines as a table
  26. function run(given_command)
  27. if given_command == nil then
  28. return {}
  29. end
  30. local cmd = "cd " .. scriptdir() .. "; " .. given_command
  31. local f = assert(io.popen(cmd, 'r'))
  32. local a = {}
  33. for line in f:lines() do
  34. table.insert(a, line)
  35. end
  36. f:close()
  37. return a
  38. end
  39. -- List a table
  40. function dir(t)
  41. if t == nil then
  42. t = _G
  43. end
  44. local output = {}
  45. for k, v in pairs(t) do
  46. table.insert(output, string.format("%-16s\t->\t%s", tostring(k), tostring(v)))
  47. end
  48. return table.concat(output, "\n")
  49. end
  50. `
  51. // Load makes functions for running commands, python code or listing files to
  52. // the given Lua state struct: py, run and dir
  53. func Load(L *lua.LState) {
  54. if err := L.DoString(luacode); err != nil {
  55. log.Errorf("Could not load extra Lua functions: %s", err)
  56. }
  57. }