Give a new instance initial properties using a return function

My first module was a little bit too complicated, so I removed the name/class assignment checking mess and made it just work like Instance.new, but with a return function that assigns properties.

Part Creator:

default = {
    Name = "RedCube";
    CanCollide = true;
    Anchored = false;
    Shape = 1;
    Size = Vector3.new(2,2,2);
    CFrame = CFrame.new();
    Position = Vector3.zero;
    Orientation = Vector3.zero;
    Material = 272;
    Transparency = 0;
    Reflectance = 0;
    Color = Color3.fromRGB(255,0,0);
    TopSurface = 0;
    BottomSurface = 0;
} :: Part

return {

    new = function(part: string, parent) -- ClassName
        part = Instance.new(part or 'Part', parent or workspace)
        -- no ClassName results in a regular part

        return function(inf)
        -- Properties to construct the part with

            for prop,val in pairs(default) do
                part[prop] = inf[prop] or val
            end
            -- construct the part, preferring given info over inherited defaults

            return part
        end

    end;

}

Script:

local physObj = require('Part Creator')

workspace.ChildAdded:Wait(3)

newCube = physObj.new() {
    Name = "Hello";
    Position = Vector3.new(10,2,15);
    Color = Color3.fromRGB(120,120,0);
} -- Creates and positions a part using these properties

-- Can also manipulate it later.
task.wait(5)

newCube.Orientation = Vector3.new(45,0,0)

It can be run without the added table. It will just result in the default red cube in the same way the regular Instance.new defaults in a grey rectangular brick.

We also have the option to remove the default option entirely and just rely on given info, if there is any:

return function(inf)
    for prop,val in pairs(inf or {})
        part[prop] = val
    end
    return part
end

If not, doesn’t matter. It just runs as Instance.new(‘Part’), which is kinda the point lol

1 Like