1

so I'm new to lua and I cannot figure out how you target elements in arrays in arrays.

And is a table the same as an array? Why does an array and an object have the same syntax? Is there a difference?

0

1 Answer 1

5

Just use the table-indexing operator several times, e.g.:

local data = { { "northwest", "north", "northeast" },
               { "west",      nil,     "east"      },
               { "southwest", "south", "southeast" } }
print(data[2][3])  -- prints east

As for the confusion regarding tables, arrays, objects, etc.: Lua has no ‘arrays’. Lua has no ‘objects’. For structure, Lua has only tables, which you can use as an array, or use as an object—but to Lua, it’s a table. They are what you make of them.

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

4 Comments

I'm getting an error: attempt to index a nil value. table.insert(tails, table.getn(tails), {x = snake.x, y = snake.y}) Targeting the table with: tails[1][1] and tails[1][2]
@Rasmus: (I’m going to fall back to saying ‘array’ and ‘object’ since while there is no difference to Lua, we do often make that distinction when talking about things.) It looks like rather than having a two-dimensional array, you instead have a single-dimensional array of objects with x and y properties. Are you trying to get one of the objects by its x and y values?
I want an array with objects in it. So I can: somex = tails[1][1] Which should refer to tails -> {{x=*10*, y =15},{x=5,y=10}}
@Rasmus: Oh, in that case, the inner index will be a string, e.g. somex = tails[1]["x"], which Lua conveniently allows you to abbreviate to somex = tails[1].x.

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.