提交 cbc2af29 编写于 作者: L linxinfa

优化Lua脚本

上级 b513366a
-- 调用 LuaFramework.NetworkManager.AddLuaProcessS2C(tag, flag) 增加lua 的网络回调处理
-- tag:proto定义的标记 | flag 0:只C#层处理(不需要添加),2:lua C#共同处理 3:只lua 处理
-- (如果需要改变方法名称可以在初始化的时候调用LuaFramework.NetworkManager.SetOnRequestDataFun / SetOnResponseDataFun)
......@@ -7,40 +6,37 @@
require "Common/define"
require "Common/protocal"
require "Common/functions"
Event = require 'events'
Event = require "events"
local sproto = require "3rd/sproto/sproto"
local core = require "sproto.core"
local print_r = require "3rd/sproto/print_r"
Network = Network or { }
Network = Network or {}
local this = Network
local c2s_proto
local s2c_proto
local c2s_host
local s2c_host
-- 注:CsNetworkMgr在define中定义了,就是C#的NetworkManager对象
local networkMgr = CsNetworkMgr
-- 处理标记
NetProcessFlag =
{
Default = 0,
NetProcessFlag = {
-- 在C#层处理(不需要添加)
Common = 1,
Default = 0,
-- c# lua 共同处理
Lua = 2-- 只lua层处理
Common = 1,
-- 只lua层处理
Lua = 2
}
local NetProcessFlag = NetProcessFlag
local NetStateEnum =
{
local NetStateEnum = {
ConnectStart = 0,
ConnectSuccess = 1,
ConnectFail = 2,
......@@ -48,22 +44,19 @@ local NetStateEnum =
ResendStart = 4,
ResendSuccess = 5,
ResendFail = 6,
Error = 7,
Error = 7
}
local c2sProcess = c2sProcessTab
local s2cProcessTab = s2cProcessTab
-- 动态添加的处理方法
local exts2cProcessTab = { }
local extc2sProcessTab = { }
local exts2cProcessTab = {}
local extc2sProcessTab = {}
-- 断线重连成功后需要重新发送的协议
-- (有些请求在断线时候客户的点击UI发送过去,等待服务器返回,然后界面会处于不可点击所以重连成功后需要主动在发一次)
local resend_in_reconnect_proto =
{
}
local resend_in_reconnect_proto = {}
this.sessionHandlers = {}
......@@ -87,8 +80,6 @@ function Network.OnInit()
logError("Network.OnInit proto/s2c.sproto is not exist ")
end
-- LuaUtil.PrintTable(s2cProcessTab)
-- 添加网络处理
-- networkMgr.AddLuaProcessS2C(1, NetProcessFlag.Lua)
-- networkMgr.AddLuaProcessC2S(1, 2)
......@@ -113,7 +104,7 @@ function Network.OnInit()
end
end
this.resend_proto_tab = { }
this.resend_proto_tab = {}
for k, v in pairs(resend_in_reconnect_proto) do
local c2s_process_info = c2sProcessTab[k]
if c2s_process_info ~= nil then
......@@ -128,20 +119,15 @@ function Network.OnInit()
logError("Network.OnInit resend_in_reconnect_proto key " .. k .. " not exist!!!")
end
end
-- LuaUtil.PrintTable(resend_in_reconnect_proto)
-- LuaUtil.PrintTable(this.resend_proto_tab)
-- 发送请求的缓存tab 主要是断线重连时候恢复重新发送的逻辑
this.req_cache_tab = { }
this.req_cache_tab = {}
this.sessionHandlers = {}
end
-- 收到服务器请求处理
function Network.OnRequestDataFun(buffer, length)
-- log("Network.OnRequestDataFun--------")
local type, protoname, request = s2c_host:dispatch_nopacked(buffer, length)
-- log("-----------Network.OnRequestDataFun-----------"..protoname)
-- LuaUtil.PrintTable(request)
local protoProcessTab = s2cProcessTab[protoname]
-- LuaUtil.PrintTable(protoProcessTab)
......@@ -166,7 +152,6 @@ end
-- 收到服务器响应处理
function Network.OnResponseDataFun(buffer, length, protoname)
-- log("Network.OnResponseDataFun--------"..protoname)
if protoname == nil then
logWarn("Network.OnResponseDataFun protoname is nil ....")
return true
......@@ -175,7 +160,7 @@ function Network.OnResponseDataFun(buffer, length, protoname)
local type, session, response = c2s_host:dispatch_nopacked(buffer, length, protoname)
this.req_cache_tab[session] = nil
local handler = this.sessionHandlers[session]
if handler then
local ret = handler(response)
......@@ -183,9 +168,7 @@ function Network.OnResponseDataFun(buffer, length, protoname)
return
end
local protoProcessTab = c2sProcessTab[protoname]
-- LuaUtil.PrintTable(protoProcessTab)
if protoProcessTab ~= nil then
if protoProcessTab[2] ~= nil then
local ret = protoProcessTab[2](session, response)
......@@ -203,18 +186,14 @@ function Network.OnResponseDataFun(buffer, length, protoname)
end
end
end
end
-- lua发送消息接口, protoname:协议名称, prototab:协议内容 lua table
function Network.SendData(protoname, prototab, handler)
local p = c2s_proto:findproto(protoname)
if p ~= nil then
if prototab == nil then
-- logWarn("Network.SendData prototab is nil ....")
prototab = { }
prototab = {}
end
local session = networkMgr.GetNextSession()
local v = c2s_host:gen_request(p.request, p.tag, session, prototab)
......@@ -222,7 +201,7 @@ function Network.SendData(protoname, prototab, handler)
networkMgr.SendData(protoname, session, p.tag, v)
-- 加入缓存
if this.resend_proto_tab[p.tag] ~= nil then
this.req_cache_tab[session] = { [1] = protoname, [2] = session, [3] = p.tag, [4] = v, [5] = prototab }
this.req_cache_tab[session] = {[1] = protoname, [2] = session, [3] = p.tag, [4] = v, [5] = prototab}
end
if handler then
this.sessionHandlers[session] = handler
......@@ -233,17 +212,15 @@ function Network.SendData(protoname, prototab, handler)
else
logError("Network.SendData p is nil tag = " .. p.tag .. " protoname = " .. protoname)
end
end
-- 在断线重连的时候重发数据
-- 在断线重连的时候重发数据
function Network.ResendCacheDataOnReconnect()
local temp_tab = this.req_cache_tab
-- this.req_cache_tab = {}
local cnt = 0
for k, v in pairs(temp_tab) do
-- 重发
-- networkMgr.SendData(v[1], v[2], v[3], v[4])
if v ~= nil then
log("ResendCacheDataOnReconnect " .. v[1])
-- TODO:此处用了同一个session所以需要在C#里面重写一个 ReSend方法,否则会重复添加sessioin爆错, 暂时不能改...
......@@ -259,7 +236,6 @@ function Network.ResendCacheDataOnReconnect()
end
end
-- 网络状态改变
function Network.OnNetStateChanged(state, param)
-- log("--------------Network.OnNetStateChanged-----------"..state:ToInt())
......@@ -328,16 +304,15 @@ function Network.RemoveAllExtProcess()
networkMgr.RemoveLuaProcessS2C(p.tag)
end
end
extc2sProcessTab = { }
exts2cProcessTab = { }
extc2sProcessTab = {}
exts2cProcessTab = {}
end
function Network.SetNetProcess(bProcessMsg, mode)
LuaFramework.NetworkManager.SetNetProcess(bProcessMsg, mode)
end
-- 卸载网络监听--
function Network.Unload()
logWarn('Unload Network...');
end
\ No newline at end of file
logWarn("Unload Network...")
end
--region *.lua
--Date
--此文件由[BabeLua]插件自动生成
--lua 的一些功能测试方法
--验证一些方法的正确性
--为某些逻辑模块提供测试数据
local json = require 'cjson'
LuaTest = LuaTest or {}
local this = LuaTest
function LuaTest.OnBeginFun(fun_name)
log("---------------------begin "..fun_name.."-----------------------")
end
function LuaTest.OnEndFun(fun_name)
log("---------------------end "..fun_name.."-----------------------")
end
function LuaTest.Assert(result)
if result == 0 then
logError("Assert failed..")
else
end
end
function LuaTest.Print(...)
if ... ~= nil then
local args = {...}
local output_str = ""
for k, v in pairs(args) do
output_str = output_str.." "..v
end
log(output_str)
end
end
--基础方法 不依赖其他
function LuaTest.TestBaseFun()
this.LuaUtil_GetTimeHMS()
this.LuaUtil_GetTodaySec()
end
------------------------------------------LuaUtil--------------------------------------
--测试 LuaUtil的GetTimeHMS方法
function LuaTest.LuaUtil_GetTimeHMS()
this.OnBeginFun("LuaUtil_GetTimeHMS")
local sec = 0
local h, m, s = LuaUtil.GetTimeHMS(sec)
this.Assert(h == 0)
this.Assert(m == 0)
this.Assert(s == 0)
sec = 3600
local h, m, s = LuaUtil.GetTimeHMS(sec)
this.Assert(h == 1)
this.Assert(m == 0)
this.Assert(s == 0)
sec = 3661
local h, m, s = LuaUtil.GetTimeHMS(sec)
this.Assert(h == 1)
this.Assert(m == 1)
this.Assert(s == 1)
this.OnEndFun("LuaUtil_GetTimeHMS")
end
function LuaTest.LuaUtil_GetTodaySec()
this.OnBeginFun("LuaUtil_GetTodaySec")
local sec = LuaUtil.GetTodaySec()
this.Print(sec)
local h, m, s = LuaUtil.GetTimeHMS(sec)
this.Print(h, m, s)
this.OnEndFun("LuaUtil_GetTodaySec")
end
------------------------------------------PlayerManager--------------------------------------
function LuaTest.PlayerManager_OnPlayerConsume()
this.OnBeginFun("PlayerManager_OnPlayerConsume")
--local pre_item_60005 = BackPackMgr.getServerNumberById(60005)
--6005 青铜核弹头
local joson_data = '[{"props":[{"id":60005,"quantity":1}]},{"gold":200000}]';
local cost_tab = json.decode(joson_data)
LuaUtil.PrintTable(cost_tab)
PlayerManager.OnPlayerConsume(cost_tab)
this.OnEndFun("PlayerManager_OnPlayerConsume")
end
function LuaTest.PlayerManager_OnPlayerConsumeTab()
this.OnBeginFun("PlayerManager_OnPlayerConsumeTab")
local joson_data = '{"gold":1000, "props":[{"id":60005,"quantity":1}]}'
local cost_tab = json.decode(joson_data)
PlayerManager.OnPlayerConsumeByTab(cost_tab)
this.OnEndFun("PlayerManager_OnPlayerConsumeTab")
end
--endregion
fileFormatVersion: 2
guid: 98b52718bbb11e440b744c1c29a47324
timeCreated: 1481162053
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
......@@ -4,7 +4,7 @@
-- 由于tolua重写了__index方法, 所以不能直接扩展 LuaFramework.Util 只能用名称LuaUtil
LuaUtil = LuaUtil or { }
LuaUtil = LuaUtil or {}
local ONE_HOUR_SEC = 3600
-- 一天的秒数
......@@ -21,7 +21,6 @@ LuaUtil.TWO_WEEKS_SEC = TWO_WEEKS_SEC
local EventDispatcher = EventDispatcher.instance
function LuaUtil.RegistEvent(eventName, handle)
-- 使用Unity导出的GameWorld事件处理器
EventDispatcher:Regist(eventName, handle)
end
......@@ -30,14 +29,14 @@ function LuaUtil.UnRegistEvent(eventName, handle)
end
function LuaUtil.FireEvent(eventName, ...)
-- log("LuaUtil.FireEvent: " .. eventName)
EventDispatcher:DispatchEvent(eventName, ...)
end
-- 获取table长度
function LuaUtil.TableCount(t)
if nil == t then return 0 end
if nil == t then
return 0
end
local cnt = 0
for _ in pairs(t) do
......@@ -61,10 +60,7 @@ local function PrintTable2(o, f, b, deep)
end
p = f or io.write
b = b or false
if type(o) == "number" or
type(o) == "function" or
type(o) == "boolean" or
type(o) == "nil" then
if type(o) == "number" or type(o) == "function" or type(o) == "boolean" or type(o) == "nil" then
p(tostring(o))
elseif type(o) == "string" then
p(string.format("%q", o))
......@@ -92,24 +88,32 @@ end
-- 打印一个lua表 用于调试输出
function LuaUtil.PrintTable(t)
local printTabStr = "";
PrintTable2(t, function(str) printTabStr = printTabStr .. str end, true, 0)
local printTabStr = ""
PrintTable2(
t,
function(str)
printTabStr = printTabStr .. str
end,
true,
0
)
if printTabStr == "" then
logError("LuaUtil.PrintTable printTabStr is nil")
end
log(printTabStr)
end
function LuaUtil.strToDate(s, sTime)
local t = { }
local t = {}
if sTime then
t.year, t.month, t.day = s:match("(%d+)-(%d+)-(%d+)")
t.hour, t.min, t.sec = sTime:match("(%d+):(%d+):(%d+)")
else
t.year, t.month, t.day, t.hour, t.min, t.sec = s:match("(%d+)-(%d+)-(%d+)%s+(%d+):(%d+):(%d+)")
end
for k, v in pairs(t) do t[k] = tonumber(v) end
for k, v in pairs(t) do
t[k] = tonumber(v)
end
return t
end
......@@ -123,7 +127,8 @@ end
function LuaUtil.getTodayTimestamp(clock, nowTime)
local nowTab = os.date("*t", nowTime)
local _, _, hour, min, sec = string.find(clock, "(%d+):(%d+):(%d+)")
local timestamp = os.time {
local timestamp =
os.time {
year = nowTab.year,
month = nowTab.month,
day = nowTab.day,
......@@ -134,11 +139,12 @@ function LuaUtil.getTodayTimestamp(clock, nowTime)
return timestamp
end
-- 通过距零点的秒数获取时间戳
function LuaUtil.GetTodayTimestampBySec(sec)
local H, M, S = LuaUtil.GetTimeHMS(sec)
local nowTab = os.date("*t", os.time())
local timestamp = os.time { year = nowTab.year, month = nowTab.month, day = nowTab.day, hour = H, min = M, sec = S }
local timestamp = os.time {year = nowTab.year, month = nowTab.month, day = nowTab.day, hour = H, min = M, sec = S}
return timestamp
end
......@@ -146,14 +152,9 @@ end
-- 将秒数转换为 小时, 分, 秒(只限于一天)
function LuaUtil.GetTimeHMS(sec)
local H = math.floor(sec / ONE_HOUR_SEC)
local L = sec -(H * ONE_HOUR_SEC)
local L = sec - (H * ONE_HOUR_SEC)
local M = math.floor(L / 60)
local S = L -(M * 60)
-- local H, L = math.modf(sec / ONE_HOUR_SEC)
-- local M, S = math.modf(L * 60)
-- S = math.floor(S * 60)
local S = L - (M * 60)
return H, M, S
end
......@@ -174,12 +175,11 @@ function LuaUtil.GetFormatTime(sec)
return str
end
-- 获取今天的秒数(相对于0点)
function LuaUtil.GetTodaySec()
local cur_time = os.time()
local nowTab = os.date("*t", os.time())
local zero_time = os.time { year = nowTab.year, month = nowTab.month, day = nowTab.day, hour = 0, min = 0, sec = 0 }
local zero_time = os.time {year = nowTab.year, month = nowTab.month, day = nowTab.day, hour = 0, min = 0, sec = 0}
return cur_time - zero_time
end
......@@ -205,47 +205,11 @@ function LuaUtil.Second2DateTable(second)
return os.date("*t", math.floor(second))
end
-- 显示奖励 name:配置表的名称 objTemplate:使用的GameObject 模板 v:数量 或者道具信息
-- function LuaUtil.ShowAward(name, objTemplate, v)
-- if name == "diamond" then
-- local cellInfo = ItemCellInfo.New()
-- cellInfo.rewardType = RewardType.diamond--RewardType.gold
-- cellInfo.num = v
-- --cellInfo.ItemType = RewardType.propItems
-- ItemCellOperate.ShowItemCell(cellInfo, objTemplate)
-- elseif name == "gold" then
-- local cellInfo = ItemCellInfo.New()
-- cellInfo.rewardType = RewardType.gold
-- cellInfo.num = v
-- ItemCellOperate.ShowItemCell(cellInfo, objTemplate)
-- elseif name == "pt" then
-- local cellInfo = ItemCellInfo.New()
-- cellInfo.rewardType = RewardType.pt
-- cellInfo.num = v
-- ItemCellOperate.ShowItemCell(cellInfo, objTemplate)
-- elseif name == "props" then
-- --道具
-- for k1, v1 in pairs(v) do
-- local cellInfo = ItemCellInfo.New()
-- cellInfo.rewardType = RewardType.propItems
-- cellInfo.ItemType = v.id
-- cellInfo.num = v.quantity
-- ItemCellOperate.ShowItemCell(cellInfo, objTemplate)
-- end
-- else
-- logError("LuaUtil.ShowAward not process award type "..name)
-- end
-- end
-- utils for string
function LuaUtil.SplitString(fullString, separator)
local startIndex = 1
local splitIndex = 1
local splitArray = { }
local splitArray = {}
if not fullString or not separator or string.len(fullString) == 0 then
return splitArray
end
......@@ -263,7 +227,7 @@ function LuaUtil.SplitString(fullString, separator)
end
function LuaUtil.StringToNumberList(fromString, separator)
local retList = { }
local retList = {}
if fromString ~= nil and string.len(fromString) > 0 then
local tempTable = LuaUtil.SplitString(fromString, separator)
for k, v in pairs(tempTable) do
......@@ -276,7 +240,6 @@ function LuaUtil.StringToNumberList(fromString, separator)
end
-- end of utils for string
function LuaUtil.ToNumber(strContent)
local ret = 0
if strContent then
......@@ -292,8 +255,6 @@ function LuaUtil.IsStrNullOrEmpty(str)
return false
end
function LuaUtil.GetTableValue(prototab, key, default)
if nil ~= prototab[key] then
return prototab[key]
......@@ -304,16 +265,20 @@ end
-- utf8字符串截取
function LuaUtil.sub_chars(s, len)
local ss = { }
local ss = {}
if len > #s then
return s
end
local k = 1
while true do
len = len - 1
if len < 0 then break end
if len < 0 then
break
end
local c = string.byte(s, k)
if not c then break end
if not c then
break
end
if c < 192 then
table.insert(ss, string.char(c))
k = k + 1
......@@ -362,8 +327,6 @@ function LuaUtil.sub_chars(s, len)
return table.concat(ss)
end
--[[ 分割字符串 ]]
function LuaUtil.StringSplit(origin_str, separator)
-- origin_str = "2"
......@@ -371,7 +334,7 @@ function LuaUtil.StringSplit(origin_str, separator)
-- origin_str = "2,3,4,5,6,7,8,9"
local mFindStartIndex = 1
local mSplitIndex = 1
local mSplitArray = { }
local mSplitArray = {}
while true do
local mFindLastIndex = string.find(origin_str, separator, mFindStartIndex)
if mFindLastIndex == nil then
......@@ -388,39 +351,35 @@ function LuaUtil.StringSplit(origin_str, separator)
return mSplitArray
end
-- 将秒转为日、时、分、秒
function LuaUtil.GetTimeDHMS(sec)
local D = math.floor(sec / ONE_DAY_SEC)
local leftHour = sec - D * ONE_DAY_SEC
local H = math.floor(leftHour / ONE_HOUR_SEC)
local L = leftHour -(H * ONE_HOUR_SEC)
local L = leftHour - (H * ONE_HOUR_SEC)
local M = math.floor(L / 60)
local S = L -(M * 60)
local S = L - (M * 60)
return D, H, M, S
end
-- 调整panel的层
function LuaUtil.AdjustPanelDepth(panel, depth)
if depth == nil then
depth = UIPanel.nextUnusedDepth
local panel_ui = panel:GetComponent(typeof(UIPanel))
if panel_ui == nil then
log("can not find uipanel")
return
end
depth = depth - panel_ui.depth
end
UnityUtils.AdjustPanelDepth(panel, depth)
end
-- 判空
function LuaUtil.IsNilOrNull(obj)
return nil == obj or null == obj
end
-- 安全销毁
function LuaUtil.SafeDestroyObj(obj)
if not LuaUtil.IsNilOrNull(obj) then
GameObject.Destroy(obj.gameObject)
return
end
GameObject.Destroy(obj.gameObject)
end
-- 安全激活或禁用
function LuaUtil.SafeActiveObj(obj, active)
if not LuaUtil.IsNilOrNull(obj) then
return
end
obj.gameObject:SetActive(active)
end
-- endregion
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册