Search code examples
lualua-table

"for" about table in Lua


tablelogin = {0 = "test1",1 = "test2",2 = "test3",3 = "test4"}

for pp=0,#table do
  if takeinternalogin == (tablelogin[pp]) then
    LogPrint("Login found")
  else
    LogPrint("failed login not found")
  end
end

takeinternalogin is an internal function of my program that takes the person's login.

In this script I'm taking the person's login and comparing whether or not the login is in the table.

It works, but after the else if the person's login is not in the table, it returns the message "failed login not found" 4 times, that is, it returns the number of times it checks the table.

I don't understand. How can I make the message execute only 1 time?


Solution

  • You are currently printing the error message every time it iterates over the table and the current value does not match.

    local arr = {[0] = "test1", [1] = "test2", [2] = "test3", [3] = "test4"}
    
    function findLogin(input)
      for i,v in pairs(tablelogin) do
        if v == input then
          LogPrint("Login found")
    
          return i
        end
      end
    
      LogPrint("failed login not found")
    end
    
    login = findLogin(takeinternalogin)
    

    Using return within a loop makes it break out of the loop and in this case never reach the line where it prints the error.