Log In  

Hello.

I have a runtime error in my game which states that a for loop's initial values must be numbers. I looked into the issue and it seems that an empty table's last item is a nil. Try typing this into the PICO-8 command prompt :

values={}
?values[#values]

and the output is

[nil]

Does anyone know of a workaround or a better way of checking a table's last item?

Thanks in advance :)

P#52875 2018-05-20 08:52 ( Edited 2018-05-21 07:24)

Maybe something like this?

last_item = values[#values] or 0
P#52877 2018-05-20 09:30 ( Edited 2018-05-20 13:30)

Ooh I haven’t thought of that. Simple and nice! Thank you so much! <3

P#52878 2018-05-20 10:05 ( Edited 2018-05-20 14:05)

Your specific problem is solved, but just to comment on the general problem: All of the elements in an empty table are nil, because there are no values. It has nothing to do with you checking the last value; any index you gave it would return nil.

P#52883 2018-05-20 12:56 ( Edited 2018-05-20 16:56)

Yeah. In an array-style table (e.g. "{12,34,56}"), indices are auto-assigned from 1 onwards. An empty array table returns a # length of 0, which would be an invalid index even in a table that had something in it. You can't use the index returned by the # operator unless you know there's actually something in the table to use it on or you can handle a nil value gracefully.

P#52893 2018-05-21 03:24 ( Edited 2018-05-21 07:24)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-04-19 20:07:46 | 0.010s | Q:20