-1

When I insert the following code (into LÖVE's engine)

function createNewBody(id,m)
    if world.attributes.isCreated==true then
        world.body[id]={mass=m,x=0,y=0,xAccel=0,yAccel=0,xR=0,yR=0} --error is in this line.
        world.bodies=world.bodies+1
    else
        print("You must first create a new world!\n")
    end
end

And calling it by: createNewBody(moon,physics.math.moonG) (yes, I have already defined moonG).

Here is my physics.math table:

physics={}
physics.math={
    gUnit="m/s^2",
    earthG=9.80665,
    moonG=1.622,
    marsG=3.711,
    mercG=3.7,
    jupitG=24.79,
    pi=3.14159265359,
    ln=2.718281828459
}

I get the following error: 'table index is nil' I'm not sure what I am doing wrong.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
MTadder
  • 33
  • 2
  • @YuHao What do you mean? – MTadder Jan 30 '16 at 01:55
  • you sure `id` and `moon` is not nil? The only thing I see in this code that could error is the `id` in `world.body[id]` – Rochet2 Jan 30 '16 at 01:58
  • You are calling `createNewBody(moon,physics.math.moonG)`, and you said you have defined `moonG`. What about `moon`? – Yu Hao Jan 30 '16 at 01:58
  • @Rochet2 How do I go about initializing `moon`? should I make it a table first? Like, `moon={}` then use the code? – MTadder Jan 30 '16 at 02:02
  • Doing `id={}` before everything seems to have fixed my problem. If you submit it as an answer I'll confirm it. @Rochet2 :D – MTadder Jan 30 '16 at 02:06

1 Answers1

0

You can't create a table this way.

First, you have to create an empty table by the following:

world.body[id] = {}

And then, you can upload it with key-value pairs:

world.body[id].mass = m
world.body[id].x = 0
world.body[id].y = 0
...

Maybe you can write them in the same fashion you did in the original code; I'm not sure if that works, but likely does.

Bonus: by creating a "template table" and usingipairs search, you can make it even more simple, but that's out of the scope of this question.

Zoltán Schmidt
  • 1,286
  • 2
  • 28
  • 48