I am making a character selection screen for a game I’m working on, but whenever I use the arrows, it returns “Attempt to get length of nil value”. Any idea why this is happening?
Here is the code
local CurrentPokemon = "Mudkip"
local PokemonList = {
"Bulbasaur", "Charmander", "Squirtle",
"Pikachu", "Chikorita", "Cyndaquil",
"Totodile", "Treecko", "Torchic",
"Mudkip", "Skitty", "Riolu"
}
MouseButton1Down = function()
local PokemonNumber = #PokemonList[CurrentPokemon]
if PokemonNumber == #PokemonList then
PokemonNumber = #PokemonList
else
PokemonNumber = #PokemonList[CurrentPokemon] + 1
end
CurrentPokemon = PokemonList[PokemonNumber]
local IconContainer = PokemonData:WaitForChild("IconContainer")
local Icon = IconContainer:WaitForChild("Icon")
Icon.Image = ("rbxassetid://"..Images[CurrentPokemon])
local Name = PokemonData:WaitForChild("Name")
local Typing = PokemonData:WaitForChild("Typing")
local Button = PokemonData:WaitForChild("Button")
Name.Text = CurrentPokemon
Typing.Text = ("Typing: "..CurrentPokemon)
Button.Text = ("Choose "..CurrentPokemon.."?")
TweenService:Create(Camera,
TweenInfo.new(1.0,
Enum.EasingStyle.Quart,
Enum.EasingDirection.Out),
{CFrame = CamerasFolder[CurrentPokemon].CFrame}
)
end
Hello, I believe the error comes in this line, local PokemonNumber = #PokemonList[CurrentPokemon], you are trying to get length but it returns nil, Instead try this, local PokemonNumber = table.find(PokemonList, CurrentPokemon)
Tell me if that fixes it.
I understand this, I don’t plan to release this, this is simply to expand my knowledge by making something I enjoy making, and that I am passionate about.
As they said, PokemonList is what’s called an array which just means it’s an ordered list of values, each one having an index starting at one, and counting upwards for every additional element in the array. Because of this, in order to retrieve a value from it, you have to give the index position (a number) of the item in the array. Dictionaries are lists of keys who’s indexes can be strings, numbers, or objects.
Now from looking at your code it seems like you understood this concept for the most part as you were at times indexing the array with a number value, but you’d frequently put #PokemonList["Mudkip"]. Now what’s going on here is the script tries to search for the index "Mudkip" in the array (which we’ve already established we can only index ordered arrays with numbers, and dictionaries with strings), and then it was trying to call #nil because PokemonList["Mudkip"] returns nil.
I know it’s quite the long explanation, but I hope this helps you better understand arrays and how to use them, as well as the quirks of debugging odd errors like these! Order of operations matters, and even a seasoned programmer may have to do a double take to figure out why exactly the error is written our the way it is.