interface.lua 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. local skynet = require "skynet"
  2. local function dft_loader(path, name, G)
  3. local errlist = {}
  4. for pat in string.gmatch(path,"[^;]+") do
  5. local filename = string.gsub(pat, "?", name)
  6. local f , err = loadfile(filename, "bt", G)
  7. if f then
  8. return f, pat
  9. else
  10. table.insert(errlist, err)
  11. end
  12. end
  13. error(table.concat(errlist, "\n"))
  14. end
  15. return function (name , G, loader)
  16. loader = loader or dft_loader
  17. local function func_id(id, group)
  18. local tmp = {}
  19. local function count( _, name, func)
  20. if type(name) ~= "string" then
  21. error (string.format("%s method only support string", group))
  22. end
  23. if type(func) ~= "function" then
  24. error (string.format("%s.%s must be function", group, name))
  25. end
  26. if tmp[name] then
  27. error (string.format("%s.%s duplicate definition", group, name))
  28. end
  29. tmp[name] = true
  30. table.insert(id, { #id + 1, group, name, func} )
  31. end
  32. return setmetatable({}, { __newindex = count })
  33. end
  34. do
  35. assert(getmetatable(G) == nil)
  36. assert(G.init == nil)
  37. assert(G.exit == nil)
  38. assert(G.accept == nil)
  39. assert(G.response == nil)
  40. end
  41. local temp_global = {}
  42. local env = setmetatable({} , { __index = temp_global })
  43. local func = {}
  44. local system = { "init", "exit", "hotfix", "profile"}
  45. do
  46. for k, v in ipairs(system) do
  47. system[v] = k
  48. func[k] = { k , "system", v }
  49. end
  50. end
  51. env.accept = func_id(func, "accept")
  52. env.response = func_id(func, "response")
  53. local function init_system(t, name, f)
  54. local index = system[name]
  55. if index then
  56. if type(f) ~= "function" then
  57. error (string.format("%s must be a function", name))
  58. end
  59. func[index][4] = f
  60. else
  61. temp_global[name] = f
  62. end
  63. end
  64. local path = assert(skynet.getenv "snax" , "please set snax in config file")
  65. local mainfunc, pattern = loader(path, name, G)
  66. setmetatable(G, { __index = env , __newindex = init_system })
  67. local ok, err = xpcall(mainfunc, debug.traceback)
  68. setmetatable(G, nil)
  69. assert(ok,err)
  70. for k,v in pairs(temp_global) do
  71. G[k] = v
  72. end
  73. return func, pattern
  74. end