lua常用操作
1 .Lua生成隨機數:
Lua 生成隨機數需要用到兩個函數:
math.randomseed(xx), math.random([n [, m]])
1. math.randomseed(n) 接收一個整數 n 作為隨機序列種子。
2. math.random([n [, m]]) 有三種用法: 無參調用, 產生 (0,1) 之間的浮點隨機數; 只有參數 n, 產生 1-n 之間的整數; 有兩個參數 n, m, 產生 n-m 之間的隨機整數
注:os.time() 返回的時間是秒級的, 不夠精確, 而 random() 還有個毛病就是如果 seed 很小或者seed 變化很小,產生的隨機序列很相似。
解決:把 time返回的數值字串倒過來(低位變高位), 再取高位6位。 這樣, 即使 time變化很小, 但是因為低位變了高位, 種子數值變化卻很大,就可以使偽隨機序列生成的更好一些。
?
2.?
-- 在棋盤范圍內,生成n個隨機位置(不重復) CHESSBOARD_MAX = 5*5 function GenRandomPos(n)local pos_list = {}local count = 0math.randomseed(tostring(os.time()):reverse():sub(1, 6)) while(count < n) do local v = math.random(1, CHESSBOARD_MAX)local flag = falsefor j,val in pairs(pos_list) do if val == v thenflag = truebreakendendif not flag thentable.insert(pos_list, v)count = count + 1endendreturn pos_list end?
3.?
-- 參數:待分割的字符串,分割字符 -- 返回:子串表.(含有空串) function LuaStringSplit(str, split_char)local sub_str_tab = {};while (true) dolocal pos = string.find(str, split_char);if (not pos) thensub_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?
4.
(1)
-- 返回當前日期數值 function GeTCurrDateMDY()local date_str = os.date("%x")local date_arr = LuaStringSplit(date_str, "/")local month, day, year = tonumber(date_arr[1]), tonumber(date_arr[2]), tonumber(date_arr[3])return month, day, year end?
(2)
local open_time_cnf = {{2, 2,}, -- month, day{4, 12,}, } -- 判斷當前日期是否在配置表的日期區間內(轉換成 時間戳 進行判斷) function IsInDateRange(_open_time_cnf)local today = os.date("*t")local curr_time = os.time({month = today.month, day = today.day, year = 2015,})local start_time = os.time({month = _open_time_cnf[1][1], day = _open_time_cnf[1][2], year = 2015,})local end_time = os.time({month = _open_time_cnf[2][1], day = _open_time_cnf[2][2], year = 2015,})print(start_time, curr_time, end_time)-- os.time的參數也可以是下面這種-- print(os.time({day=18, month=5, year=2012, hour=0, minute=0, second=0}))return (start_time <= curr_time and curr_time <= end_time) end print(IsInDateRange(open_time_cnf))?
?
5.
-- Lua 中刪除 table 元素 local test = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p' } local test_remove_flag = {}function DoSomething(_table)for k, v in pairs( _table ) do-- 一般我們不在循環中刪除,在循環中刪除會造成一些錯誤。這是可以建立一個remove表用來標記將要刪除的-- test_remove_flag[k] = (k % 2 == 0) and true or false-- print("------------" ,k, test_remove_flag[k])test_remove_flag[v] = (k % 2 == 0) and true or false-- dosomething-- v 為 列表項_table[k] copy值 end endDoSomething(test)-- 刪除標記為true的元素(從后往前刪除) -- table.remove操作后,后面的元素會往前移位,這時候后續的刪除索引對應的元素已經不是之前的索引對應的元素了 for i = #test, 1, -1 doif test_remove_flag[test[i]] thentable.remove(test, i)end endfor j = 1, #test doprint(test[j]) end
?
6. 有關lua全局變量的解析,請參見另一篇博客 lua全局變量和局部變量
-- tab不是一張lua表,或者表為空,則返回true;否則,返回false list = {"a", "b", "c", "d",} function IsTableEmpty(tab)-- tab不是一張表if type(tab) ~= 'table' then return true end-- _G.next(tab) 相當于調用全局next函數遍歷tab表的下一個元素return _G.next(tab) == nil end local flag = IsTableEmpty(list) print(flag) ------------------------------------------- -- false-- 所有全局變量都會存在_G里面,_G是一個table g_var = "global_var." -- 全局變量 print(g_var) print(_G.g_var) local l_var = "local_var." -- 局部變量 print(l_var) print(_G.l_var) --------------------------------------------- -- global_var. -- global_var. -- local_var. -- nil -- [Finished in 0.1s]7.?
?
CnfShopYouHui = {[4] = {name = "技能石",},[5] = {name = "強化石",},[6] = {name = "仙寵品階丹",},[1] = {name = "小花束",},[2] = {name = "大花束",},[3] = {name = "豪華花束",}, };local temp_cnf = CnfShopYouHuifor i, item in pairs(CnfShopYouHui) do print(" ------------ > ", i, item.name) end-- temp_cnf 是對CnfShopYouHui的一個引用,修改team_cnf會導致CnfShopYouHui也被修改 table.remove(temp_cnf, 1) print(" ********************************** ")for i, item in pairs(CnfShopYouHui) do print(" ------------ > ", i, item.name) end-- output------------ > 6 仙寵品階丹------------ > 2 大花束------------ > 3 豪華花束------------ > 1 小花束------------ > 4 技能石------------ > 5 強化石********************************** ------------ > 2 豪華花束------------ > 3 技能石------------ > 1 大花束------------ > 4 強化石------------ > 5 仙寵品階丹 [Finished in 0.1s]?
8.
?
CnfShopYouHui = {[4] = {name = "技能石",},[5] = {name = "強化石",},[6] = {name = "仙寵品階丹",},[1] = {name = "小花束",},[2] = {name = "大花束",},[3] = {name = "豪華花束",}, };for i, item in pairs(CnfShopYouHui) doif 1 == i then table.remove(CnfShopYouHui, 1)CnfShopYouHui[i] = nilend-- i, item 是CnfShopYouHui內容項的(值)復制,CnfShopYouHui[i]是內容項本身的(引用)-- 所以,雖然上面刪除了table.remove(CnfShopYouHui, 1), 但此時item已經復制了它的值。print(" ------------ > ", i, item.name, CnfShopYouHui[i]) end-- output------------ > 6 仙寵品階丹 table: 004FC270------------ > 2 大花束 table: 004FC310------------ > 3 豪華花束 table: 004FC360------------ > 1 小花束 nil------------ > 4 強化石 table: 004FC220------------ > 5 仙寵品階丹 table: 004FC270 [Finished in 0.1s]10.
?
--*************************************************-- -- 樹形打印table成員(table, variable, function ……) local tablePrinted = {} function printTableItem(k, v, tab)for i = 1, tab doio.write(" ") -- 縮進endio.write(tostring(k), " = ", tostring(v), "\n")if type(v) == "table" thenif not tablePrinted[v] thentablePrinted[v] = truefor k, v in pairs(v) do-- tab 非局部變量(Upvalue) printTableItem(k, v, tab + 1)endendend end--*************************************************---- lfs(Lua file system, lfs.dll 動態庫), 在lua的安裝目錄下就有此動態庫-- D:\5.1\clibs require "lfs" -- 打印當前文件路徑 print("-- lfs.currentdir() -------------------------------------------- ") print(lfs.currentdir())print("-- printTableItem lfs -------------------------------------------- ") -- 查看lfs.dll動態庫 成員 printTableItem("lfs", lfs, 0) -- -- 打印全局表_G -- -- printTableItem("_G", _G, 0)local file_name = "D:/tes.lua" -- D:\tes.lua (絕對路徑和相對路徑) local t = lfs.attributes(file_name) -- 取文件全部屬性 print("-- lfs.attributes D:/tes.lua -------------------------------------------- ") for k, data in pairs(t) doprint(tostring(k)) endprint("-- modify_time -------------------------------------------- ") local modify_time = lfs.attributes(file_name, "modification") -- 取文件一個屬性 print(tostring(modify_time))print(" END -------------------------------------------- ") -- output -- lfs.currentdir() -------------------------------------------- D:\ -- printTableItem lfs -------------------------------------------- lfs = table: 004EB518symlinkattributes = function: 004ECF28dir = function: 004ECE28_VERSION = LuaFileSystem 1.4.2setmode = function: 004ECF48unlock = function: 004ECFC8_DESCRIPTION = LuaFileSystem is a Lua library developed to complement the set of functions related to file systems offered by the standard Lua distributioncurrentdir = function: 004ECE08_COPYRIGHT = Copyright (C) 2003 Kepler Projectattributes = function: 004ECDA8lock = function: 004ECE68touch = function: 004ECF88mkdir = function: 004ECEA8chdir = function: 004ECDC8rmdir = function: 004ECEE8 -- lfs.attributes D:/tes.lua -------------------------------------------- dev change access rdev nlink uid gid ino mode modification size -- modify_time -------------------------------------------- 1426498014END -------------------------------------------- [Finished in 0.2s]?
11. lua腳本熱加載
(1)首先在D:\路徑下創建以下三個文件:
-- D:\add.luafunction add_func()local x, y = 12, 32print(">>>>>>>>>>>>>>add_func(12, 32):x+y = " .. tostring(x+y)) end add_func() -- D:\dive.luafunction dive_func()local x, y = 12, 3print(">>>>>>>>>>>>>>dive_func(12, 3):x / y = " .. tostring(x/y)) end dive_func() -- D:\hotreload.lua--*************************************************-- SCRIPTLIST = {"add","dive", } ----[[ -- 實現lua腳本的熱加載 pre_modify_time = 0 -- 模擬原始改變時間 function HotReload(name_str)if name_str thenlocal module_name = name_strprint(" >>>>>>>>>>>>>> name_str", name_str)package.loaded[module_name] = nilrequire(module_name)elserequire "lfs"print(lfs.currentdir()) -- D:\for _, module_name in pairs(SCRIPTLIST) dolocal file_name = lfs.currentdir() .. module_name .. ".lua"local modify_time = lfs.attributes(file_name, "modification")print("file_name, pre_modify_time, modify_time", file_name, pre_modify_time, modify_time)if modify_time > pre_modify_time thenpackage.loaded[module_name] = nilrequire(module_name)endendend end --]] HotReload()(2)執行hotreload.lua文件,輸出如下:
D:\ file_name, pre_modify_time, modify_time D:\add.lua 0 1426502029 >>>>>>>>>>>>>>add_func(12, 32):x+y = 44 file_name, pre_modify_time, modify_time D:\dive.lua 0 1426502032 >>>>>>>>>>>>>>dive_func(12, 3):x / y = 4 [Finished in 0.2s]12.
-- lua賦值操作中,如果賦值table是采用引用方式賦值;(userdata等類型還未檢驗) -- 如果賦值常規變量(string,number,...等類型)則采用值傳遞方式賦值。 local a, b = 31, 42 local copy_a = a local change_b = b change_b = change_b + 1 print(" ---------------- a, copy_a = ", a, copy_a) print(" ---------------- b, change_b = ", b, change_b)local str = "test_str" local change_str = str change_str = change_str .. "_add_str" print(" ---------------- str, change_str = ", str, change_str)-- table local t = {"a", "b", "d", "e",} local change_t = t table.remove(change_t, 1) for i, v in pairs(t) doprint(" -------------- ", v) end-- function local add = function(x, y)print(" ----------- add(x, y) = ", x + y) end local dive = add dive = function(x, y)print(" ----------- dive(x, y) = ", x/y) end add(12, 3) dive(12, 3)-- output
---------------- a, copy_a = 31 31---------------- b, change_b = 42 43---------------- str, change_str = test_str test_str_add_str-------------- b-------------- d-------------- e----------- add(x, y) = 15----------- dive(x, y) = 4 [Finished in 0.1s]?
13.
?
local test_str = "my_test_str" local testt = { list = {"a", "b", "c", "d",list_1 = {"e", "f", "g",},},limit_value=31,limit_type=1,list_t = list,list_tt = testt,list_ttt = limit_value,list_tttt = test_str, } print(" >>>>>>>>>>>>>>>>> testt.list_ttt, testt.limit_value, testt.list_tttt = ", testt.list_ttt, testt.limit_value, testt.list_tttt) -- 注:由于在表testt內定義list_ttt的時候,表testt還沒定義結束,此時limit_value為nil,所以list_ttt輸出為nil; -- 而test_str在表testt之前定義完成,所以可以在表testt內對字段list_tttt賦值; -- 同時,當打印testt.limit_value時,表testt和表內字段都已經定義完成。 --------------------------------------------------------------------------- ipairs 和 pairs 的lua的table遍歷的區別 print(" >>>>>>>>>>>>>>>>> ipairs") for j, item in ipairs(testt) doprint(j) end print(" >>>>>>>>>>>>>>>>> pairs") for j, item in pairs(testt) doprint(j) end-- 取表長度# 原理和 (i)pairs 一樣,table.sort 也類似,等等。 print(" ---------------- #testt", tostring(#testt)) -- lua中取table長度操作(#table_name)是基于Array的table local list_l = {"a", "b", "c", "d",} print(" ---------------- #list_l", tostring(#list_l)) --------------------------------------------------------------------------- foreach遍歷整張table, #list_k只打印符合array(以 1 開始的連續整數作為key的table)的連續下標的值 local list_k = {aa = "a", bb = "b", [2] = "c", [3] = "d", [4] = "e", [5] = "f",} local list_k_2 = {aa = "a", bb = "b", "c", "d", [4] = "e", [5] = "f",} table.foreach(list_k, function(i, v)print(" ---------------- i, v = ", i, v)end) print(" ---------------- #list_k = ", tostring(#list_k)) print(" ---------------- #list_k_2 = ", tostring(#list_k_2))-- output
>>>>>>>>>>>>>>>>> testt.list_ttt, testt.limit_value, testt.list_tttt = nil 31 my_test_str>>>>>>>>>>>>>>>>> ipairs>>>>>>>>>>>>>>>>> pairs limit_value list list_tttt limit_type---------------- #testt 0---------------- #list_l 4---------------- i, v = 2 c---------------- i, v = aa a---------------- i, v = 3 d---------------- i, v = 4 e---------------- i, v = 5 f---------------- i, v = bb b---------------- #list_k = 0---------------- #list_k_2 = 2 [Finished in 0.1s]
14.
?
function table.isArray(tab)if not tab thenreturn falseendlocal ret = truelocal idx = 1for f, v in pairs(tab) doif type(f) == "number" thenif f ~= idx thenret = falseendelseret = falseendif not ret then break endidx = idx + 1endreturn ret end-- table序列化 serialize --序列化一個Table function serialize(t)local assign={}local function table2str(t, parent)local ret = {}if table.isArray(t) thentable.foreach(t, function(i, v)local k = tostring(i)local dotkey = parent.."["..k.."]"local t = type(v)if t == "userdata" or t == "function" or t == "thread" or t == "proto" or t == "upval" then--ignoreelseif t == "table" thentable.insert(ret, table2str(v, dotkey))elseif t == "string" thentable.insert(ret, string.format("%q", v))elseif t == "number" thenif v == math.huge thentable.insert(ret, "math.huge")elseif v == -math.huge thentable.insert(ret, "-math.huge")elsetable.insert(ret, tostring(v))endelsetable.insert(ret, tostring(v))endend)else table.foreach(t, function(f, v)local k = type(f)=="number" and "["..f.."]" or flocal dotkey = parent..(type(f)=="number" and k or "."..k)local t = type(v)if t == "userdata" or t == "function" or t == "thread" or t == "proto" or t == "upval" then--ignoreelseif t == "table" thentable.insert(ret, string.format("%s=%s", k, table2str(v, dotkey)))elseif t == "string" thentable.insert(ret, string.format("%s=%q", k, v))elseif t == "number" thenif v == math.huge thentable.insert(ret, string.format("%s=%s", k, "math.huge"))elseif v == -math.huge thentable.insert(ret, string.format("%s=%s", k, "-math.huge"))elsetable.insert(ret, string.format("%s=%s", k, tostring(v)))endelsetable.insert(ret, string.format("%s=%s", k, tostring(v)))endend)end-- table.concat 遍歷ret并使用","分隔元素return "{"..table.concat(ret,",").."}"endif type(t) == "table" then -- 調用table2str入口return string.format("%s", table2str(t,"_"))elsereturn tostring(t)end end local testt = { limit_value=31,limit_type=1,list = {"a", "b", "c", "d",list_1 = {"e", "f", "g",}, list_2 = testt,},my_list_1 = {"111", "222", "333", "4444", "555",}, } print(serialize(testt))-- output
{limit_value=31,my_list_1={"111","222","333","4444","555"},list={[1]="a",[2]="b",[3]="c",[4]="d",list_1={"e","f","g"}},limit_type=1} [Finished in 0.2s]?15.
GameConfig = {} GameConfig.ResCompose = {} GameConfig.ResCompose.Effects_E612 = {Path = "resource/language/gt/effects/e612.png",ScaleSize = 0.5,FrameInterval = 0.125,[1] = { 1494, 0, 228, 151, 3, 4, },[2] = { 660, 0, 284, 244, 1, -85, },[3] = { 336, 0, 323, 249, 0, -82, },-- [4] = { 0, 0, 335, 250, 2, -81, }, [5] = { 1226, 0, 267, 240, -2, -91, },[6] = { 945, 0, 280, 242, -3, -87, }, } print(" >>>>>>>>>>>>>>>>>>>>> 1") -- table.getn(table_name) 獲取table_name中連續id的元素個數 print(table.getn(GameConfig.ResCompose.Effects_E612)) -- 3 print(" >>>>>>>>>>>>>>>>>>>>> 2")?16.文件操作
-- 打開文件讀取 function OpenFile(path)local content = ""local file = io.open(path, "r")if (not file) then-- 打開失敗return nilendfor line in file:lines() docontent = content .. line .. "\n"endfile:close(path)return content-- 寫入文件-- local file = io.open(path, "w")-- file:write(content)-- file:close() end -- 調用 -- local str = OpenFile("luafiletest.txt")-- 重命名文件 function ChangeFileName(path)local status = ""local file = io.open(path, "r")file:close(path) -- 關閉之后才能重命名local status = os.rename(path, path..".bak")if (not status) then-- 重命名失敗returnendreturn status end -- local status = ChangeFileName("luafiletest.txt")?17.字符串和數字比較
18.
-- 將字符串轉成table function stringToTable(str) local ret = loadstring("return "..str)() return ret end str = "{1}, print('run print')" local test = stringToTable(str) for i, v in pairs(test) doprint(i, v) endlocal str_s = "print('test print')" print(str_s)?
轉載于:https://www.cnblogs.com/yyxt/p/4180596.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
- 上一篇: 不同的jar里边相同的包名类名怎么区别导
- 下一篇: 习惯 积累 沉淀