Skip to content

[fork-ffi] numbers: sign — The Lua and/or transliteration of the JS ternary is broken for input 0 #94

@Unisay

Description

@Unisay

Package: purescript-lua-numbers
File: src/Data/Number.lua
Function: sign
Class: semantics Severity: high

The Lua and/or transliteration of the JS ternary is broken for input 0. JS x === 0 || x !== x ? x : (x < 0 ? -1 : 1) returns the VALUE x (i.e. 0) when x===0. The Lua expression x == 0 or x ~= x and x or (...) evaluates x == 0 to the boolean true and the leading or short-circuits, so sign(0) returns boolean true instead of the number 0. Confirmed under Lua 5.1: type(sign(0)) == "boolean", value true. This injects a boolean into a value typed Number on the PureScript side.

Current (Lua):

sign = (function(x) return x == 0 or x ~= x and x or (x < 0 and -1 or 1) end)

Expected: sign 0 = 0 (a Number), preserving signed zero; sign nan = nan; sign of positive = 1; sign of negative = -1.

Proposed fix:

Do not encode the value via the boolean condition. Use explicit branches: `function(x) if x ~= x then return x elseif x == 0 then return x elseif x < 0 then return -1 else return 1 end end`. This returns the actual number 0 (and the original signed zero) rather than a boolean.

Found by the FFI audit; reproduced under Lua 5.1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions