ledger.lua 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. local __meta = {
  2. balances = {},
  3. payments = {},
  4. alls = {}
  5. }
  6. local david;
  7. local mt = {
  8. __index = function(table, key)
  9. return "dynamic value for " .. key
  10. end,
  11. __newindex = function(table, key, value)
  12. error(key .. " is a read only property")
  13. end
  14. }
  15. setmetatable(__meta.balances, mt)
  16. setmetatable(__meta.payments, mt)
  17. local globalMeta = {
  18. __index = function(table, key)
  19. print("Accessing undefined key:", key)
  20. if key == "balances" then
  21. return __meta.balances
  22. elseif key == "payments" then
  23. return __meta.payments
  24. end
  25. return __meta.alls[key]
  26. end,
  27. __newindex = function(table, key, value)
  28. print("set " .. key .. " dynamically to " .. value)
  29. __meta.alls[key] = value
  30. end
  31. }
  32. setmetatable(_G, globalMeta)
  33. -- Accessing existing keys
  34. print(balances.key1) -- Output: value1
  35. print(balances.key2) -- Output: value2
  36. -- balances.key1 = "value 1"
  37. -- Accessing undefined key
  38. print(balances.key3)
  39. print("xxx")
  40. print(payments.key3)
  41. print("v => " .. cesar)
  42. print("v => " .. david)