Python1320

Metatable proposal

Jun 30th, 2014
378
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.39 KB | None | 0 0
  1.  
  2. local wep3 = {} -- our "Entity", imagine userdata here
  3.  
  4. -- helper, ignore
  5. local function set_lookup_fallback(what,towhere)
  6.    
  7.     local m = getmetatable(what)
  8.     if not m then
  9.         m = {}
  10.         setmetatable(what,m)
  11.     end
  12.     m.__index = towhere
  13.    
  14. end
  15.  
  16. -- Weapon and Entity metatable functions here like normally
  17. local WeaponFuncs={}
  18. local EntityFuncs={}
  19.  
  20. -- examples
  21. function WeaponFuncs:IsValid() print"COMMON (WEP)" assert(self==wep3)  return true end
  22. function EntityFuncs:IsValid() print"COMMON (ENT)" assert(self==wep3)  return true end
  23. function EntityFuncs:ent    () print"ENT (ENT)" end
  24. function WeaponFuncs:wep    () print"WEP (WEP)" end
  25.  
  26. -- weapon looks into entity metatable if it cant find something
  27. set_lookup_fallback(WeaponFuncs,EntityFuncs)
  28.  
  29. -- single entity specific
  30. -- these tables would need to be created for each entity
  31.     local wep3_data = {} -- this saves entity specific data
  32.    
  33.     set_lookup_fallback(wep3_data,WeaponFuncs) -- not found, lookup Weapon -> Entity
  34.    
  35.     local wep3_meta = {
  36.         __newindex=wep3_data,
  37.         __index=wep3_data,
  38.         __tostring=function() return "Weapon[3]" end,
  39.         --etc
  40.         }
  41.     setmetatable(wep3,wep3_meta)
  42.  
  43. -- testing
  44.     wep3.asd = 123
  45.     assert(wep3_data.asd==wep3.asd and wep3.asd==123,"data vanished")
  46.     assert(isfunction(wep3.IsValid),"wep3.IsValid not a function")
  47.     print("IsValid",wep3:IsValid())
  48.     wep3:wep()
  49.     wep3:ent()
  50.     print("tostring",tostring(wep3))
Advertisement
Add Comment
Please, Sign In to add comment