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 :)



Maybe something like this?

last_item = values[#values] or 0

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


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.


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.



[Please log in to post a comment]