Skip to content

mat.newrdn() "positive" logic works, but only by accident #6

@dcuny

Description

@dcuny

In Matrix.lua, the function mat.newrdn() intends to set the parameter positive to false if it's not passed (i.e it's a nil value).

  --New random matrix
  function mat.newrdn(rows,cols,positive)
  positive = false or positive
  local grid ={}
  grid.rows = rows
  grid.cols = cols
  grid.matrix = {}
  local j = 1
  for i=1,rows do
    grid.matrix[i] = {}
    for k=1,cols do
      if positive then
        grid.matrix[i][k] = math.random()
      else
        grid.matrix[i][k] = math.random(-1,0) + math.random()
      end
      j = j+1
    end
  end
    return grid
end

As written, the line:

  positive = false or positive

will always behave as:

  positive = positive

because false will always evaluate to false, and cause or to return the right hand value, positive.

The code should have been written as:

  positive = positive or false

That is, if positive wasn't passed as a parameter and so is set to nil, the line should set it to false.

The code accidentally works because if* treats nil the same as false, so even though the line doesn't change the value of positive, it still ends up taking the correct branch of the user hasn't specified a value for positive.

Still, the line should be corrected to match the intent.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions