Search code examples
lualove2d

Creating a table inside of a function returns an error


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.


Solution

  • 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.