-- 如果待判断的是一个变量
local theType = type(theObject)
if theType == "number" then
-- 是数字
elseif theType == "string" then
-- 是字符串
elseif theType == "table" then
-- 是Lua表
end
-- 如果带判断是一个字符串,要判断是否可以转成数字, 则
local theNumber = tonumber(theObject);
if theNumber ~= nil then
-- theNumber 就是得到的数字
else
-- 转换数字失败 这时theNumber = nil
end
-- 如果支持toLua的工具,也可以使用
local theNumber = checkint(theObject)
-- ↑使对象转换为int
-- 顺带一提,强制类型转换,以cocos2dx为例,转Node为Sprite
local theObjectNode = xxLayer:getChildByTag(233)
if theObjectNode ~= nil then
local theSprite = tolua.cast(theObjectNode , "cc.Sprite")
end
Lua类型判断和转换的简易方法
最新推荐文章于 2023-04-18 23:30:42 发布
本文介绍了在Lua中如何判断变量的类型以及如何将不同类型的变量进行转换的方法。具体包括检查变量是否为数字、字符串或Lua表,并演示了如何使用tonumber和checkint函数将字符串转换为数字。
644

被折叠的 条评论
为什么被折叠?



