Help with adding a new item in a table

  1. What do you want to achieve?
    I want to add a new item in a table with a new index.

  2. What is the issue?
    It replaces the first index and does not assigned the value to a new index in the table.

  3. What solutions have you tried so far?
    I tried table.insert(table1, 1 + #table1, table2[value]) but it did not solve my problem.

I’m trying to make a random dialogue system that also prevents repetition of dialogues. However, the problem is that when adding a dialogue to the “used” table; it does not add a new index for the dialogue but rather replace the first index.

image

function talk ()
	
	local dialogues = {
		"Hi, "..playersInRadius[#playersInRadius].DisplayName,
		"Hello, "..playersInRadius[#playersInRadius].DisplayName,
		"Don't get too close", "I can't move, help me", "My programmer sucks",
		"Do you have robux?", "I don't really have a personality.",
		"Nice avatar, "..playersInRadius[#playersInRadius].DisplayName
	}
	
	local used = {}
	local picked
	
	repeat task.wait()
		picked = math.random(1, #dialogues)
	until not table.find(used, dialogues[picked])
	
	table.insert(used, dialogues[picked])
	chat:Chat(bric.Head, dialogues[picked])
	
	if #used == #dialogues then 
		table.clear(used)
	end
	print(used)
	
end

This should work:

function getRandomDialog(dialogues, used)
	local picked = dialogues[math.random(1, #dialogues)]

	if table.find(used, picked) then
		getRandomDialog(dialogues, used)
	else
		return picked
	end
end

function talk()
	local dialogues = {
		"Hi, "..playersInRadius[#playersInRadius].DisplayName,
		"Hello, "..playersInRadius[#playersInRadius].DisplayName,
		"Don't get too close", "I can't move, help me", "My programmer sucks",
		"Do you have robux?", "I don't really have a personality.",
		"Nice avatar, "..playersInRadius[#playersInRadius].DisplayName
	}

	local used = {}

	for i = 1, #dialogues do
		used[i] = getRandomDialog(dialogues, used)
	end

	chat:Chat(bric.Head, used[1])
	print(used)
end

The issue here is that you’re declaring the table used as a local variable in the talk() function, meaning that every time you call talk(), the used table will be empty, which is why there is always only one index in used every call.

To fix this, simply move the declaration of used (local used = {}) outside and above the talk() function.

local used = {}
function talk()
 -- talk code
end

Hope this helps!

1 Like

Thank you so much, your help is greatly appreciated and what you taught me will be a major stepping stone in the development of my skills.