Invalid argument #2 to 'random' (interval is empty?)

i’ve made a very simple placeholder function, and suddenly i’ve ran into an issue that i’ve never encountered before: “invalid argument #2 to math.random()”

local possibleStates = {
	["waltzing"] = function()
		print("cat is walking about")
	end,
	
	["hungryForFood"] = function ()
		print("cat wants a regular food object")
	end,
	
	["hungryForProp"] = function ()
		print("cat is hungry for a random household object")
	end,	
}

function selectRandomState()
	local randomIndex = math.random(1, #possibleStates) -- interval EMPTY??? i have never had this issue.
	local selectedState = possibleStates[randomIndex]
	return selectedState
end

while task.wait(6) do
	local randomState = selectRandomState()
	print(randomState)
end
1 Like

The # operator only counts the numerical indices of the table (1, 2, 3…) and your table consists of string keys (“waltzing”, “hungryForFood”, “hungryForProp”). One way you could solve this problem would be to store all the keys in a numerical array, then selecting a random key from the array with math.random, and then directly getting the function by the selected random key from the possibleStates dictionary.

local possibleStates = {
	["waltzing"] = function()
		print("cat is walking about")
	end,
	
	["hungryForFood"] = function ()
		print("cat wants a regular food object")
	end,
	
	["hungryForProp"] = function ()
		print("cat is hungry for a random household object")
	end,	
}

local stateNames = {}
for stateName in pairs(possibleStates) do
  table.insert(stateNames, stateName)
end

function selectRandomState()
	local randomIndex = math.random(1, #stateNames)
	local stateName = stateNames[randomIndex]
	local selectedState = possibleStates[stateName]
	return selectedState
end

local randomState = selectRandomState()
print(randomState)
1 Like
local randomNumber = math.random(minValue, maxValue)

1 Like