luau icon indicating copy to clipboard operation
luau copied to clipboard

Metamethods on numbers yield bizzare results

Open cheesycod opened this issue 10 months ago • 1 comments

Image

Code:

function a()
    local a = { 1, 2, 3, 4 }
    local n = 3

    local start, stop = 1, #a

    while(start <= stop) do
        local mid = (start + (stop - start) // 2)
        local value = a[mid]
        if value == n then 
            return mid
        elseif value > n then
            stop = mid - 1
        else
            start = mid + 1
        end
    end

    return -1
end

The issue is that mid's type goes from number to local mid: t1 where t1 = add<add<t1, number> | number, idiv<sub<number | sub<t1, number>, add<t1, number> | number>, number>> in type checking. Initially found by Minii Man on ROSS

Explicitly casting mid to number solves the issue

cheesycod avatar Mar 09 '25 14:03 cheesycod

I can reproduce this bug. It seems that any math operator used in the mid variable causes the issue if including start and/or stop such as: (left + right), (left + 1), (right + 1). This bug only occurs for while loops, repeat loops & for loops, using an if statement prevents the type errors.

A small difference in behaviour that I've noticed is that if no return type for the function is specified then the whole function type errors:

Image

But if a return type is specified then only the problematic variables type error:

Image

This also occurs outside of a function:

Image

Here's an example of it happening for repeat loops too:

Image

MiniiMann avatar Mar 09 '25 14:03 MiniiMann