codeR developR
codeR developR

Reputation: 497

Love2d adding value to table inside for loop.. Using a variable

This is something that's really been nagging at me for some time:

for i = 1, 4 do
   x = love.physics.newFixture(diffTable[i].body, diffTable[i].shape):setCategory(10)
   x = x:setUserData('Border') -- error here
   table.insert(data, x)
end

Let's say I want to insert a variable into the table (basically creating the variable, and then modifying it) and then inserting it:

When I do the x = x:setUserData(...) an error comes up.. saying attempt to index global variable x (nil)

So my question is, how would I create a variable inside a for loop, specifically I need to do it this way because I'm using love.physics, and creating a fixture with a category. I also need to setUserData at that time but it's not possible.

And I'm sure there has to be a way of doing this... Thanks in advance!!

Upvotes: 0

Views: 287

Answers (1)

Nifim
Nifim

Reputation: 5021

The function Fixture:setCategory does not return a value.

so when you do this

x = love.physics.newFixture(diffTable[i].body, diffTable[i].shape):setCategory(10)

you are setting x = nil. Fixture:setUserData also does not return a value.

If you change it to this you will no longer get that error.

for i = 1, 4 do
   x = love.physics.newFixture(diffTable[i].body, diffTable[i].shape)
   x:setCategory(10)
   x:setUserData('Border') -- error here

   table.insert(data, x)
end

Upvotes: 3

Related Questions