lua基础函数 type,tonumber,tostring,pcall,print

type(v)

用来判断v的类型
返回字符串"nil", "number", "string", "boolean", "table", "function", "thread", "userdata"

tonumber(e [,base])

把e(必须为数字或者是可以转成数字的字符串)转成10进制数字,base为多少进制(可以为2-36),默认为10

例子

local num = tonumber("10")                      --返回 十进制数10

local num = tonumber("AF", 16)                  --返回 十六进制数175

local num = tonumber("0xA")                     --返回10

local num = tonumber("56.9")                    --返回56.9

local num = tonumber("0102")                    --返回102

 

local num = tonumber("12345red")                --返回nil

local num = tonumber("red")                     --返回nil

local num = tonumber(true)                      --返回nil

local num = tonumber({x = 10, y = 20})          --返回nil 

tostring(e)

把任意类型的e已适当的方式转成字符串,如果e的原表有__tostring函数,则调用并传入e作为参数,把返回值作为结果返回。

 

local found = true

print(tostring(found))                          --输出"true"

local num1 = 100

local num2 = 100.0

local num3 = 100.01

print(tostring(num1))                           --输出"100"

print(tostring(num2))                           --输出"100"

print(tostring(num3))                           --输出"100.01"

 

pcall (f [, arg1, ···])

Lua中处理错误,使用函数pcall(protected call)来包装需要执行的代码。

例子

> =pcall(function(i) print(i) end, 33)
33
true
   
> =pcall(function(i) print(i) error('error..') end, 33)
33
false        stdin:1: error..

 



 

 

posted @ 2022-02-22 22:29  durtime  阅读(722)  评论(0)    收藏  举报