使用lua Cjson實現登陸註冊(三)

博主在上上篇博客中寫了登陸註冊,但只是用Io流存儲到本地文件,那麼這次就實現把賬戶對象的錶轉成Cjson字符串儲存到本地,貼出源碼:

註冊

--註冊按鈕
function RegisterCtrl.SureRegisterButton(obj)
	--所有的用戶信息
	local AllUserDataList={}
	--是否有相同賬號
	local boolean isoverFind=false
	if(RegisterPanel.RegAccountInputField:GetComponent("Text").text=="" or RegisterPanel.RegPsaaWordInputField:GetComponent("Text").text=="") 
		then
		RegisterPanel.text:GetComponent("Text").text="賬號密碼不能爲空!"
		else 

			local datafile=io.open("D:\\Alluserdata.txt","w+")
			local userdataJsonString=datafile:read("*a")
			datafile.close()
			--解析json
			if(#userdataJsonString>0)then
				--把JSon轉成對象列表
				local userdataList= cjson.decode(userdataJsonString)
				for k,v in pairs(userdataList) do
				--把上次用戶的信息寫進表裏(爲了以個JSON字符串儲存所有用戶信息)
				table.insert(AllUserDataList,userdataList[k])
				--如果賬號相同
				if(RegisterPanel.RegAccountInputField:GetComponent("Text").text==userdataList[k].Account)then
					--有相同用戶名  註冊失敗
					isoverFind=false
					break
				else
					isoverFind=true	
					end
				end
			end
			if(isoverFind==true or #userdataJsonString==0) then--註冊成功
             --註冊成功  開始記錄賬號密碼
			 currentUserData={Account=RegisterPanel.RegAccountInputField:GetComponent("Text").text,PassWord=RegisterPanel.RegPsaaWordInputField:GetComponent("Text").text}
			--把對象寫入列表
			table.insert(AllUserDataList,currentUserData)
			--把儲存所有用戶信息的表 轉成Json字符串 等待其他地方解析使用
			AlluserCjsonString=cjson.encode(AllUserDataList)
			--把JSON字符串以io形式儲存到本地
			local alldatafile=io.open("D:\\Alluserdata.txt","w")
			--把json字符串寫入文件
			alldatafile:write(AlluserCjsonString)
			--關閉文件
			alldatafile:close()
			RegisterPanel.text:GetComponent("Text").text="註冊成功!"
			else
			RegisterPanel.text:GetComponent("Text").text="註冊失敗!"
			end
		end
end 

登陸

function LoginCtrl.ButtonClick(obj)

	--賬戶是否正確
	local boolean Accountifcorrectbool=false
	if(LoginPanel.AccountInputFild:GetComponent("Text").text=="" or LoginPanel.PassWordInputFild:GetComponent("Text").text=="") 
		then
		LoginPanel.text:GetComponent("Text").text="賬號密碼不能爲空!"
		else 
			--打開本地文件
		 	local AlluserDatafile =io.open("D:\\Alluserdata.txt","a+");
		 	--讀取json字符串
		 	local alluserdataString =AlluserDatafile:read("*a")
		 	AlluserDatafile:close()
			--如果字符串不爲空
			if(#alluserdataString>0)then
				--把儲存賬號密碼的json字符串錶轉成對象
				local alluserdatalist= cjson.decode(alluserdataString)
			    logWarn("JSon="..alluserdataString)
			    for k,v in pairs(alluserdatalist) do
			    --如果賬號密碼都正確
				if(LoginPanel.AccountInputFild:GetComponent("Text").text==alluserdatalist[k].Account and LoginPanel.PassWordInputFild:GetComponent("Text").text==alluserdatalist[k].PassWord)
				then 
				logWarn("登陸成功!")
				--準備跳轉界面
		    	Tootil.LogionPnaelGb:SetActive(false)
		    	Tootil.GamePanelGb:SetActive(true)
				else
					LoginPanel.text:GetComponent("Text").text="該賬號或密碼有誤!"	
				end
			   end
			else
					LoginPanel.text:GetComponent("Text").text="請前往註冊賬號!"	
			end
		end
end		
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章