Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Table Remove not working as it should?

Asked by
RoyMer 301 Moderation Voter
5 years ago

I have 3 tables within a table and I am trying to remove one of them. I am expected to print only "Please" and "Me" but for some reason none of the tables are being remove?

List = {["Please"] = {}, ["Help"] = {}, ["Me"] = {}}

for i,v in pairs(List) do
    print(i,v)
end

table.remove(List, 2) 

print("----------------------")

for i,v in pairs(List) do
    print(i,v)
end
0
table.remove works for arrays. You are using dictionaries, and the non numerical keys won't count towards the length of the table User#19524 175 — 5y
0
try setting it to nil instead of using table.remove hellmatic 1523 — 5y
0
If you wish to remove a dictionary entry do tab[index] = nil and that works. User#19524 175 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago

Well, the reason for this is because list is a dictionary, not an array.

Arrays and Dictionaries

Arrays are tables whose indexes are integer values

I.E.

local arr = {1,32,4434,3454543}

the above example is an array because values can be retrieved by using a integer above 0 as an index:

print(arr[2])--32

Dictionaries are tables whose indexes are string values

I.E.

local dict = {["me"] = "Hello",["Jeff"] = "ding"}

the above example is a dictionary because values can be retrieved by using a string an index, also, you can use the . syntax.

print(dict["me"])--Hello
print(dict.Jeff)--Ding

The table you had in your code is a dictionary and not an array


What Went Wrong

What went wrong was that you tried to remove the second value of the table list, that was a problem as list doesn't have a second value, as it is a dictionary. What you should've done was set the value corresponding with the Help index to nil :

List = {["Please"] = {}, ["Help"] = {}, ["Me"] = {}}

for i,v in pairs(List) do
print(i,v)
end

List.Help = nil -- you could also do List["Help"] = nil, that also works 

print("ding")

for i,v in pairs(List) do
    print(i,v)
end
0
TL;DR, you treated the dictionary as if it was an array theking48989987 2147 — 5y
1
u stol incap asnwer knob hellmatic 1523 — 5y
0
wym, kkhnob theking48989987 2147 — 5y
Ad

Answer this question