Carpet

Carpet

2M Downloads

Divide by zero when getting any element of an empty set

James103 opened this issue ยท 2 comments

commented

When you execute the following on Carpet 1.4.21 for Minecraft 1.16.4

/script run []:0
/script run []:1
/script run entity_selector(...):0 // entity_selector returns empty list
...

you get error messages like the following:

Your math is wrong, / by zero in system chat at pos 3
[] HERE>> :0
Error while evaluating expression

I would have expected them all to return null, throw an error 'index out of bounds', or something similar.

commented

Workaround: Make sure the list is not empty before querying an element of said list.

// First check to make sure the list is not empty.
if(list == [],
    // Empty list, do something else...
);
// Only then should you query elements of the list.
x = list:0;
commented

well, if you have a list and request an item from that list outside of it, you typically get a hard on most languages. Only thing you could consider be confused here about is the error that comes up (which actually comes from java is /0, which should be like an index error or something like that, so I think your report is valid, just on a different level.

Having said that there is a way to do that, which is to use 'first(list, cond)' where first([], true) returns null and first([1], true)returns1. One thing that might be good to have is allow for the predicate be optional and default to true, meaning you could just use first(list)` to get the first element or null. Will change that as well.