Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do i create a function parameter with UDIM2, or vectors?

Asked by 3 years ago

I am trying create a function that will create an ImageLabel. Within this function, i would like to pass a parameter that alters the size of my label.

local function CreateImageLabel(parent,name,image,size)
    local imagelabel = Instance.new('ImageLabel',parent)
    imagelabel.Size = UDim2.new(size)
    imagelabel.Image = image
    return imagelabel
end

i would like to call this function like so:

`` imagelabel = CreateImageLabel(parent,'label','rbx.whatever', (1,0,1,0))

My function will not work. Would i have to change it to:

local function CreateImageLabel(parent,name,image,x,y)
    local imagelabel = Instance.new('ImageLabel',parent)
    imagelabel.Size = UDim2.new(x,0,y,0)
    imagelabel.Image = image
    return imagelabel
end

or is there a clean way to achieve what im trying to do?

2 answers

Log in to vote
0
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago
local function ConstructImageLabel(ParentInstance, Name, ImageID, ScaleSize)
    local ImageLabel = Instance.new("ImageLabel")
    ---------------
    ImageLabel.Image = "rbxassetid://" .. ImageID
    ImageLabel.Size = UDim2.fromScale(unpack(ScaleSize))
    ---------------
    ImageLabel.Name = Name
    ImageLabel.Parent = ParentInstance
    ---------------
    return ImageLabel
end


--// ConstructImageLabel(ScreenGui, "ExampleLabel", 123456789, {1, 1})
0
This answers exactly what i needed to know. Thank you. I am learning roblox's lua, and lua in general. Thanks a ton! norogumi 2 — 3y
Ad
Log in to vote
0
Answered by 3 years ago

You could use a loop and pass in a config table like so:

--What would be passed to `CreateImage`, you can add any valid property of ImageLabel
local Configurations = {
    Name = "SomeName";
    Size   = UDim2.new(1,0,1,0);
    Parent = PlayerGui
}

function CreateImageLabel(Configs)
    local newImage = Instance.new("ImageLabel")
    for property, value in pairs(Configs) do
        newImage[property] = value
    end
    return newImage
end

But if you really want to pass in the properties as separate values then you can do:

--size will be just a regular Array, table unpack places the array as if you placed these in the UDim2.new parameters individually by hand
local size = {1, 0, 1, 0}
local function CreateImageLabel(parent,name,image,size)
    local newImage = Instance.new('ImageLabel')
    newImage.Size = UDim2.new(table.unpack(size))
    newImage.Image = image
    newImage.Name  = name
    newImage.Parent = parent
    return newImage 
end

Answer this question