首页 / LUA / lua 工具类(二)
lua 工具类(二)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了lua 工具类(二),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含13793字,纯文字阅读大概需要20分钟。
内容图文
![lua 工具类(二)](/upload/InfoBanner/zyjiaocheng/1243/832f59b8e9f94d9bb94eaccf4d67b410.jpg)
local tonumber_ = tonumberfunctiontonumber(v, base) return tonumber_(v, base) or0endfunction toint(v) return math.round(tonumber(v)) endfunction tobool(v) return (v ~= niland v ~= false) endfunction totable(v) iftype(v) ~= "table"then v = {} endreturn v endfunction clone(object) local lookup_table = {} localfunction_copy(object) iftype(object) ~= "table"thenreturn object elseif lookup_table[object] thenreturn lookup_table[object] endlocal new_table = {} lookup_table[object] = new_table for key, value inpairs(object) do new_table[_copy(key)] = _copy(value) endreturnsetmetatable(new_table, getmetatable(object)) endreturn_copy(object) endfunction class(classname, super) local superType = type(super) local cls if superType ~= "function"and superType ~= "table"then superType = nil super = nilendif superType == "function"or (super and super.__ctype == 1) then-- inherited from native C++ Object cls = {} if superType == "table"then-- copy fields from superprint ("superTyper is table"); for k,v inpairs(super) do cls[k] = v end cls.__create = super.__create cls.super = super else cls.__create = super cls.ctor = function() endend cls.__cname = classname cls.__ctype = 1function cls.new(...) local instance = cls.__create(...) -- copy fields from class to native objectfor k,v inpairs(cls) do instance[k] = v end instance.class = cls instance:ctor(...) return instance endelse-- inherited from Lua Objectif super then cls = {} setmetatable(cls, {__index = super}) cls.super = super else cls = {ctor = function() end} end cls.__cname = classname cls.__ctype = 2-- lua cls.__index = cls function cls.new(...) local instance = setmetatable({}, cls) instance.class = cls instance:ctor(...) return instance endendreturn cls endfunction import(moduleName, currentModuleName) local currentModuleNameParts local moduleFullName = moduleName local offset = 1whiletruedoifstring.byte(moduleName, offset) ~= 46then-- . moduleFullName = string.sub(moduleName, offset) if currentModuleNameParts and #currentModuleNameParts > 0then moduleFullName = table.concat(currentModuleNameParts, ".") .. "." .. moduleFullName endbreakend offset = offset + 1ifnot currentModuleNameParts thenifnot currentModuleName thenlocal n,v = debug.getlocal(3, 1) currentModuleName = v end currentModuleNameParts = string.split(currentModuleName, ".") endtable.remove(currentModuleNameParts, #currentModuleNameParts) endreturnrequire(moduleFullName) endfunction handler(target, method) returnfunction(...) return method(target, ...) endendfunction math.round(num) returnmath.floor(num + 0.5) endfunction io.exists(path) local file = io.open(path, "r") if file thenio.close(file) returntrueendreturnfalseendfunction io.readfile(path) local file = io.open(path, "r") if file thenlocal content = file:read("*a") io.close(file) return content endreturnnilendfunction io.writefile(path, content, mode) mode = mode or"w+b"local file = io.open(path, mode) if file thenprint("file is ok ok ok ok ok ") iffile:write(content) == nilthenprint("file is bad bad bad bad ") returnfalseendio.close(file) returntrueelsereturnfalseendendfunction io.pathinfo(path) local pos = string.len(path) local extpos = pos + 1while pos > 0dolocal b = string.byte(path, pos) if b == 46then-- 46 = char "." extpos = pos elseif b == 47then-- 47 = char "/"breakend pos = pos - 1endlocal dirname = string.sub(path, 1, pos) local filename = string.sub(path, pos + 1) extpos = extpos - pos local basename = string.sub(filename, 1, extpos - 1) local extname = string.sub(filename, extpos) return { dirname = dirname, filename = filename, basename = basename, extname = extname } endfunction io.filesize(path) local size = falselocal file = io.open(path, "r") if file thenlocal current = file:seek() size = file:seek("end") file:seek("set", current) io.close(file) endreturn size endfunction table.nums(t) local count = 0for k, v inpairs(t) do count = count + 1endreturn count endfunction table.keys(t) local keys = {} if t == nilthenreturn keys; endfor k, v inpairs(t) do keys[#keys + 1] = k endreturn keys endfunction table.values(t) local values = {} if t == nilthenreturn values; endfor k, v inpairs(t) do values[#values + 1] = v endreturn values endfunction table.containKey( t, key ) for k, v inpairs(t) doif key == k thenreturntrue; endendreturnfalse; endfunction table.containValue( t, value ) for k, v inpairs(t) doif value == v thenreturntrue; endendreturnfalse; endfunction table.getKeyByValue( t, value ) for k, v inpairs(t) doif value == v thenreturn k; endendendfunction table.merge(dest, src) for k, v inpairs(src) do dest[k] = v endendfunction arrayContain( array, value) for i=1,#array doif array[i] == value thenreturntrue; endendreturnfalse; endfunction string.htmlspecialchars(input) for k, v inpairs(string._htmlspecialchars_set) do input = string.gsub(input, k, v) endreturn input end string._htmlspecialchars_set = {} string._htmlspecialchars_set["&"] = "&" string._htmlspecialchars_set["\""] = """ string._htmlspecialchars_set["‘"] = "'" string._htmlspecialchars_set["<"] = "<" string._htmlspecialchars_set[">"] = ">"function string.nl2br(input) returnstring.gsub(input, "\n", "<br />") endfunction string.text2html(input) input = string.gsub(input, "\t", "") input = string.htmlspecialchars(input) input = string.gsub(input, "", " ") input = string.nl2br(input) return input endfunction string.split(str, delimiter) if (delimiter==‘‘) thenreturnfalseendlocal pos,arr = 0, {} -- for each divider foundfor st,sp infunction() returnstring.find(str, delimiter, pos, true) enddotable.insert(arr, string.sub(str, pos, st - 1)) pos = sp + 1endtable.insert(arr, string.sub(str, pos)) return arr endfunction string.ltrim(str) returnstring.gsub(str, "^[ \t\n\r]+", "") endfunction string.rtrim(str) returnstring.gsub(str, "[ \t\n\r]+$", "") endfunction string.trim(str) str = string.gsub(str, "^[ \t\n\r]+", "") returnstring.gsub(str, "[ \t\n\r]+$", "") endfunction string.ucfirst(str) returnstring.upper(string.sub(str, 1, 1)) .. string.sub(str, 2) end--[[-- @ignore ]]localfunction urlencodeChar(char) return"%" .. string.format("%02X", string.byte(c)) endfunction 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 "+" symbolsreturnstring.gsub(str, "", "+") endfunction string.utf8len(str) local len = #str local left = len local cnt = 0local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc} while left ~= 0dolocal tmp = string.byte(str, -left) local i = #arr while arr[i] doif tmp >= arr[i] then left = left - i breakend i = i - 1end cnt = cnt + 1endreturn cnt endfunction string.formatNumberThousands(num) local formatted = tostring(tonumber(num)) local k whiletruedo formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", ‘%1,%2‘) if k == 0thenbreakendendreturn formatted endfunction print_lua_table (lua_table, indent) indent = indent or0for k, v inpairs(lua_table) doiftype(k) == "string"then k = string.format("%q", k) endlocal szSuffix = ""iftype(v) == "table"then szSuffix = "{"endlocal szPrefix = string.rep("", indent) formatting = szPrefix.."["..k.."]".." = "..szSuffix iftype(v) == "table"thenprint(formatting) print_lua_table(v, indent + 1) print(szPrefix.."},") elselocal szValue = ""iftype(v) == "string"then szValue = string.format("%q", v) else szValue = tostring(v) endprint(formatting..szValue..",") endendendlocalfunction newCounter() local i = 0returnfunction() -- anonymous function i = i + 1return i endend 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={} localfunction ser_table(tbl,parent) mark[tbl]=parent local tmp={} local sortList = {}; for k,v inpairs(tbl) do sortList[#sortList + 1] = {key=k, value=v}; endiftostring(parent) == "ret"thenif sort_parent thentable.sort(sortList, sort_parent); endelseif sort_child thentable.sort(sortList, sort_child); endendfor i = 1, #sortList dolocal info = sortList[i]; local k = info.key; local v = info.value; local key= type(k)=="number"and"["..k.."]"or k; iftype(v)=="table"thenlocal dotkey= parent..(type(k)=="number"and key or"."..key) if mark[v] thentable.insert(assign, "\n".. dotkey.."="..mark[v]) elsetable.insert(tmp, "\n"..key.."="..ser_table(v,dotkey)) endelseiftype(v) == "string"thentable.insert(tmp, "\n".. key..‘="‘..v..‘"‘); elsetable.insert(tmp, "\n".. key.."="..tostring(v) .. "\n"); endendendreturn"{"..table.concat(tmp,",").."\n}"; endreturn"do local ".. tName .. "= \n\n"..ser_table(t, tName)..table.concat(assign,"").."\n\n return ".. tName .. " end"endfunction luautil.split(str, delimiter) if (delimiter==‘‘) thenreturnfalseendlocal pos,arr = 0, {} -- for each divider found for st,sp infunction() returnstring.find(str, delimiter, pos, true) enddotable.insert(arr, string.sub(str, pos, st - 1)) pos = sp + 1endtable.insert(arr, string.sub(str, pos)) return arr endfunction 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 = 1, #tbl dofile:write(tbl[i].."\n"); endfile:close(); endfunction luautil.readfile( strData ) local f = loadstring(strData) if f thenreturn f() endendfunction Json2Lua (fileName,filePath, desFilePath) local jsonString = io.readfile(filePath)--myfile:read("*a") t = CJson.decode(jsonString) if t then t = luautil.serialize(fileName,t); endif t then luautil.writefile(t, desFilePath) endendfunction 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) dolocal pos = string.find(str, split_char); if (not pos) then sub_str_tab[#sub_str_tab + 1] = str; break; endlocal sub_str = string.sub(str, 1, pos - 1); sub_str_tab[#sub_str_tab + 1] = sub_str; str = string.sub(str, pos + 1, #str); endreturn sub_str_tab; end--去除扩展名function stripExtension(filename) local idx = filename:match(".+()%.%w+$") if(idx) thenreturn filename:sub(1, idx-1) elsereturn filename endend--获取路径function stripfilename(filename) returnstring.match(filename, "(.+)/[^/]*%.%w+$") --*nix system--return string.match(filename, “(.+)\\[^\\]*%.%w+$”) — windowsend--获取文件名function strippath(filename) returnstring.match(filename, ".+/([^/]*%.%w+)$") -- *nix system--return string.match(filename, “.+\\([^\\]*%.%w+)$”) — *nix systemend-- 生产配置文件function genCfg( ) local assets = require("res.Asset") local sceneKey = "Scene"local commonKey = "common"local className = {"textures", "atlas", "sounds", "animations"} local config = {}; for i=1,#assets dolocal 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=1,#pathnames do cur = pathnames[i]; -- 1. 检查该路径是否是场景ifstring.find(cur, sceneKey) then sceneType = cur; ifnot config[sceneType] then config[sceneType] = {}; endendifstring.find(cur, commonKey) then commonType = cur; ifnot config[commonType] then config[commonType] = {}; endend-- 2. 查找资源类型-- 2.1 是场景资源if sceneType thenfor n=1,#className dolocal t = className[n]; if cur == t thenifnot config[sceneType][t] then config[sceneType][t] = {}; endif (t == "atlas"and pathType == "plist") then config[sceneType][t][name] = v; endif t == "atlas"and pathType == "ExportJson"thenifnot config[sceneType]["json"] then config[sceneType]["json"] = {} end config[sceneType]["json"][name] = v; endif (t == "textures") then config[sceneType][t][name] = v; endif (t == "animations"and pathType == "xml") then config[sceneType][t][name] = v; endif (t == "sounds") then config[sceneType][t][name] = v; endendend-- 2.2 是公用资源elseif commonType thenfor n=1,#className dolocal t = className[n]; if cur == t thenifnot config[commonType][t] then config[commonType][t] = {}; endif (t == "atlas"and pathType == "plist") then config[commonType][t][name] = v; endif t == "atlas"and pathType == "ExportJson"thenifnot config[commonType]["json"] then config[commonType]["json"] = {} end config[commonType]["json"][name] = v; endif (t == "textures") then config[commonType][t][name] = v; endif (t == "animations"and pathType == "xml") then config[commonType][t][name] = v; endif (t == "sounds") then config[commonType][t][name] = v; endendend-- 2.3 贴图资源elseifstring.find(cur, "textures") thenifnot config["textures"] then config["textures"] = {} end config["textures"][name] = v; -- 2.4 图集资源elseifstring.find(cur, "atlas") and pathType == "plist"thenifnot config["atlas"] then config["atlas"] = {} end config["atlas"][name] = v; -- 2.5 图集json配置文件elseifstring.find(cur, "atlas") and pathType == "ExportJson"thenifnot config["json"] then config["json"] = {} end config["json"][name] = v; -- 2.6 声音资源elseifstring.find(cur, "sounds") thenifnot config["sounds"] then config["sounds"] = {} end config["sounds"][name] = v; -- 2.7 字体资源elseifstring.find(cur, "fonts") and (pathType == "fnt"or pathType == "ttf" ) thenifnot config["fonts"] then config["fonts"] = {} end config["fonts"][name] = v; -- 2.8 动画资源elseifstring.find(cur, "animations") and pathType == "xml"thenifnot config["animations"] then config["animations"] = {} end config["animations"][name] = v; endendendreturn config; end
原文:http://www.cnblogs.com/newlist/p/3595761.html
内容总结
以上是互联网集市为您收集整理的lua 工具类(二)全部内容,希望文章能够帮你解决lua 工具类(二)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。