lua-users home
lua-l archive

Re: Injecting names & method chaining (was Re: [ANN] Penlight Libraries, First release)

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, May 5, 2009 at 2:20 PM, Petite Abeille wrote:
> Well, Objective-C had the concept of "category" for the longest time,
> and it hasn't collapse on its own weight yet.
That [1] looks like fun ;) The run-time check
"OBJC_PRINT_REPLACED_METHODS" apparently offers some help though,
perhaps somewhat similar to the "name conflict for module" error in
Lua's module function (loadlib.c).
I think it would be ideal if we could inject only lexically (the
injection limited to the lexical scope). With discipline, the wrapper
allows something like that:
On Mon, May 4, 2009 at 3:32 AM, steve donovan wrote:
> function module_fun (s1, s2)
> s1,s2 = S(s1),S(s2)
> ...
> ... s:trim() etc
> end
but we must not carelessly pass the wrapped object to functions
outside of the lexical scope expecting a string. We cannot guarantee
that our wrapper behaves exactly like a string because Lua strings are
not fully virtualizable [2].
An alternate idea is to modify the string metatable to be scope aware:
 -- framework
 local mt = debug.getmetatable('')
 local scope = {}
 function mt.__index(s, k)
 local f = debug.getinfo(2, 'f').func
 return scope[f] and scope[f][k] or string[k]
 end
 local function scoped_string_methods(t)
 local f = debug.getinfo(2, 'f').func
 scope[f] = t
 end
 -- test example libraries
 local stringx = {}
 function stringx.trim(self) return self:match('^%s*(%S*)%s*$') end
 local stringxx = {}
 function stringxx.trim(self) return self:match('^%s?(.-)%s?$') end
 -- test example
 function test2(s)
 assert(s.trim == nil)
 scoped_string_methods(stringxx)
 assert(s:trim() == ' 123 ')
 end
 function test(s)
 scoped_string_methods(stringx)
 assert(s:trim() == '123')
 test2(s)
 assert(s:trim() == '123')
 end
 local s = ' 123 '
 assert(s.trim == nil)
 test(s)
 assert(s.trim == nil)
 print 'DONE'
[1] http://kevincathey.com/code/detecting-conflicting-objective-c-category-methods/
[2] http://lua-users.org/wiki/LuaVirtualization

AltStyle によって変換されたページ (->オリジナル) /