код lua работает, но останавливается до завершения кода - PullRequest
0 голосов
/ 02 мая 2019

Я делаю код пользовательского ввода для lua, и если вы допустили ошибку при вводе информации, вы можете исправить это, сказав, что вы хотите исправить.После того, как вы введете две буквы (например, скажете, что вы написали неправильно на английском и написали это по-английски, вы наберете HT, чтобы исправить это.), Он предложит вам исправить это, и после того, как вы это сделаете, он просто скажет, что код завершен, даже если онis not.

Я попытался сделать переменные локальными, сделать блоки все ifs, а не elseif.

--user input--
print('Hello, what is your name? ')
local name = io.read()
print('What is your last name?')
local LastName = io.read()
print('The place you live?')
local Hometown = io.read()
print('Lastly, what is your favourite video game?')
local VideoGame = io.read()

--Printing the information--
print(
  'You are ' .. name .. ' ' .. LastName ..
  ' you live in ' .. Hometown ..
  ' and your favourite video game is ' .. VideoGame .. '.'
)
print('right?')

-- confirmation --    
io.write("press 1 i was correct, and press 2 if i was wrong.")
answer = io.read()

if answer == "1" then
  print('Yay, I was correct!')

elseif answer == "2" then
  print('aww, I was wrong. Do you want to enter the information again?  Say yes or no.')

  local answer2 = io.read()

  if answer2 == "yes" then
    print('What would you like to change? Type either FN, LN, HT or VG to change which one you would like.')

    local answer3 = io.read()

    if answer3 == FN then
      io.write('Ok, please enter the corrected version of your first name.')
      answerFN = io.read()
      io.write('Here is the corrected version.')
      io.write(
        'You are ' .. answerFN .. ' ' .. LastName ..
        ' you live in ' .. Hometown ..
        ' and your favourite video game is ' .. answerVG .. '.'
      )
    end

    if answer3 == LN then
      print('Ok, please enter the corrected version of your last name.')
      answerLN = io.read()
      print('Here is the corrected version.')
      print(
        'You are ' .. name .. ' ' .. answerLN ..
        ' you live in ' .. Hometown ..
        ' and your favourite video game is ' .. answerVG .. '.'
      )
    end

    if answer3 == HT then
      print('Ok, please enter the corrected version of your hometown.')
      answerHT = io.read()
      print('Here is the corrected version.')
      print(
        'You are ' .. name .. ' ' .. LastName ..
        ' you live in ' .. answerHT ..
        ' and your favourite video game is ' .. answerVG .. '.'
      )
    end


    if answer3 == VG then
      print('Ok, please enter the corrected version of your favourite video game.')
      answerVG = io.read()
      print('Here is the corrected version.')
      print(
        'You are ' .. name .. ' ' .. LastName ..
        ' you live in ' .. Hometown ..
        ' and your favourite video game is ' .. answerVG .. '.'
      )
    end

    if answer2 == "no" then
      print('Alright, tough luck. You can run the code again if you change your mind.')
    end
  end
end

Я ожидал, что это напечатает 'ок, поместите исправленную версию ..., но это даже не сработало.

Ответы [ 2 ]

1 голос
/ 02 мая 2019

Возможно, вы захотите изменить answer3 == VG на answer3 == "VG" (и другие тоже).В настоящее время он сравнивается с переменной с именем VG, которая предположительно не существует.

0 голосов
/ 02 мая 2019

После того, как вы предложите пользователю ввести «да» или «нет» в сообщении 'aww, I was wrong. Do you want to enter the information again? Say yes or no.', вы спросите, какие изменения необходимы, и сохраните введенные пользователем данные в переменной answer3.

Но вы сравниваете значение answer3 с другими переменными , такими как FN, LN и т. Д., Вместо строк, таких как "FN" и "LN".

Lua не жалуется на это, так как считается, что неопределенные переменные имеют значение nil.


Кроме того, вы использовали неопределенную переменную answerVG, когда изменяется только FN или LN или HT. Вместо этого используйте переменную VideoGame.


При сравнении значения answer3 вместо использования различных if .. end s, вы можете использовать лестницу if-else, такую ​​как

if <condition1> then
    ...
elseif <condition2> then
    ...
else
    ...
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...