Mass-Assigning Variables

I have a system where I find myself assigning variables to a bunch of parts. This appears to be unavoidable, as I need to manage the properties of each individual part in a lighting pattern.

Is there a way I could loop through a model and assign a new variable to each part based on its name?

You can create a Table with all your variables.

For example

local Variables = {}
Variables[“RandomTable”] = {String = “yes”}
Variables[“Debounce”] = true
print(Variables[“RandomTable”].String)
print(Variables[“Debounce”])

https://developer.roblox.com/en-us/articles/Table

I’ve thought about using this, yes. What I’m specifically looking for is if I can assign a variable to a part’s name for a group of parts.

(psuedocode)

local groupOfParts = {}

for i, v in pairs(workspace.Lights:GetChildren()) do
    print(v.Name)
end
-- V1
-- V2

for i = 1, #groupOfParts do
    variable = groupOfParts[i]
end

print(V1) -- workspace.Model.V1
print(V2) -- workspace.Model.V2
print(V3) -- nil

I’m thinking that, in this instance, what you might be looking for is OOP: All about Object Oriented Programming

Otherwise, I believe there are multiple ways to construct a table to meet your needs. OssieNoMae suggested one above and here is a suggestion that I think is more in line with your requirements:

local variableTable = {
  {
    ["memberParts"] = {
      workspace.Part1,
      workspace.Part2,
      workspace.Part3,
    },
    ["Variable1"] = false,
    ["Variable2"] = 123,
    ["Variable3"] = "abcdefg",
  },
}

The downside to the above solution would be the time spent searching through the table and finding the subtable containing the part you want. This would require two for loops unfortunately.

1 Like

Though you can’t assign a variable directly to your script through your own script at runtime, you can use tables and instead assign keys inside it with your model’s child as the value as such:

local model = workspace.MyModel
local a = {}

for _, child in pairs(model:GetChildren()) do
    if child:IsA("BasePart") then
        a[child.Name] = child
    end
end

--[[
Let us assume there were parts named "Part1", "Part2" and "Part3" in the model
now you can do things like this:
]]

a.Part1.Transparency = 1
print(model.Part1.Transparency) --> 1

This isn’t truly a direct variable but hey, it’s just two characters a. more ¯\_(ツ)_/¯

1 Like