title: Lua NodeMCU net.udpsocket:listen - how to handle the possibility of the socket already being open?
body: <p>I need to listen on an UDPsocket, but I don't know if the listener is already running.</p>
  
  <p>I tried this approach to close any existing UDPsocket:</p>
  
  <pre><code>s=net.createUDPSocket()
  s:on("receive",function(s,c) 
  
  .... snip - define the handler ......
  
  if (s~=nil) then 
      s:close()
      print("closing previous instance of UDP Server")
  end
  
  s:listen(7333)
  print("UDP Server started")
  </code></pre>
  
  <p>If the socket is open, this fails with:</p>
  
  <pre><code>PANIC: unprotected error in call to Lua API (udpserver.lua:104: not connected)
  </code></pre>
  
  <p>Then I tried this approach to only call listen if the socket didn't exist:</p>
  
  <pre><code>if (s==nil) then 
     s:listen(7333)
     print("starting UDP Server")
  else
      print("Previous instance of UDP Server")
  end
  </code></pre>
  
  <p>That doesn't work - s is never nil and I get "Previous instance of UDP Server" after a restart, but the socket is not actually listening. </p>
  
  <p>Simply calling s:listen(7333) without any checking results in </p>
  
  <pre><code>PANIC: unprotected error in call to Lua API (udpserver.lua:105: address in use)
  </code></pre>
  
  <p>when the code is run and s:listen has previously been run. </p>
  
  <p>I assume s=net.createUDPSocket() causes s to be non-nil, regardless of whether s:listen is ever called.  How can I detect whether listen has been called, or needs to be called? </p>
  
  <p>EDIT - I'm new to Lua, and was thinking about the error "unprotected call"... So maybe there is a way to protect the call?  Some searching, and I learned about <a href="https://www.lua.org/manual/5.3/manual.html#pdf-pcall" rel="nofollow noreferrer">pcall</a>. So I tried this approach:</p>
  
  <pre><code>lstatus, lret = pcall(s:listen,7333)     -- protected call to listen
  if lstatus then 
     print("starting UDP Server")
  else
      print("UDP Server - listen returned:",lret)
  end
  </code></pre>
  
  <p>Surprisingly, I get this result:</p>
  
  <pre><code>PANIC: unprotected error in call to Lua API (udpserver.lua:104: function arguments expected near ',')
  </code></pre>
  
  <p>So the Protected Call itself is unprotected. </p>