lua-users home
lua-l archive

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


On Wednesday 21 April 2004 10:57, Nodir Temirhodzhaev wrote:
> Zimmermann, Maik wrote:
> > the problem here is that you are using the same
> > instance of pr in both coroutines. Try ...
>
> Yes, it works (as internal local function).
> But I want to do other thing.
> There is an external function (loaded lua-chunk), which uses
> global variable "out" as file to output.
> And new threads call this function, but outfile is different
> for each thread.
> How to implement such thing?
> (In 1 posting I showed how, but it's expensive.)

Option 1) Rewrite your external function (or wrap it at load time by adding 
strings at either end, or use a custom chunkreader) to make it look like this 
(untested):

-- External function
return function(out)
    return function()
        out:write("test")
    end
end

Now you can do:

-- Main code
local make_instance = dofile("inc.lua")
local a = make_instance(io.stdout)
local b = make_instance(io.stderr)

Now a and b point to the same bytecode, but with different values of out, and 
aside from the string manipulation (if you do it that way), the whole thing's 
probably more efficient than any method using globals.

Option 2) Of course, you're going to run into problems if this function uses 
any other globals and starts writing to them and screwing up other instances, 
so you may well be better off giving them individual environments, perhaps 
like this:

-- External function
return function()
    out:write("test")
end

-- Main code
local inc = loadfile("inc.lua")

local function make_instance(fn, out)
    local env = setmetatable({ out = out }, { __index = _G })
    local rf = fn()
    setfenv(rf, env)
    return rf
end

local a = make_instance(inc, io.stdout)
local b = make_instance(inc, io.stderr)

-- Jamie Webb