title: How to prevent race condition in Lua?
body: <p>I am writing a Lua script that uses a library to access a hardware device with buttons. I register a callback function to handle the button presses. The code looks like:</p>
  
  <pre><code>globalvar = {}
  
  function buttonCallback(buttonId)
      ...accessing globalvar
  end
  
  device.RegisterButtonCallback("buttonCallback")
  
  while true do
  end
  </code></pre>
  
  <p>This works.</p>
  
  <p>Now I want to update the globalvar not only at a button presses but also at 1 minute intervals. Since I will need to access a network resource anyway I plan on using the socket.select call to get the 1 minute interval.</p>
  
  <pre><code>#require "socket"
  
  globalvar = {}
  
  function buttonCallback(buttonId)
      ...access globalvar
  end
  
  device.RegisterButtonCallback("buttonCallback")
  
  while true do
      socket.select(nil, nil, 60)  -- wait 60 seconds
      ...access network
      ...access globalvar
  end
  </code></pre>
  
  <p>Now I am concerned about the concurrent access of the globalvar. How can I prevent race conditions here? Most sources on multithreading in Lua advise to use continuations in cooperative scheduling but I don't see how that could be applied in my case.</p>