Jump to content

table.reverse util indexing mistake


CarlZalph
  • Fixed

data/scripts/util.lua:115-125::

-- only for indexed tables!
function table.reverse ( tab )
    local size = #tab
    local newTable = {}
 
    for i,v in ipairs ( tab ) do
        newTable[size-i] = v
    end
 
    return newTable
end

Wrong: newTable[size-i] = v

Correct: newTable[size-i+1] = v

Otherwise it starts indexing at index 0, which is not how an indexed table starts.

 

Also I'd like to note that this is not used anywhere in the Klei base code, so it'd only affect mods.

Double note that this is O(n) where a reverse can be O(n/2) by only swapping, though this loses the behaviour of the function by not touching the original table.


Steps to Reproduce
Use the utility function 'table.reverse' on any table and see it generate a table that starts at index 0.



User Feedback


A developer has marked this issue as fixed. This means that the issue has been addressed in the current development build and will likely be in the next update.

Slight optimization is to pull the +1 out of the loop and shove it onto the 'size' via: local size = #tab + 1

Not sure how LUA script compiles in the JIT portion or if it does any optimization at all, so this may or may not be beneficial.

Personally I fall in the camp of 'trust nothing a compiler does' due to how many nuances each tend to have.

Share this comment


Link to comment
Share on other sites



Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
  • Create New...