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
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:
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:Note the use of the
localkeyword in both of these examples: if you neglect thelocal, 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:
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: