[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to set the environment of a function
- From: Tomas Guisasola Gorham <tomas@...>
- Date: Sat, 7 Jul 2007 22:05:38 -0300 (BRT)
Hi Sherry
On Sun, 8 Jul 2007, Sherry Zhang wrote:
> hi,
> Now I have a program like
>
> a={}
> a["foo"]=function() bar() end
> a["bar"]=function () print("Hello") end
> function p(t) foo() end
> p(a)
>
> when running p(a) , I want to get the "Hello" output.
> and I want to know two easy way to do that.
> ( I do not ways like for k, v in pairs(t) do ... end)
You can change the environment of the functions to
let the code works:
...
setfenv(a.foo, a)
setfenv(p, a)
p(a)
Or you could change function p:
function p(t) t.foo() end
Then it will call the function at member "foo" of
the given table.
Also you should change a.foo to:
function a.foo() a.bar() end
Or maybe you would like to rewrite it:
a = {
foo = function (self) self:bar() end,
bar = function (self) print("Hello") end,
}
function p(obj) obj:foo() end
p(a) -- => a:foo() => a:bar() => print("Hello")
> 1 how to set it outside the function and leave the function unmodified?
> 2 how to set it inside the function?
I didn't understand the questions :-(
Regards,
Tomás