Lua judges whether the variable is a number, whether the string can be converted to a number, etc

Time:2022-4-19

1、 Lua determines whether it is a character or a number

Copy codeThe code is as follows:


–If it’s a variable to judge

 

local t = type(x);
if t == “number” then
— it’s a number
else if t == “string” then
— is a string
end

–If the string is a string and you want to judge whether it can be converted into a number, then
local n = tonumber(x);
if n then
— N is to get the number
else
— failed to convert to number. It is not a number. At this time, n = = nil
end

 

2、 Lua judge number

Judgment explicit

Type can judge the type that has been converted, but it can distinguish strings because it looks at the original type.

Copy codeThe code is as follows:

>a=”12″
>print(type(a))
string

 

experience

1. Judge whether it can be converted
The direct conversion test can determine whether it can be converted to that type, that is, whether it can be that type of string pattern.

Copy codeThe code is as follows:

> print(tonumber(“222”))
222
> print(tonumber(“222a”))
nil
>


Judge and prepare an initial value

Copy codeThe code is as follows:

Srcstr = ToNumber (“2323224a”) or 1 — nil overflows, but gets 1
Print (“transfer number”. Srcstr)