Reputation: 1049
I have searched around quite a bit and couldn't quite find a solution for this. Any help you can offer would be appreciated.
-- 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
I am getting an error about attempting to index a nil
value, in reference to the EnemyList
table/array. What I am trying to accomplish is I am trying to compile a new array of only enemies that are allowed. I guess I am unsure how to insert a new row into the EnemyList
table. I tried using table.insert
, but the value parameter is required, and I am not sure how to do that with the fact that I am storing multiple values into the EnemyList
array.
Any help or insight on the proper way to insert a new row into an empty table/array would be much appreciated. Thanks!
EDIT: I got a working solution, but I figured I should update the code here if anyone in the future finds it.
-- 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
Upvotes: 0
Views: 1974
Reputation:
You can store tables within tables in Lua. Tables are indexed in one of two ways: First, by index number. This is what table.insert
uses; it will add an entry at the next index number.
The second way is by key; e.g.
> t = {}
> t.test = {}
> =t.test
table: 0077D320
You can insert tables into tables; this is how you create a 2D table. Because of the way you've defined your tables, type(EnemyList[counter]) = table
.
You can insert new entries into tables by running table.insert(table, value)
. This will assign value
to the next available numeric entry. type(value)
can also be a table
; this is how you create "multidimensional arrays" in Lua.
As an aside, instead of using for i=1,#Enemies
I would suggest using for i,v in ipairs(Enemies)
. The second one will iterate over all numerical entries in the Enemies
table.
Upvotes: 2