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?
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.
Hi noposts,
local tab = {nil, nil, "hi"} for _, val in next, tab do print(val); -- Only runs once printing "hi". end
tab = {["key"] = nil}; print(tab.key);
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.Thanks,
Best regards,
~~ KingLoneCat