Math.random isn't working with table

Hello dear developers. I have a problem with my code, certainly choosing random array from table. Here is the main information below:

  1. What do you want to achieve?
    Make the script select random array from the table.
  2. What is the issue?
    math.random seems to be generating just 1.
  3. What solutions have you tried so far?
    I tried print() to see the result of math.random, change the build of math.random but nothing really helps. The output ain’t showing anything.
    (The script is legacy.)

Code:

local runAnomalies = {
	MoveVentilationSystem(),
	SwapTables()
}

local function SpawnAnomaly()
	if runAnomalies then
		local anomalie = runAnomalies[math.random(1,#runAnomalies)]
		print(math.random(1,#runAnomalies))
		anomalie()
	end
end

SpawnAnomaly()

Try making the table like this.

local runAnomalies = {
	[1] = MoveVentilationSystem(),
	[2] = SwapTables(),
}

Ran the game couple times but the result is the same.

Try adding a couple more options to make sure that something else is being generated, or indeed it only gives one

1 Like

I think you have to delete “()” because when you use “()” on a function you’re calling it. Let me know if it works

1 Like

All of the tips didn’t worked D:
I don’t have a clue how to fix that really now. Is there any other way to select random array from the table?

local runAnomalies = {
	[1] = MoveVentilationSystem,
	[2] = SwapTables,
	[3] = MoveShelfBooks,
	[4] = ColorBathroomChair
}

local function SpawnAnomaly()
	if runAnomalies then
		local anomalie = runAnomalies[math.random(1,#runAnomalies)]
		print(math.random(1,#runAnomalies))
		anomalie()
	end
end

SpawnAnomaly()
local runAnomalies = {
	[1] = MoveVentilationSystem,
	[2] = SwapTables,
	[3] = MoveShelfBooks,
	[4] = ColorBathroomChair
}

local function SpawnAnomaly()
	print("Starting")
	if runAnomalies~=nil then
		local r = math.random(1,#runAnomalies)
		local anomalie = runAnomalies[r]
		print(r)
		anomalie()
	end
end

SpawnAnomaly()
1 Like

Maybe you have to directly write the function inside the table, like this:

local runAnomalies = {
	MoveVentilationSystem = function()
       -- Stuff here
    end),
}

The problem is solved, thanks to everyone.

2 Likes

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