EnAppelsin / SHARCarRandomiser

Randomiser Mod for Simpsons Hit & Run
https://enappelsin.github.io/SHARCarRandomiser/
14 stars 6 forks source link

Fixes several issues and optimises the code. #4

Closed jakeandreoli closed 6 years ago

jakeandreoli commented 6 years ago

Optimised the code to use Lua's built in table count method. I removed:

RandomCarPoolN = 0
for i in ipairs(RandomCarPool) do
    RandomCarPoolN = RandomCarPoolN + 1
end

and changed it to this:

-- Count number of random cars
RandomCarPoolN = #RandomCarPool

You could theoretically update other parts of the code to not reference RandomCarPoolN and just use #RandomCarPool - I did not make this change because I felt that should be up to the maintainer.

Moved the NoHusk check above the count so that we don't have to remove redundant code. To prevent looking up the count for RandomCarPoolN multiple times, we moved the NoHusk check above it. There's no need for it to be below it.

I changed the following about the code to optimise it:

-- Add the husk unless disabled
if GetSetting("NoHusk") == false then

changed to

-- Add the husk unless disabled
if not GetSetting("NoHusk") then

GetSetting("NoHusk") returns a boolean, so when it's enabled, instead of checking true == false, we'll check to see it's not true.

"huskA" is now added using table.insert to fix a bug where it was replacing the last entry (zombi_v) of the table. In your original version, you would replace "zombi_v" when using RandomCarPoolN to index the table and add huskA.

using table.insert avoids this issue and makes the code neater.

This also fixes a potential crash where if math.random returns the last number, it would go outside the array. After adding this, you were adding one to RandomCarPoolN. If math.random returned the total of RandomCarPoolN, you would have a Lua error which would cause a crash.

Sincerely, Jake Andreøli Co-Founder of Donut Team

EnAppelsin commented 6 years ago

Thanks for the corrections! I am more used to 0-based arrays.