Reputation: 101
If I had code like this in Lua, how would I call 'this'?
array = { this = { pic="hi.png", health=4 } , pos=20 }
Edit:
Say for example I have a table of enemies like:
enemy = {}
enemy[1] = {pic="Ships/enem-01.png", hp=2}
enemy[2] = {pic="Ships/enem-02.png", hp=4}
enemy[3] = {pic="Ships/enem-03.png", hp=3}
enemy[4] = {pic="Ships/enem-04.png", hp=5}
enemy[5] = {pic="Ships/enem-05.png", hp=7}
enemy[6] = {pic="Ships/enem-06.png", hp=9}
enemy[7] = {pic="Ships/enem-07.png", hp=15}
I then want to be able to create a table of there positions.
level1 = {}
level1[1] = { ent = enemy[2], xpos= 20, ypos=20}
how would I call pic, using level1, or wouldn't I?
would I change level1 to be like
level1[1] = {ent = 2, xpos=20, ypos=20}
then use
screen:draw(level[1].xpos, level[1].ypos, enemy[level[1].ent].pic)
Upvotes: 0
Views: 7702
Reputation: 52698
Edit:
level1[1] = { ent = enemy[2], xpos= 20, ypos=20}
how would I call pic, using level1, or wouldn't I?
You just need to do this:
level1[1].ent.pic -- "Ships/enem-02.png"
Upvotes: 2
Reputation: 3687
Remember that there is no such thing as 'array' in Lua. The only existing complex data structure are 'tables', wich are build using { }
Tables are associative structures, where every data stored can be indexed by keys of any type: numbers, strings or even other tables. The only restriction is the nil
type.
Let's see an example, we want to build one table with two keys, one number and one string:
example = { [1] = "numberkey", ["key"] = "stringkey" }
Note that in the example above, the table construction is different from your example.
You index a table using [ ]
, like the following example:
example[1]
example["key"]
But this syntax to create and index string keys is quite verbose. So to make our life easier, Lua offers us what it calls a "syntax sugar":
example2 = { [1] = "numberkey", key = "stringkey" }
The contents of this table is the same as before. But the key "key" was declared differently. We can do that with string keys: put them directly in table constructors. And to index them, we can use another "syntax sugar":
example2.key
Back to your example, you can access this
, wich is a string key, using:
array.this
Sorry about my english, it is not my first (and second) language.
Upvotes: 3