interface.lua 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 mainfunc
  18. local function func_id(id, group)
  19. local tmp = {}
  20. local function count( _, name, func)
  21. if type(name) ~= "string" then
  22. error (string.format("%s method only support string", group))
  23. end
  24. if type(func) ~= "function" then
  25. error (string.format("%s.%s must be function"), group, name)
  26. end
  27. if tmp[name] then
  28. error (string.format("%s.%s duplicate definition", group, name))
  29. end
  30. tmp[name] = true
  31. table.insert(id, { #id + 1, group, name, func} )
  32. end
  33. return setmetatable({}, { __newindex = count })
  34. end
  35. do
  36. assert(getmetatable(G) == nil)
  37. assert(G.init == nil)
  38. assert(G.exit == nil)
  39. assert(G.accept == nil)
  40. assert(G.response == nil)
  41. end
  42. local temp_global = {}
  43. local env = setmetatable({} , { __index = temp_global })
  44. local func = {}
  45. local system = { "init", "exit", "hotfix", "profile"}
  46. do
  47. for k, v in ipairs(system) do
  48. system[v] = k
  49. func[k] = { k , "system", v }
  50. end
  51. end
  52. env.accept = func_id(func, "accept")
  53. env.response = func_id(func, "response")
  54. local function init_system(t, name, f)
  55. local index = system[name]
  56. if index then
  57. if type(f) ~= "function" then
  58. error (string.format("%s must be a function", name))
  59. end
  60. func[index][4] = f
  61. else
  62. temp_global[name] = f
  63. end
  64. end
  65. local pattern
  66. local path = assert(skynet.getenv "snax" , "please set snax in config file")
  67. mainfunc, pattern = loader(path, name, G)
  68. setmetatable(G, { __index = env , __newindex = init_system })
  69. local ok, err = xpcall(mainfunc, debug.traceback)
  70. setmetatable(G, nil)
  71. assert(ok,err)
  72. for k,v in pairs(temp_global) do
  73. G[k] = v
  74. end
  75. return func, pattern
  76. end