Page 1 of 1

For cycle won't work because "attempt to index local 'v' (a number value)"

Posted: Wed Dec 21, 2016 10:50 pm
by josephcda
Hello, so, when running spaceinvaders.love (File attached). And pressing space, I get an error message: main.lua:64: attempt to index local value 'v' (A number value).

This is the for cicle:

for k, v in pairs(bullet) do
love.graphics.rectangle("fill", v[bulx], v[buly], 10, 10)

You can see the entire thing in main.lua (also attached), but here is the associative array "bullet," just in case:
bullet = {
bulx = (player.x + 10),
buly = player.y,
}

Thank you very much, for anyone who is able to help.

Re: For cycle won't work because "attempt to index local 'v' (a number value)"

Posted: Thu Dec 22, 2016 6:36 am
by s-ol
You are using pairs() to iterate over each pair of keys in 'bullet', so you do two runs of the inside of the loop with v set to 'player.x + 10' and player.y respectively. v is therefore always just a number and you are trying to index it using [], hence the "attempt to index local value 'v' (A number value).".

So first off, you want to completely remove the loop because you are only working with one bullet. You don't need a loop to process one thing
Secondly, to access the values for the keys "bulx" and "buly" you need to either write bullet.bulx and bullet.buly or bullet["bulx"] and bullet["buly"]. bullet[bulx] finds the value whose key is equal to the value of the variable 'bulx' which isn't even set.

It seems that you don't quite understand what you are doing with pairs and tables in general, and I would recommend you spend some time reading the PiL and really getting a strong understanding of them. Tables really are one of the, if not the, basic building block of Lua.