OCA
OCA

Reputation: 111

Filling Lua table not going as expected

I am coding a little something in Lua and I've encountered a very frustrating bug/mistake in my code.

network = {}
network.neurons = {}

for i=1,4 do
    network.neurons[20000] = {}
    network.neurons[20000][i] = NewNeuron()
    print(network.neurons[20000][i])
end

The NewNeuron() function creates a new object with some variables. The print() inside this for loop returns the table with the correct variables as expected. The problem comes when I try to use this print again in this loop:

for i=1,4 do
    print(network.neurons[20000][i])
end

The print then writes 4 console lines as follows:

(no return)
(no return)
(no return)
*neuron info that should be printed*

It looks as if only the last of the 4 objects exists after I exit the creation loop. Why is this? What am I doing wrong?

Upvotes: 2

Views: 50

Answers (1)

hjpotter92
hjpotter92

Reputation: 80629

You are assigning an entirely new table inside the loop when creating a NewNeuron. The declaration should be outside:

network = {}
network.neurons = {}
network.neurons[20000] = {}

for i=1,4 do
    network.neurons[20000][i] = NewNeuron()
    print(network.neurons[20000][i])
end

Upvotes: 0

Related Questions