开发者

Lua Copas, help clarifying how to handle multiple users

I'm a bit confused and think it's going to be an easy answer but my searches aren't helping me much :( I want to be able to do an skt:send anywhere. I could send it into OutToUser function as a parameter but I'm going to have a lot of different places I'll want to do this at and feel that will get too messy. I tried storing it something like Server.connections[key] = skt where key is host and port but can't figure out how to get host and port again later when I need it.

Any good solutions?

edit I get that it's a scope issue but not seeing a good solution as I'm new to lua.

require "copas"
Server = {}
function Server:new()
    local object = {}
    setmetatable(object, { __index = Server })
    return object
end

function Server:init()
    function handler(skt, host, port)
        while true do
            data = skt:receive()
            if data == "quit" then
                -- isn't going to work
          开发者_StackOverflow社区      OutToUser(data)

                -- this would work fine of course
                -- skt:send(data .. "\r\n")
            end
        end
    end

    server = socket.bind("*", 49796)
    copas.addserver(server, 
        function(c) return handler(copas.wrap(c), c:getpeername()) end
    )
    copas.loop()
end

function OutToUser(data)
    skt:send(data .. "\r\n")
end

server = Server:new()
server:init()


You can define OutToUser in the scope of the handler:

function Server:init()
    local function handler(skt, host, port)

        --make the function local to here
        local function OutToUser(data)
            --references the skt variable in the enclosing scope
            --(the handler function)
            skt:send(data .. "\r\n")
        end

        while true do
            data = skt:receive()
            if data == "quit" then
                OutToUser(data)
            end
        end
    end

    local server = socket.bind("*", 49796)
    copas.addserver(server, 
        function(c) return handler(copas.wrap(c), c:getpeername()) end
    )
    copas.loop()
end

Functions can always reference variables in their scope (function arguments and variables declared with local), even once they've left that scope - you can use that as an alternative solution, where you enclose the variables you want the function to use in a scope outside the function:

local function makeOTU(skt)

    --skt is visible in the scope of the function
    --that gets returned as a result

    return function(data)
        skt:send(data .. "\r\n")
    end
end

function Server:init()
    local function handler(skt, host, port)

    --create a function that references skt
    --as part of its closure
    local OutToUser = makeOTU(skt)

        while true do
            data = skt:receive()
            if data == "quit" then
                -- OutToUser is still referencing the
                -- skt from the call to makeOTU()
                OutToUser(data)
            end
        end
    end

    local server = socket.bind("*", 49796)
    copas.addserver(server, 
        function(c) return handler(copas.wrap(c), c:getpeername()) end
    )
    copas.loop()
end

Note the use of the local keyword in both of these examples: if you neglect the local, the name will ignore the scope altogether and go into / come from the global environment (which is just a table like any other: when you invoke a new Lua state, it's placed in the global _G), which is not what you want.

Keeping your variables local to their scope instead of using globals is important. Take, for example, these two functions:

local function yakkity(file, message)

    line = message .. '\n' --without local,
                           --equivalent to _G["line"] = message

    function yak() --without local,
                   --equivalent to _G["yak"] = function()

        file:write(line) --since no local "line" is defined above,
                         --equivalent to file:write(_G["line"])
    end
    for i=1, 5 do
        yak()
    end
end

local function yakker(file, message)
    line = message .. '\n' --without local,
                           --equivalent to _G["line"] = message

    return function()
        file:write(line) --again, since no local "line" is defined above,
                         --equivalent to file:write(_G["line"])
    end
end

Because their variables aren't defined as local, they clobber each other's data, leave their belongings lying around where anybody can abuse them, and just generally act like slobs:

--open handles for two files we want:
local yesfile = io.open ("yesyes.txt","w")
local nofile = io.open ("no.txt","w")

--get a function to print "yes!" - or, rather,
--print the value of _G["line"], which we've defined to "yes!".
--We'll see how long that lasts...
local write_yes = yakker(yesfile,"yes!")

--Calling write_yes() now will write "yes!" to our file.
write_yes()

--when we call yakkity, though, it redefines the global value of "line"
--(_G["line"]) - as well as defining its yak() function globally!
--So, while this function call does its job...
yakkity(nofile, "oh no!")

--calling write_yes(), which once again looks up the value of _G["line"],
--now does the exact OPPOSITE of what it's supposed to-
write_yes() --this writes "oh no!" to yesfile!

--additionally, we can still write to the nofile handle we passed to yakkity()
--by calling the globally-defined yak() function!
yak() --this writes a sixth "oh no!" to nofile!

--even once we're done with the file and close our handle to it...
nofile:close()

--yak() still refers to that handle and will still try to write to it!
yak() --tries to write to the closed file handle and throws an error!


I think all you need to do is have the OutToUser function also accept the skt argument, and pass it along from inside the handler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜