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

原文地址http://www.freecls.com/a/2712/17

type(v)

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


tonumber(e [,base])

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

例子

--把16进制a装成10进制
--10
local res = tonumber('a',16)

--把8进制的10转成10进制
--8
res = tonumber('10',8)

--把10进制10转成16进制
--a
res = string.format('%x',10)


tostring(e)

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


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

以保护模式调用函数(也就是报错也不抛出异常)

例子

function add(x,y)
    return x+y
end

--成功stat为true,data为返回的数据
--true    3
stat,data = pcall(add,1,2)

--失败stat为false,data为报错信息
--false	tmp.lua:2: attempt to perform arithmetic on local 'x' (a string value)
stat,data = pcall(add,'http://www.freecls.com',2)


print(...)

简单的打印各个参数为字符串(调用tostring函数)

例子

local str = 'http://www.freecls.com'
local name = '沧浪水'

--http://www.freecls.com	沧浪水	1	2	3	4	5
print(str,name,1,2,3,4,5)


总结

1.本文对几个基础函数做简单的介绍,如果有疑问可以给我留言
2.lua的版本为5.1,运行环境centos7 64位
3.原文地址http://www.freecls.com/a/2712/17

猜你喜欢

转载自blog.csdn.net/freecls/article/details/80280518