Jump to content




Find values in table, error that the if was expected to end


  • You cannot reply to this topic
3 replies to this topic

#1 augustas656

  • Members
  • 158 posts

Posted 27 April 2014 - 06:58 PM

abc = {
{"test", "lol"},
{"abcd", "123"},
{"haba", "abc"}
}
username = "abcd"
function ha(user)
  for k, v in pairs(abc) do
	if v[1] == user then
	return v[1], v[2]
	break
	end
  end
end
u, p = ha(username)
print(u .. " " .. p)

I'm trying to find a matching username and print out the username and password.

Regards
Augustas

Edited by augustas656, 27 April 2014 - 06:59 PM.


#2 MKlegoman357

  • Members
  • 1,170 posts
  • LocationKaunas, Lithuania

Posted 27 April 2014 - 07:22 PM

Next time post the full error message you get.

Your problem is using break after return. After returning (using return keyword) or breaking out of the loop (using break keyword) the code after return or break isn't executed, plus Lua expects an end, else, until, etc. and doesn't even allow to write any code after those keywords.

It would be easier if you would setup your table using usernames as keys and passwords as values:

local users = {
  ["testuser"] = "testpassword",
  ["anotheruser"] = "123"
}

local username = read() --// Ask for a username
local password = read() --// Ask for a password

if users[username] and users[username] == password then --// If the user exists and the password is correct
  print("Welcome " .. username .. "!")
else --// If the username or password was incorrect
  print("Wrong username or password!")
end

Edited by MKlegoman357, 27 April 2014 - 07:22 PM.


#3 augustas656

  • Members
  • 158 posts

Posted 28 April 2014 - 04:49 PM

If I recall correctly, you don't need [" "], you just type in without the square brackets or quotes, it's like a variable, variable being the key and value being the value.
But you can access the key the same way by ["username"] whereas inside the table it's username = "password"

#4 HometownPotato

  • Members
  • 62 posts

Posted 28 April 2014 - 05:03 PM

You need to use brackets if the key has spaces or non-alphanumerical characters or if it starts with a number.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users