Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- nil-condition support module by alprog.
- Provide two form of expression syntax. First one is more readable
- but use debug.getlocal and may be unacceptable for some reason
- Unsafe call: Safe call (form 1): Safe call (form 2):
- a.b.c.d __.a.b.c.d.__ __(a).b.c.d.__
- foo:bar(1, 2, 3) __.foo:bar(1, 2, 3).__ __(foo):bar(1, 2, 3).__
- a.b:c('text').d.e __.a.b:c('text').d.e.__ __(a).b:c('text').d.e.__
- if such expressions acts as single call without using returned value
- the closing tag is not written:
- __.foo:bar(1, 2, 3)
- __(foo):bar(1, 2, 3)
- also this form may be convenient:
- Wrap(foo):bar(1, 2, 3)
- --]]
- local Wrapper = {}
- function Wrapper:__index(key)
- local object = rawget(self, 'object')
- if key == '__' then
- return object -- unwrap
- end
- if object then
- self.parent = object
- self.object = object[key]
- end
- return self
- end
- function Wrapper:__call(arg0, ...)
- local object = rawget(self, 'object')
- if object then
- if arg0 == self then
- local parent = rawget(self, 'parent')
- self.parent = object
- self.object = object(parent, ...)
- else
- self.parent = object
- self.object = object(arg0, ...)
- end
- end
- return self
- end
- function Wrap(object)
- local wrapper = { object = object }
- setmetatable(wrapper, Wrapper)
- return wrapper
- end
- local NilCondition = {}
- function NilCondition:__index(key)
- local index = 1
- while true do
- local name, value = debug.getlocal(2, index)
- if name then
- if name == key then
- return Wrap(value)
- end
- else
- break
- end
- index = index + 1
- end
- return _G[key]
- end
- function NilCondition:__call(object)
- return Wrap(object)
- end
- _G['__'] = {}
- setmetatable(__, NilCondition)
Advertisement
Add Comment
Please, Sign In to add comment