How to increment table roblox

How do I increment the hairs table

local hairs = {
	hairFolder["Spiky Hair"],
}

local currentHair = hairs[1]

local function getHairForward()
	currentHair = hairs + 1
	return currentHair
end


local function getHairBackward()
	currentHair = hairs - 1
	return currentHair
end

when if I do teh getHairForward function I expected currentHair = hairs[1] to go to currentHair = hairs[2]

well it doesn’t work because it tells me i tried to add a number and a table.

consider adding a currentHairIndex variable

Try this code:

local hairs = {
	hairFolder["Spiky Hair"],
}

local currentHairIndex = 1
local currentHair = hairs[currentHairIndex]

local function getHairForward()
	currentHairIndex += 1
    currentHair = hairs[currentHairIndex]
	return currentHair
end


local function getHairBackward()
	currentHairIndex -= 1
    currentHair = hairs[currentHairIndex]
	return currentHair
end
3 Likes

thanks,

i have no idea why I didnt think of that :sob:

2 Likes

That’s it. Just a small suggestion, the index may currently reach outside the bounds of the array, so you might want to make sure that the lowest possible is 1 and highest possible the length of the table.

local function getHairForward()
	currentHairIndex = math.min(currentHairIndex +1, #hairs)
	...
end

local function getHairBackward()
	currentHairIndex = math.max(currentHairIndex -1, 1)
	...
end

Alternatively, the forward over table length could revert to 1 and vice versa.

local function getHairForward()
	currentHairIndex = if currentHairIndex +1 > #hairs then 1 else currentHairIndex +1
	...
end

local function getHairBackward()
	currentHairIndex = if currentHairIndex -1 == 0 then #hairs else currentHairIndex -1
	...
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.