Saturday 4 June 2016

'Truly global' variables pay off


In order to facilitate Rapid Application Development, the FireStorm game engine implements the Lua scripting engine, and also the Dear ImGui immediate-mode gui library.

One of the 'problems' when interfacing C and Lua code is that Lua likes to 'own everything', and does not easily share its data with other languages (like C, the language in which it was written). Allowing Lua to own all our application's runtime variables is the easy option, but it has a terrible price, and furthermore, Lua is not designed with hardware multithreading in mind - sharing data between one Lua state and the engine is one thing, but multiple Lua states means that letting Lua own anything is just a really bad idea - Lua is not the center of the Universe.

To be clear, I found that I had two concepts of 'global data' - the Lua global variables stored in (each) Lua State, and the C 'global data', but rather than choose one, I created a third - the C 'blackboard' whose sole purpose is to share data across all interested parties regardless of language or thread.

I chose to keep all my data on the C (engine) side, as the engine is my hub, my nexus, no matter how many threads are independently running Lua engine instances.
This turned out to be a good idea, with respect to ImGui.

You see, the immediate-mode GUI requires that we provide Pointers to Typed Data, which it can use to display variable contents, and also to allow their live editing.
But values in Lua don't have pointers, and we can't create them, so Lua variables are pretty much useless with respect to interfacing with the ImGui library.
Luckily, it's no problem to get raw pointers to the data held by the engine's 'truly global' shared data.

As a result, I'm able to smash out quite complex Application GUIs  with a fairly small amount of Lua Scripting, and to illustrate how handy that is, I can use the GUI to edit its own script, and reload the edited script into the Engine, without blinking an eye;)

No comments:

Post a Comment