2013-05-10 68 views
2

我正在嘗試創建一個函數getInput(prompt, number),其中prompt是將在用戶輸入前面打印的文本(例如>Choose a password:),而number是一個布爾值,用於指示輸入是數字還是任何類型。避免編寫代碼兩次,同時保持正確的代碼方式?

這是我寫的函數:

function getInput(prompt, number) 
    if number then 
     while not input do 
      io.write(prompt) 
      input = tonumber(io.read()) 
     end 
    else 
     io.write(prompt) 
     input = io.read() 
    end 
    return input 
end 

不過,我重複的代碼相當很多。 我有io.write(prompt)寫了兩次,我也有input = io.read()兩次與tonumber()圍繞其中一個電話。 我基本上只是重複相同的事情兩次,一次在while循環,一次不在。

這裏有一個小的解決方法我做:

function getInput(prompt, number) 
    while not input do 
     io.write(prompt) 
     input = io.read() 
     if number then 
      input = tonumber(input) 
     end 
    end 
    return input 
end 

這個版本只有io.write()io.read()寫一次,但它不是「正確」的代碼。 即使不需要(當number爲false時),我仍在使用while循環。 我也在做if number檢查while循環的每一輪(當number爲真)。

我應該去第一個代碼,還是有一種方法來改善第二個代碼,使其更「適當」?

+0

第二個版本在到達EOF時會永遠循環。 – lhf 2013-05-10 16:16:01

+1

'input'是全球性的,它的值保留了以前的呼叫,所以這兩個函數都不會要求用戶在第二次呼叫時輸入數據。 – 2013-05-10 16:22:15

+0

還要考慮'read(「* n」)'來讀取一個數字。那麼你的代碼路徑就不一樣了。 – daurnimator 2013-05-10 17:00:09

回答

3

一般情況下,重複一個非常簡單的單行代碼類似io.write(prompt)的代碼不會被視爲「代碼重複」。此外,重複檢查相同的簡單條件通常不會被認爲是性能危險。兩種方式都具有同等的可讀性,所以任何一種都可以,這取決於您的偏好。

的一種可能的改進將被分裂功能在兩個,並且丟棄number標誌,這樣的:

function getInput(prompt) 
    io.write(prompt) 
    return io.read() 
end 
function getNumericInput(prompt) 
    while not input do 
     io.write(prompt) 
     input = tonumber(io.read()) 
    end 
    return input 
end 

然而,這可能不是當輸入的類型是在運行時決定在以下情況下接受的,並且必須通過變量來控制。

+0

那麼我不會有這個問題,除了你只能寫文本和/或數字,所以這將是足夠的! :) – 2013-05-10 16:20:23

1
local function getInput(prompt, number) 
    io.write(prompt) 
    local input = (number and tonumber or assert)((assert(io.read(), 'EOF'))) 
    return (input and function() return input end or getInput)(prompt, number) 
end 
+0

這不是一個尾部調用,可能會溢出調用堆棧。 – lhf 2013-05-10 16:48:16

+0

@lhf - 修正後打個電話:-) – 2013-05-10 18:06:59

0

那麼,我會說,第一種形式是非常清晰,易於閱讀。即使你寫了兩次非常相似的語句,它也沒什麼問題。

我唯一的建議是將它分成沒有布爾標誌(即,getInput(提示)和getNumericInput(提示))的兩個函數,或者將布爾值更改爲類型並將邏輯捕捉合適的類型,以一個單獨的方法:

function getInput(prompt, type) 
    io.write(prompt) 
     input = getTypedInput(type) 
    return input 
end 

function getTypedInput(type) 
    input(io.read()) 
    ...change to type here <I don't know lua syntax) 
    return input 
end 

後者可能是你有問題矯枉過正,除非你認爲有你會比數字或非數字使用更多類型的機會。