在函数中创建表格会出现错误。

当我将以下代码(插入LÖVE的引擎):

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

并通过以下方式调用它:createNewBody(moon,physics.math.moonG)(是的,我已经定义了moonG)。

这是我的物理数学表:

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
}

我得到以下错误:'table index is nil'

我不确定我做错了什么。

点赞
用户2320153
用户2320153

你不能用这种方式创建一个表格。

首先,你需要通过以下方式创建一个空表格:

world.body[id] = {}

然后,你可以使用键值对上传它:

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

也许你可以像在原始代码中一样以同样的方式编写它们;我不确定那是否有效,但很可能有效。

奖励:通过创建一个“模板表格”并使用ipairs搜索,你可以使它变得更简单,但这超出了这个问题的范围。

2016-02-22 15:20:45