0

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) 
1
  • I'd call that 'this' a "key" in the table array points to. Commented Jan 11, 2012 at 14:03

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Aside of nil, you can't use NaN as table key either.
2

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.