[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Namespace pollution
- From: David Manura <dm.lua@...>
- Date: Mon, 6 Dec 2010 21:56:48 -0500
On Mon, Dec 6, 2010 at 6:52 AM, Dirk Laurie <dpl@sun.ac.za> wrote:
> Now I can see the point in those cases, since the functions are never
> called object-ly, but always os.foo or io.foo.
Injecting into os is probably unjustified since you can alias: local
os = require 'os.extended' .
> However: what about the case of string functions?
That's a problem.
I once tried to address it with a new type of metamethod that applied
to all objects but only within a lexical scope [1]:
do
local function __index(t,k)
if type(t) == 'string' then return t:sub(k,k) else return t[k] end
end
print(("foo")[2], math.sqrt(2))
end
-- [1] http://lua-users.org/lists/lua-l/2010-06/msg00515.html
but that has some runtime overhead when different types exist in the
scope. Here's a refinement of that idea, related to the _ENV concept
in Lua 5.2-alpha:
local env_string = setmetatable({}, {__index = at}}
do
local _ENV_STRING = env_string
print(t[2], math.sqrt(2))
end
Within the scope of the variable _ENV_STRING, all index operations on
strings would go through the value of _ENV_STRING. The VM would need
some support for knowing how to look into _ENV_STRING (as well as
_ENV_FUNCTION, _ENV_NUMBER, etc.--perhaps all of which could somehow
be stuffed into _ENV's metatable).
You may also want to combine that idea with the previously discussed
__methindex proposal, which breaks the equivalence between indexing
'.'/'[' and method call ':' operators so that s[i] and s:match(...) no
longer conflict.