2017-05-27 17 views
0

問題是當txt.text爲空時出現錯誤。lua中的TextFiled輸入爲空時出錯?

--input text 
local txt = native.newTextField(160,100,300,50) 
--button press to get answer 
local btn = display.newRect(160,300,120,40) 
--label text to show answer 
local label = display.newText("answer",160,200) 

txt.inputType = "number" 

function doit(e) 
    -- Currency exchange (USD to any country) 
    label.text = txt.text * 2 
    -- when txt.text == empty I get error 
end 

btn:addEventListener("tap",doit) 

我試圖使用if else但同樣的問題。

回答

1

您只需添加適當的if聲明。嘗試:

function doit (e) 
    if tonumber(txt.text) then 
     label.text = tonumber(txt.text) * 2 
    end 
end 

其餘代碼保持不變。