Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

First table.insert value always goes nil! Any idea?

Hello everyone! I am trying to make a table (put into a modulescript in ReplicatedFirst) to hold a limited amount of items and, when I put a limit to the amount of items through a #table >= 3, it counts as if there were 4! Like as if the first click I do doesn't exist. Any help?

LocalScript to create the item and send it through RemoteEvent

local creating = script.Parent.Parent.Creating

script.Parent.MouseButton1Down:Connect(function()
	local NEWvirus = math.random(1,3)
	local virus = ""
		
	if NEWvirus == 1 then
		virus = "TrojanVirusLVL1"
	end
	if NEWvirus == 2 then
		virus = "TrojanVirusLVL2"
	end
	if NEWvirus == 3 then
	    virus = "TrojanVirusLVL3"
	end
		
	game.ReplicatedStorage.Virus.AddVirus:FireServer(virus)
end)

ServerScript in ServerScriptService to receive the item and put it into the table

game.ReplicatedStorage.Virus.AddVirus.OnServerEvent:Connect(function(plr, virus)
	local virusTable = require(game.ReplicatedFirst.CreatedViruses)
	
	table.insert(virusTable, virus)
end)

ServerScript in the same place as the LocalScript (StarterGUI) to check the amount and limit it

local creating = script.Parent.Parent.Creating

game.ReplicatedStorage.Virus.AddVirus.OnServerEvent:Connect(function()
	local crVirus = require(game.ReplicatedFirst.CreatedViruses)
	
	if #crVirus ~= 3 then
		print(crVirus[1], crVirus[2], crVirus[3])
	else
		print(#crVirus)
		script.Parent.Create.Disabled = true
		script.Parent.Parent.Creating.Visible = true		
		script.Parent.Parent.Creating.Text = "You reached the maximum amount of virus! Use or discard one then try again!"
	end
end)

As I told you, the first time I click the button and the RemoteEvent fires the line

	if #crVirus ~= 3 then
		print(crVirus[1], crVirus[2], crVirus[3])
	else

prints me out "nil nil nil" then it proceeds on printing the rest as if nothing's happened, like the first click never happened. Please help!

5 comments

0

Update: if I put a print(crVirus[1] in the script I use to modify the table, it prints it! No idea why the rest is not working... :')

0

make sure you already have the table

0

I do have the table already, I create it through a modulescript.

0

whats the module script?

0

It's just a simple table, the module script is in ServerScriptService. It was something like local crVirus = {}

1 answer

you need to Return the Table like this

local Module = {}

function Module.GetTable()
       return Module --now you can use it
end
function Module.AddStuffToTable(Stuff)
       table.insert(Module,Stuff)
end
return Module

usage example

local Module = require(game.replicatedstorage.Module)
Module.AddStuffToTable("EXE")
wait(5)
print(Module.GetTable()[1]) --It prints EXE

This discussion is preserved as it was. New answers, comments, and votes are closed.