lua 中的文本字段输入为空时出错?
Error when TextFiled Input in lua is empty?
问题是当 txt.text 为空时出现错误。
--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
但同样的问题。
您只需要添加适当的 if
语句。尝试:
function doit (e)
if tonumber(txt.text) then
label.text = tonumber(txt.text) * 2
end
end
其余代码保持不变。
问题是当 txt.text 为空时出现错误。
--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
但同样的问题。
您只需要添加适当的 if
语句。尝试:
function doit (e)
if tonumber(txt.text) then
label.text = tonumber(txt.text) * 2
end
end
其余代码保持不变。