function DrawCard() local Random = math.random(1,7) -- Create Switch Case local Factions = { [1] = 'Wisdom', [2] = 'Bounty', [3] = 'Might', [4] = 'Culture', [5] = 'Balance', [6] = 'Marauders', [7] = 'Privateer' } print(Factions[Random]) script.Parent.Factions[Random].Value = -1 end
Say that Random = 1
print(Factions[Random]) -- Prints Wisdom to output
Then why does
script.Parent.Factions[Random].Value = -1 -- Throw an exception of "1 is not a valid member of script?
I know I can reverse the table to do this, however I am trying to find a much more efficient way and I think there is a much simpler way to do this if I don't reverse it.
Random
in your example is a number. You are trying to access your Factions object using this number in square brackets. You need to access your faction by its name, not using a number.
local factions = { 'Wisdom', 'Bounty', 'Might', 'Culture', 'Balance', 'Marauders', 'Privateer' } -- we generate a random number ranging from [1, #factions], where -- `#factions` is the length of the `factions` table. local rand = math.random(#factions) local chosen = factions[rand] -- we then get the name out of the table -- from the random position -- finally, we get the faction object itself using this name local faction = script.Parent.Factions:FindFirstChild(chosen) -- ensure `faction` exists if faction then -- it exists; we can continue on else -- it does not exist :( end
As a side note, I'd like to encourage you to use different variable names for your Factions object and your factions table, to make your code less ambiguous and easier to read.
I am going to assume here that your structure is organized in your workspace like so:
Parent ThisScript Wisdom Bounty Might Culture Balance Marauders Privateer
So you seem to want to access these IntValue objects (I assume they are), depending on what card is drawn. To do this, you should use FindFirstChild
rather than indexing using .
. This is true for any time you want to index a varying property or child.
You should change the line to:
local chosenFaction = script.Parent:FindFirstChild(Factions[Random]) if chosenFaction then chosenFaction.Value = -1 end
Hope this helps! :)