0

我已经搜索了很多,但找不到解决方案。您可以提供的任何帮助将不胜感激。

-- The array compiled of enemies only allowed in the current
-- level phase
local EnemyList = {}
-- Counter to determine the next spot in the EnemyList
-- array to insert into
local counter   = 1

for i=1,#Enemies do
    if Enemies[i].phase == 0 or Enemies[i].phase == which_phase then
        EnemyList[counter].src      = Enemies[i].src
        EnemyList[counter].exp      = Enemies[i].exp
        counter                     = counter + 1
    end
end

我收到关于尝试索引nil值的错误,参考EnemyList表/数组。我想要完成的是我试图编译一个新的数组,其中只有允许的敌人。我想我不确定如何在表中插入新行EnemyList。我尝试使用table.insert,但 value 参数是必需的,而且我不知道如何做到这一点,因为我将多个值存储到EnemyList数组中。

任何有关将新行插入空表/数组的正确方法的帮助或见解将不胜感激。谢谢!

编辑: 我有一个可行的解决方案,但我想如果将来有人找到它,我应该在这里更新代码。

-- The array compiled of enemies only allowed in the current
-- level phase
local EnemyList = {}

for i=1,#Enemies do
    if Enemies[i].phase == 0 or Enemies[i].phase == which_phase then
        table.insert( EnemyList, { src = Enemies[i].src, exp = Enemies[i].exp } )
    end
end
4

1 回答 1

2

您可以在 Lua 中的表中存储表。表以以下两种方式之一进行索引:首先,按索引号。这就是table.insert用途;它将在下一个索引号处添加一个条目。

第二种方式是按键;例如

> t = {}
> t.test = {}
> =t.test
table: 0077D320

您可以将表格插入表格;这就是您创建 2D 表的方式。由于您定义表的方式,type(EnemyList[counter]) = table.

您可以通过运行将新条目插入到表中table.insert(table, value)。这将分配value给下一个可用的数字条目。type(value)也可以是table;这就是在 Lua 中创建“多维数组”的方式。

顺便说一句,for i=1,#Enemies我建议不要使用for i,v in ipairs(Enemies). 第二个将遍历表中的所有数字条目Enemies

于 2013-04-07T18:35:12.283 回答