Posted: Tue Aug 23, 2016 6:12 pm Post subject: Averaging values in a lua table
So what i'm trying to do is:
Whenever the player starts a stage, the value of the character object speed is added to a table each tick until the player reaches the end of the stage.
At the end of the stage i want to stop adding stuff to the table, and instead average all the values. I want to output this value to a d3d text container in-game.
The code snippet:
Code:
if asMeter~=nil then asMeter.destroy(); asMeter = nil; end
asMeter=d3dhook_createTextContainer(fontmap,-1,640,"Average speed last run: N/A")
averageSpeed = {}
asTableLoop = 1;
calculateAverage = false
--calculate average speed
--This part of the code runs inside a timer
if (gameMode == 1) then
if(calculateAverage == false) then
calculateAverage = true
end
averageSpeed[asTableLoop] = playerSpeed
asTableLoop = asTableLoop+1
elseif (gameMode == 2) then
if (calculateAverage == true) then
local sum = 0
local ave = 0
local elements = #averageSpeed
for i = 1, elements do
sum = sum + averageSpeed[i]
end
ave = sum / elements
d3dhook_textcontainer_setText(asMeter, [[Average speed last run: ]] .. ave)
asTableLoop = 1;
averageSpeed = {}
calculateAverage = false
end
end
The current effect:
Regardless of gameState the asMeter text container always displays: "Average speed last run: N/A"
So what am i doing wrong? Would really appreciate it if anyone could point me in the right direction!
Check PlayerSpeed, or verify that each input inside your table is actually is a number, I believe your table contains bad inputs or somehow the calculation corrupts the desired output.
Try to print all table information (for key,value in pairs..), post it here, and also how do you set playerSpeed? _________________
I'm rusty and getting older, help me re-learn lua.
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum