local tonumber_ = tonumber

function tonumber(v, base)
return tonumber_(v, base) or
end function toint(v)
return math.round(tonumber(v))
end function tobool(v)
return (v ~= nil and v ~= false)
end function totable(v)
if type(v) ~= "table" then v = {} end
return v
end function clone(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for key, value in pairs(object) do
new_table[_copy(key)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end function class(classname, super)
local superType = type(super)
local cls if superType ~= "function" and superType ~= "table" then
superType = nil
super = nil
end if superType == "function" or (super and super.__ctype == ) then
-- inherited from native C++ Object
cls = {} if superType == "table" then
-- copy fields from super
print ("superTyper is table");
for k,v in pairs(super) do cls[k] = v end
cls.__create = super.__create
cls.super = super
else
cls.__create = super
cls.ctor = function() end
end cls.__cname = classname
cls.__ctype = function cls.new(...)
local instance = cls.__create(...)
-- copy fields from class to native object
for k,v in pairs(cls) do instance[k] = v end
instance.class = cls
instance:ctor(...)
return instance
end else
-- inherited from Lua Object
if super then
cls = {}
setmetatable(cls, {__index = super})
cls.super = super
else
cls = {ctor = function() end}
end cls.__cname = classname
cls.__ctype = -- lua
cls.__index = cls function cls.new(...)
local instance = setmetatable({}, cls)
instance.class = cls
instance:ctor(...)
return instance
end
end return cls
end function import(moduleName, currentModuleName)
local currentModuleNameParts
local moduleFullName = moduleName
local offset = while true do
if string.byte(moduleName, offset) ~= then -- .
moduleFullName = string.sub(moduleName, offset)
if currentModuleNameParts and #currentModuleNameParts > then
moduleFullName = table.concat(currentModuleNameParts, ".") .. "." .. moduleFullName
end
break
end
offset = offset + if not currentModuleNameParts then
if not currentModuleName then
local n,v = debug.getlocal(, )
currentModuleName = v
end currentModuleNameParts = string.split(currentModuleName, ".")
end
table.remove(currentModuleNameParts, #currentModuleNameParts)
end return require(moduleFullName)
end function handler(target, method)
return function(...) return method(target, ...) end
end function math.round(num)
return math.floor(num + 0.5)
end function io.exists(path)
local file = io.open(path, "r")
if file then
io.close(file)
return true
end
return false
end function io.readfile(path)
local file = io.open(path, "r")
if file then
local content = file:read("*a")
io.close(file)
return content
end
return nil
end function io.writefile(path, content, mode)
mode = mode or "w+b"
local file = io.open(path, mode)
if file then
print("file is ok ok ok ok ok ")
if file:write(content) == nil then print("file is bad bad bad bad ") return false end
io.close(file)
return true
else
return false
end
end function io.pathinfo(path)
local pos = string.len(path)
local extpos = pos +
while pos > do
local b = string.byte(path, pos)
if b == then -- 46 = char "."
extpos = pos
elseif b == then -- 47 = char "/"
break
end
pos = pos -
end local dirname = string.sub(path, , pos)
local filename = string.sub(path, pos + )
extpos = extpos - pos
local basename = string.sub(filename, , extpos - )
local extname = string.sub(filename, extpos)
return {
dirname = dirname,
filename = filename,
basename = basename,
extname = extname
}
end function io.filesize(path)
local size = false
local file = io.open(path, "r")
if file then
local current = file:seek()
size = file:seek("end")
file:seek("set", current)
io.close(file)
end
return size
end function table.nums(t)
local count =
for k, v in pairs(t) do
count = count +
end
return count
end function table.keys(t)
local keys = {}
if t == nil then
return keys;
end
for k, v in pairs(t) do
keys[#keys + ] = k
end
return keys
end function table.values(t)
local values = {}
if t == nil then
return values;
end
for k, v in pairs(t) do
values[#values + ] = v
end
return values
end function table.containKey( t, key )
for k, v in pairs(t) do
if key == k then
return true;
end
end
return false;
end function table.containValue( t, value )
for k, v in pairs(t) do
if value == v then
return true;
end
end
return false;
end function table.getKeyByValue( t, value )
for k, v in pairs(t) do
if value == v then
return k;
end
end
end function table.merge(dest, src)
for k, v in pairs(src) do
dest[k] = v
end
end function arrayContain( array, value)
for i=,#array do
if array[i] == value then
return true;
end
end
return false;
end function string.htmlspecialchars(input)
for k, v in pairs(string._htmlspecialchars_set) do
input = string.gsub(input, k, v)
end
return input
end
string._htmlspecialchars_set = {}
string._htmlspecialchars_set["&"] = "&"
string._htmlspecialchars_set["\""] = """
string._htmlspecialchars_set["'"] = "'"
string._htmlspecialchars_set["<"] = "&lt;"
string._htmlspecialchars_set[">"] = "&gt;" function string.nl2br(input)
return string.gsub(input, "\n", "<br />")
end function string.text2html(input)
input = string.gsub(input, "\t", " ")
input = string.htmlspecialchars(input)
input = string.gsub(input, " ", "&nbsp;")
input = string.nl2br(input)
return input
end function string.split(str, delimiter)
if (delimiter=='') then return false end
local pos,arr = , {}
-- for each divider found
for st,sp in function() return string.find(str, delimiter, pos, true) end do
table.insert(arr, string.sub(str, pos, st - ))
pos = sp +
end
table.insert(arr, string.sub(str, pos))
return arr
end function string.ltrim(str)
return string.gsub(str, "^[ \t\n\r]+", "")
end function string.rtrim(str)
return string.gsub(str, "[ \t\n\r]+$", "")
end function string.trim(str)
str = string.gsub(str, "^[ \t\n\r]+", "")
return string.gsub(str, "[ \t\n\r]+$", "")
end function string.ucfirst(str)
return string.upper(string.sub(str, , )) .. string.sub(str, )
end --[[--
@ignore
]]
local function urlencodeChar(char)
return "%" .. string.format("%02X", string.byte(c))
end function string.urlencode(str)
-- convert line endings
str = string.gsub(tostring(str), "\n", "\r\n")
-- escape all characters but alphanumeric, '.' and '-'
str = string.gsub(str, "([^%w%.%- ])", urlencodeChar)
-- convert spaces to "+" symbols
return string.gsub(str, " ", "+")
end function string.utf8len(str)
local len = #str
local left = len
local cnt =
local arr = {, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}
while left ~= do
local tmp = string.byte(str, -left)
local i = #arr
while arr[i] do
if tmp >= arr[i] then
left = left - i
break
end
i = i -
end
cnt = cnt +
end
return cnt
end function string.formatNumberThousands(num)
local formatted = tostring(tonumber(num))
local k
while true do
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
if k == then break end
end
return formatted
end function print_lua_table (lua_table, indent)
indent = indent or
for k, v in pairs(lua_table) do
if type(k) == "string" then
k = string.format("%q", k)
end
local szSuffix = ""
if type(v) == "table" then
szSuffix = "{"
end
local szPrefix = string.rep(" ", indent)
formatting = szPrefix.."["..k.."]".." = "..szSuffix
if type(v) == "table" then
print(formatting)
print_lua_table(v, indent + )
print(szPrefix.."},")
else
local szValue = ""
if type(v) == "string" then
szValue = string.format("%q", v)
else
szValue = tostring(v)
end
print(formatting..szValue..",")
end
end
end local function newCounter()
local i =
return function() -- anonymous function
i = i +
return i
end
end g_id_generator = newCounter() function getNextID()
local nextID
nextID = g_id_generator()
return nextID
end luautil = {};
function luautil.serialize(tName, t, sort_parent, sort_child)
local mark={}
local assign={} local function ser_table(tbl,parent)
mark[tbl]=parent
local tmp={}
local sortList = {};
for k,v in pairs(tbl) do
sortList[#sortList + ] = {key=k, value=v};
end if tostring(parent) == "ret" then
if sort_parent then table.sort(sortList, sort_parent); end
else
if sort_child then table.sort(sortList, sort_child); end
end for i = , #sortList do
local info = sortList[i];
local k = info.key;
local v = info.value;
local key= type(k)=="number" and "["..k.."]" or k;
if type(v)=="table" then
local dotkey= parent..(type(k)=="number" and key or "."..key)
if mark[v] then
table.insert(assign, "\n".. dotkey.."="..mark[v])
else
table.insert(tmp, "\n"..key.."="..ser_table(v,dotkey))
end
else
if type(v) == "string" then
table.insert(tmp, "\n".. key..'="'..v..'"');
else
table.insert(tmp, "\n".. key.."="..tostring(v) .. "\n");
end
end
end return "{"..table.concat(tmp,",").."\n}";
end return "do local ".. tName .. "= \n\n"..ser_table(t, tName)..table.concat(assign," ").."\n\n return ".. tName .. " end"
end function luautil.split(str, delimiter)
if (delimiter=='') then return false end
local pos,arr = , {}
-- for each divider found
for st,sp in function() return string.find(str, delimiter, pos, true) end do
table.insert(arr, string.sub(str, pos, st - ))
pos = sp +
end
table.insert(arr, string.sub(str, pos))
return arr
end function luautil.writefile(str, file)
os.remove(file);
local file=io.open(file,"ab"); local len = string.len(str);
local tbl = luautil.split(str, "\n");
for i = , #tbl do
file:write(tbl[i].."\n");
end
file:close();
end function luautil.readfile( strData )
local f = loadstring(strData)
if f then
return f()
end
end function Json2Lua (fileName,filePath, desFilePath)
local jsonString = io.readfile(filePath)--myfile:read("*a")
t = CJson.decode(jsonString)
if t then
t = luautil.serialize(fileName,t);
end
if t then
luautil.writefile(t, desFilePath)
end
end function performWithDelay(callback, delay)
local handle
handle = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(function()
CCDirector:sharedDirector():getScheduler():unscheduleScriptEntry(handle)
handle = nil
callback();
end , delay , false)
end -- 参数:待分割的字符串,分割字符
-- 返回:子串表.(含有空串)
function lua_string_split(str, split_char)
local sub_str_tab = {};
while (true) do
local pos = string.find(str, split_char);
if (not pos) then
sub_str_tab[#sub_str_tab + ] = str;
break;
end
local sub_str = string.sub(str, , pos - );
sub_str_tab[#sub_str_tab + ] = sub_str;
str = string.sub(str, pos + , #str);
end return sub_str_tab;
end --去除扩展名
function stripExtension(filename)
local idx = filename:match(".+()%.%w+$")
if(idx) then
return filename:sub(, idx-)
else
return filename
end
end --获取路径
function stripfilename(filename)
return string.match(filename, "(.+)/[^/]*%.%w+$") --*nix system
--return string.match(filename, “(.+)\\[^\\]*%.%w+$”) — windows
end --获取文件名
function strippath(filename)
return string.match(filename, ".+/([^/]*%.%w+)$") -- *nix system
--return string.match(filename, “.+\\([^\\]*%.%w+)$”) — *nix system
end -- 生产配置文件
function genCfg( )
local assets = require("res.Asset")
local sceneKey = "Scene"
local commonKey = "common"
local className = {"textures", "atlas", "sounds", "animations"} local config = {}; for i=,#assets do
local k = assets[i].k;
local v = assets[i].v; local pathnames = lua_string_split(v, "/");
local fileName = pathnames[#pathnames];
local name = stripExtension(fileName);
local pathType = fileName:match(".+%.(%w+)$");
local sceneType;
local commonType;
local cur;
for i=,#pathnames do
cur = pathnames[i];
-- 1. 检查该路径是否是场景
if string.find(cur, sceneKey) then
sceneType = cur;
if not config[sceneType] then
config[sceneType] = {};
end
end if string.find(cur, commonKey) then
commonType = cur;
if not config[commonType] then
config[commonType] = {};
end
end -- 2. 查找资源类型
-- 2.1 是场景资源
if sceneType then
for n=,#className do
local t = className[n];
if cur == t then
if not config[sceneType][t] then
config[sceneType][t] = {};
end if (t == "atlas" and pathType == "plist") then
config[sceneType][t][name] = v;
end if t == "atlas" and pathType == "ExportJson" then
if not config[sceneType]["json"] then
config[sceneType]["json"] = {}
end
config[sceneType]["json"][name] = v;
end if (t == "textures") then
config[sceneType][t][name] = v;
end if (t == "animations" and pathType == "xml") then
config[sceneType][t][name] = v;
end if (t == "sounds") then
config[sceneType][t][name] = v;
end
end
end -- 2.2 是公用资源
elseif commonType then
for n=,#className do
local t = className[n];
if cur == t then
if not config[commonType][t] then
config[commonType][t] = {};
end if (t == "atlas" and pathType == "plist") then
config[commonType][t][name] = v;
end if t == "atlas" and pathType == "ExportJson" then
if not config[commonType]["json"] then
config[commonType]["json"] = {}
end
config[commonType]["json"][name] = v;
end if (t == "textures") then
config[commonType][t][name] = v;
end if (t == "animations" and pathType == "xml") then
config[commonType][t][name] = v;
end if (t == "sounds") then
config[commonType][t][name] = v;
end
end
end -- 2.3 贴图资源
elseif string.find(cur, "textures") then
if not config["textures"] then
config["textures"] = {}
end
config["textures"][name] = v;
-- 2.4 图集资源
elseif string.find(cur, "atlas") and pathType == "plist" then
if not config["atlas"] then
config["atlas"] = {}
end
config["atlas"][name] = v;
-- 2.5 图集json配置文件
elseif string.find(cur, "atlas") and pathType == "ExportJson" then
if not config["json"] then
config["json"] = {}
end
config["json"][name] = v;
-- 2.6 声音资源
elseif string.find(cur, "sounds") then
if not config["sounds"] then
config["sounds"] = {}
end
config["sounds"][name] = v;
-- 2.7 字体资源
elseif string.find(cur, "fonts") and (pathType == "fnt" or pathType == "ttf" ) then
if not config["fonts"] then
config["fonts"] = {}
end
config["fonts"][name] = v;
-- 2.8 动画资源
elseif string.find(cur, "animations") and pathType == "xml" then
if not config["animations"] then
config["animations"] = {}
end
config["animations"][name] = v;
end
end
end return config;
end

lua 工具类(二)的更多相关文章

  1. java工具类(二)之java正则表达式表单验证

    java正则表达式表单验证类工具类(验证邮箱.手机号码.qq号码等) 这篇文章主要介绍了java使用正则表达式进行表单验证工具类,可以验证邮箱.手机号码.qq号码等方法,需要的朋友可以参考下. jav ...

  2. Java学习笔记49(DBUtils工具类二)

    上一篇文章是我们自己模拟的DBUtils工具类,其实有开发好的工具类 这里使用commons-dbutils-1.6.jar 事务的简单介绍: 在数据库中应用事务处理案例:转账案例 张三和李四都有有自 ...

  3. cocos2dx 3.0 之 lua 创建类 (二)

    利用lua 中的table 特性 Base = {x = 0,y = 0} Base.name = "luohai"Base.age = 12Base.sex = "ma ...

  4. JDK1.8 LocalDate 使用方式;LocalDate 封装Util,LocalDate工具类(二)

    未完待续 ........ java.time.*代替方案 1.Instant 代替 Date2.LocalDateTime 代替 Calendar3.DateTimeFormatter 代替 Sim ...

  5. lua 工具类(一)

    -- -- Author: My Name -- Date: 2013-12-16 18:52:11 -- csv解析 -- -- 去掉字符串左空白 local function trim_left( ...

  6. Lua工具类

    1.打印table --一个用以打印table的函数 function print_r (t, name) print(pr(t,name)) end function pr (t, name, in ...

  7. 并发编程常用工具类(二) SymaPhore实现线程池

    1.symaPhore简介 symaphore(信号量)用来控制同时访问某个资源的线程数量,一般用在并发流量控制.个人对它的理解相当于是接待室每次只能接待固定数量的人,当达到最高接待数的时候,其他人就 ...

  8. 自定义的jdbc连接工具类JDBCUtils【java 工具类】

    JDBCUtils 类设计: 1. 创建私有的属性*(连接数据库必要的四个变量):dreiver url user password 2. 将构造函数私有化 3.将注册驱动写入静态代码块 4.外界只能 ...

  9. Collections集合工具类

    一.Collection与Collections Collection 是所有单列集合的根接口 Collection 是操作集合的工具类 二.Collections中常见的方法:(大都是static方 ...

随机推荐

  1. 2011的n次方

    题目:http://noi.openjudge.cn/ch0204/2991/ 总时间限制:1000ms  内存限制: 65536kB 描述 已知长度最大为200位的正整数n,请求出2011^n的后四 ...

  2. 删数问题(NOI94)

    删数问题(NOI94) 输入一个高精度的正整数N,去掉其中任意S个数字后剩下的数字按原左右次序组成一个新的正整数.编程对给定的N和S,寻找一种方案使得剩下的数字组成的新数最小.输出新的正整数.(N不超 ...

  3. RHEL7 光盘修复

    光盘修复#rm -rf /boot/*#dd if=/dev/zero of=/dev/sda bs=446 count=1#systemctl rebootTroubleshooting(排错模式) ...

  4. Axure快速原型教程02--创建页面和设置界面

    目录 Axure快速原型教程02--创建页面和设置界面 Axure快速原型教程01--原型说明下载和安装 首先,在左侧的面板中,我们发现有一个叫sitemap的面板,这个面板就是我们的一个个的页面了, ...

  5. Linux-LVS为何不能完全替代DNS轮询

    转自:链接 上一篇文章“一分钟了解负载均衡的一切”引起了不少同学的关注,评论中大家争论的比较多的一个技术点是接入层负载均衡技术,部分同学持这样的观点: 1)nginx前端加入lvs和keepalive ...

  6. 安全删除linux旧内核的方法

    我们在用yum升级系统之后,希望往往会为我们保持旧的内核文件,这样以防在出现硬件或者软件冲突的时候我们能够返回到旧的内核文件继续使用,如果我们想要安全的删除旧的内核文件,可以follow下面的方法. ...

  7. [转]极不和谐的 fork 多线程程序

    极不和谐的 fork 多线程程序 继续前几天的话题.做梦幻西游服务器优化的事情.以往的代码,定期存盘的工作分两个步骤,把 VM 里的动态数据序列化,然后把序列化后的数据写盘.这两个步骤,序列化工作并没 ...

  8. Hibernate+maven+eclipse 实现自动建表

    一.需求 如题,当建好Model 时,不想自己手工建表,可以采取hibernate进行自动建表.下面将用一个小例子来说明如何将其实现. 二.实现 说明:1)这里用的是4.3.1.Final版本的hib ...

  9. Windows Sockets错误标识及对应解释

    WSAETIMEDOUT 对应 linux 的 ETIMEDOUT WSAETIMEDOUT 对应 linux 的 ETIMEDOUT IdWinsock2.pas 文件中也有说明. Windows ...

  10. cd及目录快速切换

    一.cd   ~ 切换到用户目录 二.cd   - cd - 返回进入当前目录前所在目录 三.pushd.popd.dirs 在Linux的多目录命令提示符中工作是一种痛苦的事情,但以下这些利用lin ...