Simplifying Code?

Hi, I have a Function that is called to calculate and determine the corners of a Part and then put them into a table depending on whether or not they’re of the Top or Bottom:

I was wondering if there were any way to simplify this as to remove all the constant table.insert just to help tidy it up a little bit?

Thanks!

local function GetPartCorners(Part)
local Size = Part.Size
	table.insert(Points.Top, Part.CFrame * CFrame.new(Size.X / 2, -Size.Y / 2, -Size.Z / 2))
	table.insert(Points.Top, Part.CFrame * CFrame.new(Size.X / 2, -Size.Y / 2, Size.Z / 2))
	table.insert(Points.Top, Part.CFrame * CFrame.new(-Size.X / 2, -Size.Y / 2, -Size.Z / 2))
	table.insert(Points.Top, Part.CFrame * CFrame.new(-Size.X / 2, -Size.Y / 2, Size.Z / 2))
	
	table.insert(Points.Bottom, Part.CFrame * CFrame.new(Size.X / 2, Size.Y / 2, -Size.Z / 2))
	table.insert(Points.Bottom, Part.CFrame * CFrame.new(Size.X / 2, Size.Y / 2, Size.Z / 2))
	table.insert(Points.Bottom, Part.CFrame * CFrame.new(-Size.X / 2, Size.Y / 2, -Size.Z / 2))
	table.insert(Points.Bottom, Part.CFrame * CFrame.new(-Size.X / 2, Size.Y / 2, Size.Z / 2))
end
local insert = table.insert
local t = {"Top", "Bottom"}
local function GetPartCorners(Part)
    local Size = Part.Size
    local positionX, positionY, positionZ
    for i = 1, 2 do
        for j = 1, 4 do
            positionX = ( (-1)^((j+(j%2))/2+1) ) * Size.X/2
            positionY = ( (-1)^(i) ) * Size.Y/2
            positionZ = ( (-1)^(j) ) * Size.Z/2
            insert(Points[t[i]], Part.CFrame * CFrame.new(positionX, positionY, positionZ))
        end
    end
end

I did this on a trial and error basis, so it can probably be improved.

4 Likes

Similar to your previous thread, just use the code I provided.

You would take the table of corners:

local Vertices = {
	{1, 1, -1},  --v1 - top front right
	{1, -1, -1}, --v2 - bottom front right
	{-1, -1, -1},--v3 - bottom front left
	{-1, 1, -1}, --v4 - top front left
	
	{1, 1, 1},  --v5 - top back right
	{1, -1, 1}, --v6 - bottom back right
	{-1, -1, 1},--v7 - bottom back left
	{-1, 1, 1}  --v8 - top back left
}

Then, you would use the iterator:

for _, Vector in pairs(Vertices) do
    local CornerPos = (Part.CFrame * CFrame.new(Size .X/2 * Vector[1], Size .Y/2 * Vector[2], Size .Z/2 * Vector[3])).Position
end

Use the iterator to insert values into the table:

local function GetPartCorners(Part)
    for _, Vector in pairs(Vertices) do
        table.insert(Points.Top, Part.CFrame * CFrame.new(Size .X/2 * Vector[1], Size .Y/2 * Vector[2], Size .Z/2 * Vector[3])).Position)
    end
end

This doesn’t really sort the top and bottom but, you get the general idea.


Having that many table inserts there doesn’t affect perform ace, it’s just a bit longer. You really don’t need to optimize that short of a code.

1 Like