Home > Software engineering >  Why does this list always grab the first item?
Why does this list always grab the first item?

Time:02-27

This function is supposed to go through all of the list items and check whether the argument coordinates are close to the position in the list items (the second and third numbers in the nested lists), but from the readout I can tell that it only ever checks the first one.

function CapitalProximity(x,y)
  local positions = {{"lusitani",31,328},{"ebdani",78,592},{"carpetani",101,329}}
  for i = 1, #positions do
    local dist = distance_2D(x,y,positions[i][2],positions[i][3])
    print("position is "..dist.." from "..positions[i][1])
    if dist < 20 then
      return true
    else
      return false
    end
  end
end

CodePudding user response:

Since both branches of the if return from inside the loop, the loop can never reach a second iteration. To get results based on all elements from the positions array, you need to make a table to store them:

function CapitalProximity(x,y)
  local positions = {{"lusitani",31,328},{"ebdani",78,592},{"carpetani",101,329}}
  local result = {} -- This will hold all results.
  for i = 1, #positions do
    local dist = distance_2D(x,y,positions[i][2],positions[i][3])
    print("position is "..dist.." from "..positions[i][1])
    result[i] = dist < 20 -- Store the current result.
  end
  return result
end
  • Related