Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do you index the last element in a list??

Asked by 6 years ago
Edited 6 years ago

Here's my attempt based on how its done in Python or Ruby

01local list = {1,2,3,4}
02 
03print(list[-1])
04 
05>> 4
06----------
07 
08local list = {A, C, D, R, G}
09 
10print(list[-1])
11 
12>> G

list[-1] returns nil, is there an end of list reference in LUA might of just missed it but can't seem to find it in the docs, roblox or lua

*I can table.getn(list) and use that but I was just curious if there was something like the example above?

0
In the list, you are placing a letter alone which is considered nil. To make something a string, you would place quotations around it like this; "A". Therefore If I were to print "A" it would print A rather than nil. In your list/Array you should be doing {"A","C","D","R","G"} . If you try printing now, It should print the letter G itself. Stephenthefox 94 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

Well in lua, to get the last member of a table/ last element in a list, you would use the length operator, or #, which is the easiest way of achieving this. This is the case as arrays in lua start at 1 instead of 0, unlike most other languages.

Also note that the getn function was deprecated in 5.1

Length operator

1local tbl = {41,"owo",412,14,25,24,254,23}
2 
3print(#tbl)--8
4 
5print(tbl[#tbl]) --23
6print(tbl[8])--23

Hopefully this helped! And be sure to accept this answer if it did

0
Thank you GoodCallMrOlsen 70 — 6y
0
no problem! theking48989987 2147 — 6y
Ad

Answer this question