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

Why isn't my iteration for the table not printing anything?

Asked by
noposts 75
6 years ago

I've made an example of what I'm trying to convey and I don't know why it's not working as expected.

local tab = {["key"] = nil}
for k, v in pairs(tab) do
    print(v)
end

What I expect it to do is print nil since the value of the key is nil, but what it's doing is print completely nothing at all. However, if I do set the value to something else other than nil, it functions as expected and prints the value.

local tab = {["key"] = "hi"}
for k, v in pairs(tab) do
    print(v)
end

-- prints "hi"

Directly printing the value from the table like tab.key seems to print nil so why doesn't iterating through the table not work?

2 answers

Log in to vote
0
Answered by
EB8699 30
6 years ago

Hello!

I tried out a few variations myself just to be sure.

Here's the code:

local Table1 = {["Key"] = nil}
local Table2 = {["Key"] = "nil"}
local Table3 = {["Key"] = "Hi1"}
local Table4 = {["Key1"] = "Hi2",
    ["Key2"] = nil,
    ["Key3"] = 256
    }

local function PrintTable(Table)
    for i, v in pairs(Table) do
        print(v)
    end
end

Table4.Key3 = Table4.Key2

PrintTable(Table1)
PrintTable(Table2)
PrintTable(Table3)
PrintTable(Table4)

print(Table1.Key, Table2.Key, Table3.Key, Table4.Key1, Table4.Key2, Table4.Key3)

The result printed was: nil Hi1 Hi2 nil nil Hi1 Hi2 nil nil

So to answer your question, when you iterate over a table (Such as with the for i, v in pairs) it simply skips the nil value. When you Deliberately call it however then it'll print the result.

Basically, it's a resource saving measure. It still works as expected though.

Ad
Log in to vote
1
Answered by 6 years ago

Hi noposts,

I think the answer to your question is simple. When you iterate through a table, it ignores all values that are nil.

You can see this when you try it with a normal table and not a dictionary

local tab = {nil, nil, "hi"}

for _, val in next, tab do
    print(val); -- Only runs once printing "hi".
end

So, a table ignores all values that are nil, since an empty table has nil values inside of it to begin with. Also, you asking it to print the value by doing:

tab = {["key"] = nil};

print(tab.key);

This doesn't mean anything because if you were to do tab.[any word] it will just print nil. So, tab.whatever or tab.nothing or tab.anyword will end up printing nil, since those don't exist in the first place. So, ["key"] isn't even recognized as a real value. It just ignores that whole value since it's nil.

Well, I hope I explained the issue well and helped. Have a wonderful day/night.

Thanks,

Best regards,

~~ KingLoneCat

Answer this question