views:

668

answers:

1

My embedded project contains a Qt application for the PC which is mainly a simulator for debugging and testing. In the application I can create several widgets which represent either my embedded software or simulate the hardware controlled by the application or can generate external inputs for testing.

I plan to improve the application by adding Lua scripting so that the widgets can be created or controlled from a script. I need an elegant way for single stepping the scripts. I plan scripts like:

createThermometerWidget(10,20,30)
while time < maxTime do
  setTemperature(20+time/1000)
  pauseSimulation()
  time = time + 1
end

The custom function pauseSimulation should stop the Lua script, enable the Qt event loop to run so that interaction with the software is possible (seting other inputs for example) and after pressing a button the script will continue.

My first idea was to create a separate thread for the Lua execution which will be stopped by pauseSimulation and released by the button. But Qt widgets cannot be created from non-main thread so that I will have to create all widgets in the main thread and pass all constructor parameters from Lua functions to the main thread.

Is there a more smooth way?

+3  A: 

Coroutines are one approach to implementing this. Your pauseSimulation() can internally call coroutine.yield(), and be restarted later by a call to coroutine.resume() from the button's action. The problem is that your UI is at the mercy of your script fragments, since the only way to halt a running coroutine is for it to eventally call yield().

Alternatively, you can use the Lanes module to put part of your Lua application into a separate thread. You would use a Linda to pass messages from the main Qt widget thread to your simulator's worker thread. This would have the advantage that the UI thread is not blocked by the simulation which runs in its own thread.

RBerteig
Thank you very much.
danatel
Qt has decent multi-threading support. You can use QThreads rather than Lanes for synchronizing lua with Qt's GUI. Lua's thread would work in a loop that only receives messages from GUI and resumes different coroutines. One less external library to worry about.
Tadeusz A. Kadłubowski
My only concern there is that Lua itself is not necessarily thread safe or thread aware. It is safe to keep a separate Lua state in each thread, but that state must only be accessed from within that thread. If the Qt binding to Lua makes that easy to achieve, then that is a good solution. Lanes provides safely synchronized data transfer between OS threads which addresses some of that concern.
RBerteig