lua-users home
lua-l archive

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


I want that to be transparent to the function definer, so my class object looks like this:

MyClass = {
  __newindex = function (table, key, value)
    if type(value) == "function" then
      setfenv(value, table)
    end
    rawset(table, key, value)
  end
}

My "new" function takes a table to use for the object, so it goes through it an calls setfenv() on each function, like this:

function MyClass.new(obj)
   obj = obj or {}
   for k, v in pairs(obj) do
     if type(v) == "function" then
       print ("Setting environment for ", k)
       setfenv(v, obj)
     end
   end
   setmetatable(obj, MyClass)
   MyClass.__index = MyClass
   return obj
end

For a class with no base class, I need to do this:

setmetatable(MyClass, {__index = _G})

Best,
Martin

David Given wrote:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Martin C. Martin wrote:
[...]
For an OO style while accessing fields is more common than globals, the
environment option seems cleaner than the standard : option.  Are there
any down sides that I'm missing?

Correct me if I'm wrong, but won't the same function (with one
environment) need to be shared among several different objects? Won't
you have to explicitly call setfenv() at the top of each method,
preventing them from being called reentrantly?

- --
┌─── dg@cowlark.com ───── http://www.cowlark.com ─────
│
│ "All power corrupts, but we need electricity." --- Diana Wynne Jones,
│ _Archer's Goon_
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFJ36h9f9E0noFvlzgRAhB3AKCll17SHhX4H985QHJIiWFGSKraKACgiIiU
UZuWXvTP18z81yD/xqMHK5o=
=OixL
-----END PGP SIGNATURE-----