Guest User

Lua nil-condition support module for Defold game engine

a guest
Jun 10th, 2016
402
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.85 KB | None | 0 0
  1. --[[
  2.  
  3.  nil-condition support module by alprog.
  4.  Provide two form of expression syntax. First one is more readable
  5.  but use debug.getlocal and may be unacceptable for some reason
  6.  
  7.  Unsafe call:         Safe call (form 1):       Safe call (form 2):                      
  8.  
  9.  a.b.c.d              __.a.b.c.d.__             __(a).b.c.d.__
  10.  foo:bar(1, 2, 3)     __.foo:bar(1, 2, 3).__    __(foo):bar(1, 2, 3).__
  11.  a.b:c('text').d.e    __.a.b:c('text').d.e.__   __(a).b:c('text').d.e.__
  12.  
  13.  if such expressions acts as single call without using returned value
  14.   the closing tag is not written:
  15.  
  16.  __.foo:bar(1, 2, 3)
  17.  __(foo):bar(1, 2, 3)
  18.  
  19.   also this form may be convenient:
  20.  
  21.  Wrap(foo):bar(1, 2, 3)
  22.  
  23. --]]
  24.  
  25. local Wrapper = {}
  26.  
  27. function Wrapper:__index(key)
  28.   local object = rawget(self, 'object')
  29.   if key == '__' then
  30.     return object -- unwrap
  31.   end
  32.  
  33.   if object then
  34.     self.parent = object
  35.     self.object = object[key]
  36.   end
  37.   return self
  38. end
  39.  
  40. function Wrapper:__call(arg0, ...)
  41.   local object = rawget(self, 'object')
  42.   if object then
  43.     if arg0 == self then
  44.       local parent = rawget(self, 'parent')
  45.       self.parent = object
  46.       self.object = object(parent, ...)
  47.     else
  48.       self.parent = object
  49.       self.object = object(arg0, ...)
  50.     end
  51.   end
  52.   return self
  53. end
  54.  
  55. function Wrap(object)
  56.   local wrapper = { object = object }
  57.   setmetatable(wrapper, Wrapper)
  58.   return wrapper
  59. end
  60.  
  61. local NilCondition = {}
  62.  
  63. function NilCondition:__index(key)
  64.   local index = 1
  65.   while true do
  66.     local name, value = debug.getlocal(2, index)
  67.     if name then
  68.       if name == key then
  69.         return Wrap(value)
  70.       end
  71.     else
  72.       break
  73.     end
  74.     index = index + 1
  75.   end
  76.   return _G[key]
  77. end
  78.  
  79. function NilCondition:__call(object)
  80.   return Wrap(object)
  81. end
  82.  
  83. _G['__'] = {}
  84. setmetatable(__, NilCondition)
Advertisement
Add Comment
Please, Sign In to add comment