Lua: Sane Granular Defaults for User Supplied Data


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. local mooDB
  2.  
  3. local defaults = {
  4. a = {
  5. foo = "bar"
  6. },
  7. b = 1,
  8. c = {
  9. bar = "foo"
  10. },
  11. }
  12.  
  13. if not mooDB then
  14. -- NOTE: This would not be in the actual real world code. This
  15. -- simulates user data, normally loaded from some sort
  16. -- of datastore, which is SavedVariables in the case of
  17. -- World of Warcraft.
  18. mooDB = {
  19. c = {
  20. bop = "whee"
  21. }
  22. }
  23. end
  24.  
  25. function inheritdefaults(t, defaults)
  26. for k,v in pairs(defaults) do
  27. if t[k] then
  28. if type(v) == "table" then
  29. inheritdefaults(t[k], v)
  30. end
  31. end
  32. end
  33.  
  34. local mt = getmetatable(t) or {}
  35. function mt:__index(k)
  36. return defaults[k]
  37. end
  38. return setmetatable(t, mt)
  39. end
  40.  
  41. inheritdefaults(mooDB, defaults)
  42.  
  43. assert(mooDB ~= defaults)
  44. assert(mooDB.a == defaults.a)
  45. assert(mooDB.c ~= defaults.c)
  46. assert(mooDB.a.foo == "bar")
  47. assert(mooDB.b == 1)
  48. assert(mooDB.c.bar == "foo")
  49. assert(mooDB.c.bop == "whee")

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.