What do you want to achieve?
I want to add a new item in a table with a new index.
What is the issue?
It replaces the first index and does not assigned the value to a new index in the table.
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.
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
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.