[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: [RFC] Local function call
- From: "Jérôme VUARAND" <jerome.vuarand@...>
- Date: Sun, 28 May 2006 13:51:04 -0400
Hi list,
I had an idea this morning, and it's worth a mail to the Lua mailing
list. Please read to the end, the idea comes at the end.
I was thinking of yet another object oriented implementation that
would roughly look like that (it's a bit long, but nothing really
interesting for now, keep reading) :
-- Yet another class implementation
function class(classname)
return function(members) -- this is for parenthesis-less argument chaining
local caller_env = getfenv(2) -- we will declare the class in
callers environment
caller_env[classname] = {
new = function()
local object = {} -- we copy data members as is
local methods = {} -- we put methods in object metatable's __index table
for k,v in pairs(members) do
if type(v)=="function" then
methods[k] = v
else
object[k] = v
end
end
setmetatable(object, {__index=methods})
return object
end;
}
end
end
-- Let's create a class
class "CFoo"
{
a = 1;
b = 2;
c = nil;
amethod = function(self)
self.c = self.a + self.b;
end;
}
-- Let's instantiate an object
local obj = CFoo.new()
print(obj.c)
obj:amethod()
print(obj.c)
----
Ok, tested and that works. A big drawback is that I can't declare
local classes, because getfenv returns only global environments. And
here come the idea. I thought it would be nice to be able to write :
-- Let's create a local class
local class "CFoo"
{
a = 1;
b = 2;
c = nil;
amethod = function(self)
self.c = self.a + self.b;
end;
}
----
The Lua compiler complains because there is no = signe before "CFoo".
It means that it's a possible future additionnal valid situation in
the Lua language. And what means the above block ? It can be
simplified as :
local f()
It's what I call a local function call (the call is local, not the
function). And the only difference with the normal function call, is
that inside the function, getfenv(2) returns a table of the local
variables of the caller chunk (with eventually the real environment
accessible in metatable __index of that table). That way the exact
same implementation of my class function above would do what I want.
I think it would be a nice addition to the future of Lua. I have no
idea of the possible implementation difficulties that exist in current
Lua implementation, but the principle is rather simple. What do you
think of it ?
Jérôme.