schema.lua 925 B

1234567891011121314151617181920212223242526272829303132
  1. local schema = {}
  2. function schema.new(k, default_value)
  3. assert(k)
  4. if default_value then
  5. local self = {
  6. assert_get = function(t) return assert(t.getspecific(k).get()) end,
  7. assert_runtime = function(t) return assert(t.getspecific(k).runtime) end,
  8. persist = function(t) t.persist(k, function() t.getspecific(k).save() end)
  9. end,
  10. load = function(t)
  11. if t.readonly then
  12. rawset(t, 'persist', function(...) end)
  13. end
  14. return t.register_specific(k, function()
  15. return default_value
  16. end)
  17. end
  18. }
  19. return self
  20. else
  21. local self = {
  22. assert_get = function(t) return assert(false, k) end,
  23. assert_runtime = function(t) return assert(t.getspecific(k).runtime) end,
  24. persist = function(t) return assert(false, k) end,
  25. load = function(t) return t.register_specific(k) end
  26. }
  27. return self
  28. end
  29. end
  30. return schema