I'm planning on implementing scripting support to embedded project coded in C. I have never done such thing before and found out about eLua.
My goal is to get a scripting support to my existing C based system. I would like to keep the C code running and doing its thing 'on the background' while the user script is running as well. The user script does not need to directly interface with any hardware, but is intended to build logic, like conditions, loops and timed events and the HW control is all handled in the C side.
In my use case the system is basically automation controller where the script would be user implemented logic and the C code would handle the interfacing with various interfaces and protocols (already implemented in C). The script can then just say 'turn on lamp number x' and the C code actually does the heavy lifting, packs and transmits the message to the correct lamp.
The problem I face is that all the examples I've found all either do everything in Lua, or the script is run to completion before any other things can happen. In my case that won't work because the C side needs to listen for inputs to uart for example. UART and the HW in general will be interrupt driven so its ok if the lua side takes some time to process its things.
I've read the documentation and looked at examples but cannot understand how (if it is possible even) to run a lua script while also running other C code.
Is there a way to do this in eLua? Or is there a better alternative. My goal eventually is to just run some user defined logic that can be changed easily.
my question is basically if I can do something like this with eLua:
int main() {
initialize_everything();
load_script_from_memory();
while(1) {
step_script();
step_other_logic();
if( has_new_script() ) {
load_new_script();
}
}
}
For reference my hardware at the moment is STM32 evaluation kit(STM32L476G-DISCO) to test the idea. If there is a better solution to my problem that would be more resource intensive I'm still also interested.
You need to learn how to do multi-threading on your target. Then put the processing of the script in one thread, and use more threads as you see fit for the other tasks that need to run concurrently.
This has nothing to do with Lua, as you show in your example source. Running the Lua script is nothing more than calling some C function. Just think how you would do it, if such a script were written as a sequence of C statements, which potentially block or run a long time.
A simple way of multi-threading is to use a periodic timer interrupt. Put the script executor in the main thread, and anything else in the timer ISR or other applicable interrupts. Make sure that this "anything else" never blocks and runs quickly as necessary.