Lua limitation – 200 local variables

You wrote a big app with a lot of local variables. You try to run it only to find that it stops to an error saying too many local variables. What is this about?

The reason

Is simple, it’s a lua-limitation. That means it is not fixable for example by Jetimodel in an firmware update, we need to fix it ourself, in the code.

Problem

Let’s look at this code snippet:

local cell1, cell2, cell3, cell4, cell5, cell6 

-- Let's say we read telemetry here, let's emulate that
cell1 = 3.74
cell2 = 3.73
cell3 = 3.74
cell4 = 3.75
cell5 = 3.75
cell6 = 3.74

-- Let's do something with the values 
print("Cell Voltages:")
print("Cell 1:", cell1.."V")
print("Cell 2:", cell2.."V")
print("Cell 3:", cell3.."V")
print("Cell 4:", cell4.."V")
print("Cell 5:", cell5.."V")
print("Cell 6:", cell6.."V")

And the result is:

Cell Voltages:
Cell 1: 3.74V
Cell 2: 3.73V
Cell 3: 3.74V
Cell 4: 3.75V
Cell 5: 3.75V
Cell 6: 3.74V

What is happening here is that in order to use the 6 cell-values we are using 6 local variables. If we have a lot going on with for example a lot of telemetry values we might get close to 200 local variables. I had a look on my biggest app and it uses 91 variables so I’m safe on that one at least.

Anyway, solutions. What this is is enumeration of variables for storing values to. It’s not only storage since the values needs to be read too we need to consider that also.

Solution

Well, one of the solutions. Use a table, here’s the same snippet as above but with one local variable:

local voltages = {cell1, cell2, cell3, cell4, cell5, cell6}

-- Let's say we read telemetry here, let's emulate that
voltages.cell1 = 3.74
voltages.cell2 = 3.73
voltages.cell3 = 3.74
voltages.cell4 = 3.75
voltages.cell5 = 3.75
voltages.cell6 = 3.74

-- Let's do something with the values 
print("Cell Voltage:")
print("Cell 1:", voltages.cell1.."V")
print("Cell 2:", voltages.cell2.."V")
print("Cell 3:", voltages.cell3.."V")
print("Cell 4:", voltages.cell4.."V")
print("Cell 5:", voltages.cell5.."V")
print("Cell 6:", voltages.cell6.."V")

And the output of the snippet above:

Cell Voltage:
Cell 1: 3.74V
Cell 2: 3.73V
Cell 3: 3.74V
Cell 4: 3.75V
Cell 5: 3.75V
Cell 6: 3.74V

The same but with only one used variable, “voltages”.

To take into consideration

There is a very small performance hit when using tables in this way. At the moment I doubt it will have any real-life implications at all in our Jeti-use. But just in case it happens there is a way around that too. Maybe we’ll look into it next time, now, go coding and have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *