'Getting error 'for' loop limit must be a number
when implementing for loop I get error 'for' limit must be a number and here is my code,and my input is number phone,can someone help me edit, let me complete. Thank you
local a = tonumber(nameInput.value);
for i = 1,tonumber(nameInput.value),1 do
line = fh:read()
if line == nil then break end
a = a +tonumber(nameInput.value);
Solution 1:[1]
tonumber will return nil if the value passed to it can not be converted, a phone number like 123-456-7890 is not a valid input to
tonumber it does not know what to do with the -s in the string.
Some documentation on tonumber:
Lua 5.3 Manual: tonumber
to handle this you can use or 0 in lua to create a ternary of sorts.
local a = tonumber(nameInput.value) or 0;
for i = 1,tonumber(nameInput.value) or 0,1 do
line = fh:read()
if line == nil then break end
a = a +tonumber(nameInput.value);
end
now when tonumber(nameInput.value) returns nil you will use the default value of 0. With this change you will no longer see the error but when nameInput.value is a non-numeric value you will also no enter your loop.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nifim |
