character.lua 967 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. local skynet = require "skynet"
  2. require "skynet.manager"
  3. local spawn = require "model.spawn"
  4. local character = { }
  5. function character.loadfrom(metadata)
  6. local usercenter = skynet.localname(".usercenter")
  7. local skynet_call = skynet.call
  8. local skynet_sleep = skynet.sleep
  9. local trigger = {}
  10. local t = spawn().loadfrom(metadata)
  11. rawset(t, "persist", function(k, v)
  12. trigger[k] = v
  13. end)
  14. local k = assert(t.uid)
  15. local function flushall()
  16. -- Execute all asynchronous setter
  17. local tmp = trigger
  18. trigger = {}
  19. for _, f in pairs(tmp) do
  20. f()
  21. end
  22. -- Serialize dirty data to array
  23. local pkg = t.pack(k)
  24. if pkg then
  25. -- Save data to database
  26. skynet_call(usercenter, "lua", "batch_save", pkg)
  27. end
  28. end
  29. character.flushall = flushall
  30. setmetatable(character, t)
  31. skynet.fork(function()
  32. while true do
  33. flushall()
  34. skynet_sleep(300)
  35. end
  36. end)
  37. return character
  38. end
  39. return character