As they are, both would likely not work as you expect. In your first version, 'dest' is a table and would thus raise in an error. It should probably be 'cv'. In the second version, 'i' is a number which is probably not your intended comparison. It should probably be 'source[i]'.
Regarding the use of pairs vs #table. It really depends on whether or not the table order matters. There may be some slight performance benefit from the second method, but it probably won't be noticeable at this scale. For convenience, there is also ipairs that works similarly to pairs, but respects table index.
Putting those aside, the function would still not work as you describe because as written it would add the string from 'source' multiple times for each mismatch. This would result in a lot of duplicate entries. The way to do it is to traverse the entire destination table
before adding the new string. This assures that
1) If the string already exists, but is at the end of the table, it isn't added again prior to that check, and
2) It is only added once.
Lua Code:
local function CopyAndDeleteTable(source)
local dest = Chat.db.profile.randChatTbl
for si, sv in ipairs(source) do -- Using ipairs here mostly as an example of usage.
local hasMatch
for ci, cv in ipairs(dest) do
if string.match(cv, sv) then
hasMatch = true
break -- We found a dupe, no need to go farther
end
end
if not hasMatch then
table.insert(dest, sv)
end
end
wipe(source)
end
Finally, are you planning to do anything else with the old table? If not, using wipe() will only remove keys and indexes on the table, the table itself will still exist. To delete it, you would have to reassign the table as nil. In this case you would have to move the delete part out of CopyAndDeleteTable because assigning nil to 'source' would only delete that reference, not the actual table.
All together:
Lua Code:
local function CopyTable(source)
local dest = Chat.db.profile.randChatTbl
for si, sv in ipairs(source) do -- Using ipairs here mostly as an example of usage.
local hasMatch
for ci, cv in ipairs(dest) do
if string.match(cv, sv) then
hasMatch = true
break -- We found a dupe, no need to go farther
end
end
if not hasMatch then
table.insert(dest, sv)
end
end
end
function Chat:OnInitialize()
CopyTable(SmartRes2.db.profile.randChatTbl)
SmartRes2.db.profile.randChatTbl = nil -- delete the now unused table
end
Hope this helps!