There is an orange underline on “sc” with a little dialog saying:
Is there something wrong with this? Is it recommended to really change it? Cuz to be honest this lil problem never happened to me before with the same code.
Tables in luau are really two things put in one, an array and a dictionary.
An array is basically a list of stuff, like {1, 2, 3}. #sc would only get the length of this part.
A dictionary is basically anything else in the table. Examples:
-- numeric indices are not continous, so this is "really" a dictionary
-- the "length" of this table would be 1, since there is only one numeric index
-- that is part of the "continous run"
{
[1] = 1,
[3] = 3,
}
-- string indices, so definitely not an array
-- the "length" of this table would be 0, since there is no array part of this table
{
s1 = sounds:WaitForChild("I_Strike_01"),
s2 = sounds:WaitForChild("I_Strike_02"),
s3 = sounds:WaitForChild("I_Strike_03"),
s4 = sounds:WaitForChild("I_Strike_04")
}
If there’s no reason for the table to have string indices, just write:
local sc = {sounds:WaitForChild("I_Strike_01"), sounds:WaitForChild("I_Strike_02"), sounds:WaitForChild("I_Strike_03"), sounds:WaitForChild("I_Strike_04")}
The # operator is not supposed to give you the length of a dictionary.
As it only works if the array that starts with an integer key of 1.
Explanation (hopefully): The # operator on different types
Arrays
local exampleTable = {10, 20, 30, nil, 50} -- {[1] = 10, [2] = 20, [3] = 30, [4] = nil, [5] = 50}
print(#exampleTable) -- prints 3
--the length of the array is 3 because there are three elements before the first `nil` value
local x = {[2] = 10, [3] = 20}
print(#x) -- prints '0' because '[1]' doesn't have a value therefore `nil`
Dictionaries
local dictionary = {name = "John", age = 30}
print(#dictionary) -- Output: 0 (not reliable)
--`#` returns '0' because the keys are not consecutive integers.
Suggestion
Use:
i = 0
for _ in (sc) do
i += 1
end
local rs = sc["s".. tostring(math.random(1, i))] -- if you still want to access the key as `s{number}`
Thank you so much! I fixed it by myself yesterday but i forgot to post it here, but still, you explained perfectly what happens here, thank you so much!
Glad you fixed it, but I just want to clarify 1 thing which you might need in the future. Tables are of 2 types:
Arrays
Dictionaries
Arrays are those types of tables in which the indexes are numbers.
Dictionaries are those types of tables in which the indexes are string or something else.
Your original code’s sc table was a dictionary and you cannot use # on a dictionary. # is only allowed on arrays, so you’d have to do workarounds if you want to be able to check the length of any table.
This is personally how I do it:
local function CheckLength(t: { [any]: any })
local Index = 0
for i, _ in t do
Index += 1
end
return Index
end