Lua: are nil errors positional?

given this code:

109:    local distance = distanceToPoint(item.x + item.w/2, item.y+item.h/2, planePos[1], planePos[2])
110:    local sound = self:soundForSpecial(item)
111:    if sound then
112:        sound.minDistance = min(sound.minDistance, distance)
113:    end

And the error message: attempt to compare number with nil for line 112 in math.min. Can we conclude that distance is nil, or could sound.minDistance be nil too?

In other words, is the order of number and nil meaningful in this message?

I'd assumed that wasn't the case, that you'd get the same error either way, but I'm wrong:

> print(1<nil)
[string "console"]:1: attempt to compare number with nil
> print(nil<1)
[string "console"]:1: attempt to compare nil with number

You'll need to check the source for the min() function to see which value is nil on line 112, it's possible they're reversed there from how they're passed in. And I think it's much more likely that the issue there is sound.minDistance hasn't been initialized than distanceToPoint() is returning nil.

ah yes, could have tested this myself of course. Thanks. Issue was fixed btw, indeed minDistance was nil

Also nice to use the simulator console for this kind of REPL like tests

fyi entering "1+3" in the command section won't work, but "print(1+4)" will actually print 4

One of these days I'll get around to checking whether it'll be possible to have the console accept expressions instead of just statements, and print the result. Until then a handy shortcut is p <expr> which is equivalent to print(<expr>).

1 Like