Lua scripting - Optimization

Document created by Thomas GENTILHOMME Champion on Mar 7, 2017Last modified by Thomas GENTILHOMME Champion on May 23, 2017
Version 2Show Document
  • View in full screen mode



I'm working with lua since few years now. I started lua for video games at first (where i writed the biggest framework of my life). During this time i learned how to control the lua GC and optimize the code to run as fast is possible.


NAS Lua scripting is a major component in the behavior and the life of CA UIM. However executing lua script stop the NAS processing ( So optimizing code is a important mission ).



1 - Declare variable as local


All variable have to be declared with the local keyword ! For people this is maybe something not very important ( but for the garbage collector it's important ^^ ). 


x = 5 become local x = 5 


Local variables are very quick, since they are accessed by index.

"Local variables are very fast as they reside in virtual machine registers, and are accessed directly by index. Global variables on the other hand, reside in a lua table and as such are accessed by a hash lookup." -- Thomas Jefferson


2 - Bind function in local block code (same as 1)


Processing local binded function is a lot faster than processing a global function. In my case my code will be a lot faster ( with a good optimization you can a improvment of 10-30% ). Be aware of the memory cost (i personnaly use this a lot when you have to while something). 


local alarms = alarm.get(); 

local sp = split(); -- Bind split as sp here

for _,v in pairs(alarms) do

    sp(v.message,'/'); -- use the binded function here.



3 - Do not declare variable if you dont use it


If you dont use the key or the value just put the underscore symbol. That mean your variable is not assigned and declared. It can be very useful when you dont need the value 

local alarms = alarm.get(); 

for k,_ in pairs(alarms) do

    -- Only 'k' is assigned !



It's work too when you give arguments to a function (or when you retrieve function arguments). 


4 - Variables scope (expr chunk)






to limit your code scope. This will help you to control variables and will let you avoid unused memory assignment. This can be used in many situations.


Hope you like it ! All theses tricks are pretty easy to do (this is why i writed this article). 


More read on lua optimization  

Note: All lua examples are developed by me.


Best Regards,


8 people found this helpful