Advertisement
eliasdaler

Safe_handle.lua

Jan 15th, 2017
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.92 KB | None | 0 0
  1. function getWrappedFunction(f)
  2.     -- this function will be called with handle, but we want to call it with raw reference
  3.     return function(handle, ...) return f(handle.cppRef, ...) end
  4. end
  5.  
  6. local memoizedEntityCppFuncs = {}
  7.  
  8. function createHandle(e)
  9.     local handle = {
  10.         cppRef = e,
  11.         isValid = true
  12.     }
  13.  
  14.     local mt = {}
  15.     mt.__index = function(handle, key)
  16.         if not handle.isValid then
  17.             error("Handle is invalid!", 2)
  18.         end
  19.  
  20.         -- memoizing functions speeds this up a lot
  21.         local memF = memoizedEntityCppFuncs[key]
  22.         if not memF then
  23.             memF = getWrappedFunction(Entity[key])
  24.             memoizedEntityCppFuncs[key] = memF
  25.         end
  26.         return memF
  27.     end
  28.  
  29.     setmetatable(handle, mt)
  30.     return handle
  31. end
  32.  
  33. function onEntityDeleted(handle)
  34.     handle.isValid = false
  35. end
  36.  
  37. function test(handle)
  38.     print("Calling through handle:", handle:getName())
  39. end
  40.  
  41. function test2(e)
  42.     print("Calling through raw reference:", e:getName())
  43. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement