lua data type conversion

Lua provides type conversion functions, these conversion functions include: conversion to number and conversion to string, etc.


1. Convert to string
tostring() can convert boolean type and numeric type to string type, for example:


local bVar = false;
print(tostring(bVar)); -- output "false"


local num1 = 10;
local num2 = 10.0;
local num3 = 10.03;
print(tostring(num1)); -- output "10"
print(tostring(num2)); -- output "10"
print(tostring(num3)); -- output "10.03"


local t = {x = 10,y = 0};
print(tostring(t)); -- output nil, cannot convert table type to string
1
2
3
4
5
6
7
8
9
10
11
12
2. Convert to Number
tonumber() can convert non-numeric primitive values ​​to numbers, for example:


local num = tonumber("10"); -- returns the decimal number 10
local num = tonumber("AF",16); -- returns the hexadecimal number 175 
local num = tonumber("0xA"); -- returns 10
local num = tonumber("56.9"); -- returns 56.9
local num = tonumber("0102"); -- returns 102
local num = tonumber("123456red"); -- returns nil
local num = tonumber("red "); -- returns nil
local num = tonumber("true"); -- returns nil
local num = tonumber({x =10, y = 20});-- returns nil
1
2
3
4
5
6
7
8
9
Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission. https://blog.csdn.net/mitu405687908/article/details/51137956

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325711253&siteId=291194637