Loop only recognizing the 1st iteration

So basically I’m trying to loop through 4 and make different keys in a table called Inventory but the problem is that it only works for the first iteration, everything after that returns nil

Code :

local Inventory = {}
	
for i = 1, 4 do
	Inventory[tostring(i)] = false
    print(Inventory[1]) -- prints false
	print(Inventory[2]) -- prints nil
end

Visualization

local Inventory = {
	
	["1"] = false;
	["2"] = false;
	["3"] = false;
	["4"] = false;
		
}
1 Like
for i = 1,4 do
         print(i)
         print("Past this road block")
	Inventory[tostring(i)] = false
         print(Inventory[1]) -- prints false
	print(Inventory[2]) -- prints nil
        wait()
end

Try this should work

Its still printing nil after I added the wait for 2,3,4

Have you tried printing with:

print(Inventory["1"])

instead of

print(Inventory[1])

NOTE: If you don’t use tostring(i) when entering the data you can access it like Inventory[1]

Yeah I just tried that and it prints nil again

for 2,3,4

local test = {}

for i = 1, 4 do
  test[tostring(i)] = false
end

print(test["1"])
print(test["2"])
print(test["3"])
print(test["4"])

This works for me. 1-4 print false. Not sure what the issue you are having is. Accessing indexes is different from accessing keys.

Yeah I know but I dont want the key to be an integer I want it to be a string and either way itll still return nil for 2,3,4 anyways

This works find for me.

local Inventory = {}

for i = 1, 4, 1 do
    Inventory[tostring(i)] = false
end

print(Inventory["1"])
print(Inventory["2"])
print(Inventory["3"])
print(Inventory["4"])

Yeah It works for me now too…

Inventory["1"] is different from Inventory[1].

That isnt the problem it was still giving me nil before

edit : it does error but for some reason I think i just put a typo

I don’t think you can access a dictionary with index e.g. Inventory[1] you have to access by key as @hamsterloverboy3 said, they’re different. The key in this case is a string of “1”

Yeah it was a typo on my end, I was actually using a string key to access it

That wasnt the problem i was accessing it while it was looping through adding the keys to the Inventory table

Heres proof of just that hold on

@hamsterloverboy3
@Angiris_treecreeper

Yeah, that is expected behaviour. It should’ve still only been nil on the first iteration. On the second they should both be false e.g.

local test = {  }

for i = 1, 2 do

	test[i] = false

	-- i == 1
	print(test[1]) --Prints false
	print(test[2]) --Prints nil
	
	-- i == 2
	print(test[1]) --Prints false
	print(test[2]) --Prints false
end

The only reason its nil on first print is because you’re printing Inventory[2] before setting it. That’s why you get 3 false prints afterwards since Inventory[2] is set on iterations 2,3 and 4.

It should print one nil because Inventory[“2”] hasn’t been set to false yet.