[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Namespace pollution
- From: Michal Kottman <k0mpjut0r@...>
- Date: Mon, 06 Dec 2010 13:36:02 +0100
On Mon, 2010-12-06 at 13:52 +0200, Dirk Laurie wrote:
> The author of the os and io extensions in
> http://lua-users.org/wiki/ExtensionProposal
> is criticized for polluting the standard namespaces. Now I can see the
> point in those cases, since the functions are never called object-ly,
> but always os.foo or io.foo.
One solution to "namespace pollution" is to create a function in your
module dedicated to "polluting" the global namespace, i.e. import().
When requiring the module, all functions can be stored in the module
table, in order to keep everything clean. If the user WANTS to bring the
functions to corresponding tables, like the globals table, or string,
os, io etc, he would call the import() function. Something along these
lines:
require 'ex':import()
-- this would bring all functions from 'ex' to corresponding 'os'
-- and 'io' tables
IMHO namespace pollution is not a problem, when you are the final user
of the code and you know what you can expect from your code (i.e. you
are responsible for it). It is different, when you are writing a module
and cannot expect in what context will it be used - better keep it safe
and clean.
> For example, having been a Pascal programmer when there was not much
> else to program in, I would love to write s[i] for s:sub(i,i).
> The closest I can get is to use LHF's tip and assign something to
> string metamethod __call so that s(i) means that. Fooling around
> with __index scares me.
For your Pascal-like string access, try the following:
getmetatable("").__index = function(s,i)
if tonumber(i) then
return string.sub(s,i,i)
else
return string[i]
end
end
s="abcd"
print(s[2], s:sub(3)) -- b cd