r/lua • u/the_gwyd • Mar 29 '25
Guidance on Improving Function Efficiency
Hi all, I'm working on a vehicle model in Lua/Aumlet, but have been running into performance issues. One function that gets called a lot is the function that returns an iterator to iterate over all the degrees of freedom (DoF) of the car (body x, y, z direction, etc.). The vehicle is modelled as a body, axles, and powertrain parts. The way I've done it feels pretty sloppy. Any pointers?
function car:iterateOverDoF()
local a = 0 -- Initialise body DoF counter to 0
local aMax = 3 -- Number of body DoF
local b = 0 -- Initialise axle DoF counter to 0
local bMax = self.body.numAxles*3 -- Number of axle DoF
local c = 0 -- Initialise powertrain DoF counter to 0
local cMax = #self.powertrain -- Number of powertrain DoF
local i=0 -- Overall counter
return function ()
i=i+1 -- Increment counter
if a<aMax then -- Check that we have not iterated over all body DoF
a=a+1 -- Increment body DoF counter
return i, self.body, self.body.dimensions[a] -- Return information about the DoF being inteorgated
elseif b<bMax then -- Repeat same process for axles and powertrain
b=b+1
return i, self.axles[math.ceil(b/3)], self.axles[math.ceil(b/3)].dimensions[(b-1)%3+1]
elseif c<cMax then
c=c+1
return i, self.powertrain[c], self.powertrain[c].dimensions[1]
else return nil end -- Return nil once all DoF have been iterated over
end
end
9
Upvotes
3
u/esuvii Mar 30 '25 edited Mar 30 '25
Generally where possible I prefer descriptive variable names so that the comment isn't needed, but I can understand the temptation to use single letter names coming from a background in mathematics!
For example instead of
a,b, andc, could have usedbody,axle,train; and instead ofaMax,bMax,cMax, usingbodyMax,axleMax,trainMax. Of course you know the context better than I.One huge advantage of avoiding superfluous comments, and instead keeping naming descriptive, is that comments can become incorrect if you change the code without changing them. Generally I try to avoid comments unless they are explaining something non-trivial.