How to iterate through a tuple?

As the title says.

I’m trying to make a variable collection thing using attributes, it works by putting attributes that are available into a table and then it’s unpacked for other parts of my script to use:

local VariableTable = {}
local CurrentVariableNumber = 1
local VariableToAdd = CacheFolder:GetAttribute("Variable"..CurrentVariableNumber)
if VariableToAdd then
	table.insert(VariableTable, CurrentVariableNumber, VariableToAdd)
	CurrentVariableNumber = CurrentVariableNumber+1
end
return VariableTable

the problem with attributes is that they don’t store nil values in themselves, so if I needed a nil value to be returned it won’t be returned because you can’t put nil values in tables either, which is a problem because I use table.unpack after getting the table result.

My idea right now is to make attributes that need to have nil values have a string nil and have it become nil if detected in a dictionary, my issue right now is trying to loop through tuples, how do you iterate through a tuple from a table.unpack?

Edit: Current Scenario I’m trying to solve

I have seven variables made that each fire SetAttribute()
Variables 1-4 are random numbers.
Variables 5-6 are nil. They are needed readable nil values.
Variable 7 is a random number. This is a needed value.
Variables 5-7 aren’t being returned from table.unpack from my variable collection, they are being indexed correctly with Table[5] = nil, Table[6] = nil, Table[7] = 25 but only Table[1-4] gets readable printed back and nothing appears after 5-7.

I’m confused, couldn’t you just iterate through before unpacking and use the pairs iterator which works with nil values?

local t = {1;2;3;4;5;nil;nil,8}
for i,v in pairs(t) do
    print(v) -- prints 1-8 except 6 and 7
end

print(unpack(t)) -- prints the tuple instead of the table except for 8

There’s already a function for this.

2 Likes

When I put nil inside of a table it doesn’t get seen by the script and the rest of the table is cut off. However if I replace nil with a string it can be used inside of tables.

By putting it inside I mean indexing a table as a nil value like Table[1] = nil you can’t put a nil inside a table so if you do Table[1] = "Chicken" Table[2] = nil Table[7] = "Nuggets" print(unpack(Table)) it doesn’t print 7 or the nils in between 2-6.

not entirely sure, but I think this solves your issue. I haven’t used the Select() function

Pairs doesn’t care about nil values though. You can use that to iterate over all of the values and ignore the nil ones.

If your table will have nil in it, then you should use pairs instead of ipairs. Although it won’t be in order, I don’t know why you have nil in a table, so it shouldn’t affect it much.

You may want to read this great article:

https://benaiah.me/posts/everything-you-didnt-want-to-know-about-lua-multivals/

To summarize: don’t bother with tuples in most cases, they’re sort of half-datatypes in lua that have some weird behavior.