content
stringlengths
5
1.05M
util.AddNetworkString('ChangeCamera') util.AddNetworkString('ChangeFollowCamera') util.AddNetworkString('RemoveCamera') hook.Add('OnChangeCamTrigger', 'ChangeCamera', function() local activator, caller = ACTIVATOR, CALLER local trigger_postfix = '_TRIGGER' local camName = caller:GetName() camName = string.sub( camName, 1, string.find(camName, trigger_postfix, 1, true) - 1 ) print(camName) local cameras = ents.FindByName(camName) local camera = nil; if ( !table.IsEmpty(cameras) ) then camera = cameras[1] end net.Start('ChangeCamera') net.WriteVector(camera:EyePos()) net.WriteAngle(camera:EyeAngles()) net.Send(activator) end ) hook.Add('OnChangeFollowCamTrigger', 'ChangeFollowCamera', function() local activator, caller = ACTIVATOR, CALLER local trigger_postfix = '_FOLLOWTRIGGER' local camName = caller:GetName() camName = string.sub( camName, 1, string.find(camName, trigger_postfix, 1, true) - 1 ) print(camName) local cameras = ents.FindByName(camName) local camera = nil; if ( !table.IsEmpty(cameras) ) then camera = cameras[1] end net.Start('ChangeFollowCamera') net.WriteVector(camera:EyePos()) net.Send(activator) end ) hook.Add('OnRemoveCamTrigger', 'RemoveCamera', function() local activator = ACTIVATOR net.Start('RemoveCamera') net.Send(activator) end )
local g = vim.g local cmd = vim.cmd g.dart_format_on_save = 1 g.dart_style_guide = 2
object_static_structure_dathomir_static_undead_liver = object_static_structure_dathomir_shared_static_undead_liver:new { } ObjectTemplates:addTemplate(object_static_structure_dathomir_static_undead_liver, "object/static/structure/dathomir/static_undead_liver.iff")
local cjson = require "cjson" local dbbase = require "db.base_db" local reqArgs = require "common.request_args" local redis = require "redis.zs_redis" local systemConf = require "common.systemconfig" local resty_md5 = require "resty.md5" local str = require "resty.string" local uuid = require 'resty.jit-uuid' local http = require "resty.http" local respone = require "common.api_data_help" local httpc = http:new() local red = redis:new() local userDbOp = userDb:new(); --[[微信登录--]] local function wechatlogin(loginparm) -- body end local currentRequestArgs = reqArgs.new() local args = currentRequestArgs.getArgs() --登录方式 -- local logintype = args["logintype"] -- ngx.say(zhCn_bundles.db_no_parm) -- if not args["code"] then -- local result = respone.new_failed({},zhCn_bundles.db_no_parm) -- ngx.say(cjson.encode(result)) -- return -- end --获取access_token local res, err = httpc:request_uri("https://api.weixin.qq.com/sns/oauth2/access_token", { method = "GET", query = { grant_type = "authorization_code", appid = "wx5dd7a03e3fe86262", --填写自己的appid secret = "9b47297518f953376dec0c5b0697dd42", -- 填写自己的secret code = args["code"], }, ssl_verify = false, -- 需要关闭这项才能发起https请求 headers = {["Content-Type"] = "application/x-www-form-urlencoded" }, }) if not res then local result = respone.new_failed({},err) ngx.say(cjson.encode(result)) return end -- if not res.access_token then -- local result = respone.new_failed({},"invalid code") -- ngx.say(cjson.encode(result)) -- return -- end ngx.status = res.status ngx.say(res.body) --验证access_token是否有效 res, err = httpc:request_uri("https://api.weixin.qq.com/sns/auth", { method = "GET", query = { access_token = res["access_token"], openid = res["openid"], --用户openid }, ssl_verify = false, -- headers = {["Content-Type"] = "application/x-www-form-urlencoded" }, }) if not res then ngx.say("failed to request: ", err) return end --获取用户信息 res, err = httpc:request_uri("https://api.weixin.qq.com/sns/userinfo", { method = "GET", query = { access_token = res["access_token"], openid = res["openid"], -- }, ssl_verify = false, -- headers = {["Content-Type"] = "application/x-www-form-urlencoded" }, }) if not res then ngx.say("failed to request: ", err) return end
local AS = unpack(AddOnSkins) if not AS:CheckAddOn('Skada') then return end function AS:Skada() local L = LibStub('AceLocale-3.0'):GetLocale('Skada', false) function Skada:ShowPopup() AS:AcceptFrame(L['Do you want to reset Skada?'], function(self) Skada:Reset() self:GetParent():Hide() end) end local SkadaDisplayBar = Skada.displays['bar'] hooksecurefunc(SkadaDisplayBar, 'AddDisplayOptions', function(self, win, options) options.baroptions.args.barspacing = nil options.titleoptions.args.texture = nil options.titleoptions.args.bordertexture = nil options.titleoptions.args.thickness = nil options.titleoptions.args.margin = nil options.titleoptions.args.color = nil options.windowoptions = nil end) hooksecurefunc(SkadaDisplayBar, 'ApplySettings', function(self, win) local skada = win.bargroup skada:SetSpacing(1) skada:SetFrameLevel(5) skada:SetBackdrop(nil) if win.db.enabletitle then AS:SkinFrame(skada.button, 'Default') local color = win.db.title.color skada.button:SetBackdropColor(color.r, color.g, color.b, color.a or 1) end if not skada.Backdrop then AS:SkinBackdropFrame(skada) end if skada.Backdrop then skada.Backdrop:ClearAllPoints() if win.db.reversegrowth then skada.Backdrop:SetPoint('TOPLEFT', skada, 'TOPLEFT', -2, 2) skada.Backdrop:SetPoint('BOTTOMRIGHT', win.db.enabletitle and skada.button or skada, 'BOTTOMRIGHT', 2, -2) else skada.Backdrop:SetPoint('TOPLEFT', win.db.enabletitle and skada.button or skada, 'TOPLEFT', -2, 2) skada.Backdrop:SetPoint('BOTTOMRIGHT', skada, 'BOTTOMRIGHT', 2, -2) end end end) hooksecurefunc(Skada, 'ToggleWindow', function() if not (AS:CheckEmbed('Skada') and AS.EmbedSystemCreated) then return end for i, win in ipairs(Skada:GetWindows()) do if win:IsShown() then AS:SetOption('EmbedIsHidden', false) EmbedSystem_MainWindow:Show() else AS:SetOption('EmbedIsHidden', true) EmbedSystem_MainWindow:Hide() end end end) hooksecurefunc(Skada, 'CreateWindow', function() if AS:CheckEmbed('Skada') then AS:Embed_Skada() end end) hooksecurefunc(Skada, 'DeleteWindow', function() if AS:CheckEmbed('Skada') then AS:Embed_Skada() end end) hooksecurefunc(Skada, 'UpdateDisplay', function() if AS:CheckEmbed('Skada') and not InCombatLockdown() then AS:Embed_Skada() end end) end AS:RegisterSkin('Skada', AS.Skada)
local constant_keys = { 'crypto_sign_PUBLICKEYBYTES', 'crypto_sign_SECRETKEYBYTES', 'crypto_sign_BYTES', 'crypto_sign_SEEDBYTES', 'crypto_sign_ed25519_PUBLICKEYBYTES', 'crypto_sign_ed25519_SECRETKEYBYTES', 'crypto_sign_ed25519_BYTES', 'crypto_sign_ed25519_SEEDBYTES', } return constant_keys
Graphics = LCS.class{} SB_GFX_DIR = Path.Join(SB_DIR, "gfx/") SB_GFX_DRAW_DIR = Path.Join(SB_GFX_DIR, "draw/") SB.IncludeDir(SB_GFX_DIR) SB.IncludeDir(SB_GFX_DRAW_DIR) function Graphics:init() self:__InitTempTextures() end
return { ['sv_gamemode'] = 1, ['mp_hudscale'] = 1, ['mp_unbuildable'] = 'turret', ['mp_hud'] = 8+64, ['mp_radar'] = 0, ['mp_respawndelay'] = 255, ['mp_luamap'] = 1 }
local interface = {} interface["func"] = {} interface["setting"] = {} interface["db"] = DB_MANAGER interface["log"] = LOGGER_IN interface["tool"] = { -- 检查某个函数是否存在(或被实现) method_exist = function (name) local state, func = pcall(require, name) if state then return func else return nil end end, -- 打印 table 数据 dump = function (object) if type(object) == 'table' then local s = '{ ' for k,v in pairs(object) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s .. '['..k..'] = ' .. interface.tool.dump(v) .. ',' end return s .. '} ' else return tostring(object) end end } return interface
local debug = {} function debug:setup_gvv() if script.active_mods["gvv"] then require("__gvv__.gvv")() end end return debug
--*********************************************************** --** ROBERT JOHNSON ** --*********************************************************** require "TimedActions/ISBaseTimedAction" ---@class ISFixGenerator : ISBaseTimedAction ISFixGenerator = ISBaseTimedAction:derive("ISFixGenerator"); function ISFixGenerator:isValid() return self.generator:getObjectIndex() ~= -1 and not self.generator:isActivated() and self.generator:getCondition() < 100 and self.character:getInventory():contains("ElectronicsScrap") end function ISFixGenerator:waitToStart() self.character:faceThisObject(self.generator) return self.character:shouldBeTurning() end function ISFixGenerator:update() self.character:faceThisObject(self.generator) self.character:setMetabolicTarget(Metabolics.UsingTools); end function ISFixGenerator:start() self:setActionAnim("Loot") self.character:SetVariable("LootPosition", "Low") self.character:reportEvent("EventLootItem") end function ISFixGenerator:stop() ISBaseTimedAction.stop(self); end function ISFixGenerator:perform() -- needed to remove from queue / start next. ISBaseTimedAction.perform(self); self.generator:setCondition(self.generator:getCondition() + 4 + (1*(self.character:getPerkLevel(Perks.Electricity))/2)) self.character:getInventory():RemoveOneOf("ElectronicsScrap"); self.character:getXp():AddXP(Perks.Electricity, 5); if self.generator:getCondition() < 100 and self.character:getInventory():contains("ElectronicsScrap") then ISTimedActionQueue.add(ISFixGenerator:new(self.character, self.generator, 150)); end end function ISFixGenerator:new(character, generator, time) local o = {} setmetatable(o, self) self.__index = self o.character = character; o.generator = generator; o.stopOnWalk = true; o.stopOnRun = true; o.maxTime = time - (o.character:getPerkLevel(Perks.Electricity) * 3); if o.character:isTimedActionInstant() then o.maxTime = 1; end o.caloriesModifier = 4; return o; end
--[[ Jericho's system.print() extension -- https://github.com/Jericho1060 Display content in lua chat channel with colors Source : https://github.com/Jericho1060/DualUniverse/blob/master/tools/console%20text%20colors.lua ]] system.printColor = function(message, color) system.print('<span style="color:' .. color .. ';">' .. message .. '</span>') end system.printPrimary = function(message) system.printColor(message, "#007bff") end system.printSecondary = function(message) system.printColor(message, "#6c757d") end system.printSuccess = function (message) system.printColor(message, "#28a745") end system.printDanger = function (message) system.printColor(message, "#dc3545") end system.printWarning = function (message) system.printColor(message, "#ffc107") end system.printInfo = function (message) system.printColor(message, "#17a2b8") end
local function f(i,sum) return i-1, sum + 1 end local sum = 0 local j = 1000 while (j > 0) do if (j % 10 == 0) then io.write('.'); io.flush() end local i = 10000 while (i > 0) do i,sum = f(i,sum) end j = j - 1 end print (sum)
-- Generated by CSharp.lua Compiler local System = System local SlipeClientGame local SlipeMtaDefinitions local SlipeSharedElements local SlipeSharedHelpers local SystemNumerics System.import(function (out) SlipeClientGame = Slipe.Client.Game SlipeMtaDefinitions = Slipe.MtaDefinitions SlipeSharedElements = Slipe.Shared.Elements SlipeSharedHelpers = Slipe.Shared.Helpers SystemNumerics = System.Numerics end) System.namespace("Slipe.Client.Lights", function (namespace) -- <summary> -- This function creates a searchlight. A searchlight is a spotlight which looks like the one available in the Police Maverick. -- </summary> namespace.class("SearchLight", function (namespace) local getToAttached, getIsAttached, getStartPosition, setStartPosition, getEndPosition, setEndPosition, getStartRadius, setStartRadius, getEndRadius, setEndRadius, AttachTo, AttachTo1, AttachTo2, AttachTo3, Detach, Update, internal, __ctor1__, __ctor2__, __ctor3__ internal = function (this) this.relativeEndPosition = System.default(SystemNumerics.Vector3) this.Offset = System.default(SystemNumerics.Matrix4x4) end __ctor1__ = function (this, element) internal(this) SlipeSharedElements.Element.__ctor__[2](this, element) end -- <summary> -- Create a searchlight from all parameters -- </summary> __ctor2__ = function (this, start, end_, startRadius, endRadius, renderSpot) __ctor1__(this, SlipeMtaDefinitions.MtaClient.CreateSearchLight(start.X, start.Y, start.Z, end_.X, end_.Y, end_.Z, startRadius, endRadius, renderSpot)) this.relativeEndPosition = SystemNumerics.Vector3.op_Subtraction(end_, start) end -- <summary> -- Create a searchlight attached to an element -- </summary> __ctor3__ = function (this, attachTo, relativeEnd, offset, startRadius, endRadius, renderSpot) __ctor2__(this, SystemNumerics.Vector3.getZero(), relativeEnd:__clone__(), startRadius, endRadius, renderSpot) AttachTo(this, attachTo, offset:__clone__()) end getToAttached = function (this) return this.toAttached end getIsAttached = function (this) return this.toAttached ~= nil end getStartPosition = function (this) local result = SlipeMtaDefinitions.MtaClient.GetSearchLightStartPosition(this.element) return SystemNumerics.Vector3(result[1], result[2], result[3]) end setStartPosition = function (this, value) SlipeMtaDefinitions.MtaClient.SetSearchLightStartPosition(this.element, value.X, value.Y, value.Z) end getEndPosition = function (this) local result = SlipeMtaDefinitions.MtaClient.GetSearchLightEndPosition(this.element) return SystemNumerics.Vector3(result[1], result[2], result[3]) end setEndPosition = function (this, value) SlipeMtaDefinitions.MtaClient.SetSearchLightEndPosition(this.element, value.X, value.Y, value.Z) end getStartRadius = function (this) return SlipeMtaDefinitions.MtaClient.GetSearchLightStartRadius(this.element) end setStartRadius = function (this, value) SlipeMtaDefinitions.MtaClient.SetSearchLightStartRadius(this.element, value) end getEndRadius = function (this) return SlipeMtaDefinitions.MtaClient.GetSearchLightEndRadius(this.element) end setEndRadius = function (this, value) SlipeMtaDefinitions.MtaClient.SetSearchLightEndRadius(this.element, value) end -- <summary> -- Attach this attachable to a toAttachable using a matrix to describe the positional and rotational offset -- </summary> AttachTo = function (this, toElement, offsetMatrix) this.toAttached = toElement this.Offset = offsetMatrix:__clone__() SlipeClientGame.GameClient.OnUpdate = SlipeClientGame.GameClient.OnUpdate + System.fn(this, Update) end -- <summary> -- Attach this attachable to a toAttachable with 2 vectors describing a position offset and a rotation offset -- </summary> AttachTo1 = function (this, toElement, positionOffset, rotationOffset) AttachTo2(this, toElement, positionOffset:__clone__(), SlipeSharedHelpers.NumericHelper.EulerToQuaternion(rotationOffset:__clone__())) end -- <summary> -- Attach this attachable to a toAttachable with a vector describing the position offset and a quaternion describing the rotation offset -- </summary> AttachTo2 = function (this, toElement, positionOffset, rotationOffset) AttachTo(this, toElement, SystemNumerics.Matrix4x4.Transform(SystemNumerics.Matrix4x4.CreateTranslation(positionOffset), rotationOffset)) end -- <summary> -- Attach this attachable to a toAttachable without any offset -- </summary> AttachTo3 = function (this, toElement) AttachTo(this, toElement, SystemNumerics.Matrix4x4.getIdentity()) end -- <summary> -- Detach this attachable -- </summary> Detach = function (this) SlipeClientGame.GameClient.OnUpdate = SlipeClientGame.GameClient.OnUpdate - System.fn(this, Update) end -- <summary> -- Updates this element to the correct position and rotation -- </summary> Update = function (this, source, eventArgs) setStartPosition(this, SystemNumerics.Vector3.op_Addition(getToAttached(this):getPosition(), this.Offset:__clone__():getTranslation())) setEndPosition(this, SystemNumerics.Vector3.Transform(this.relativeEndPosition, SystemNumerics.Matrix4x4.op_Multiply(getToAttached(this):getMatrix(), this.Offset:__clone__()))) end return { __inherits__ = function (out) return { out.Slipe.Shared.Elements.Element } end, getToAttached = getToAttached, getIsAttached = getIsAttached, getStartPosition = getStartPosition, setStartPosition = setStartPosition, getEndPosition = getEndPosition, setEndPosition = setEndPosition, getStartRadius = getStartRadius, setStartRadius = setStartRadius, getEndRadius = getEndRadius, setEndRadius = setEndRadius, AttachTo = AttachTo, AttachTo1 = AttachTo1, AttachTo2 = AttachTo2, AttachTo3 = AttachTo3, Detach = Detach, Update = Update, __ctor__ = { __ctor1__, __ctor2__, __ctor3__ }, __metadata__ = function (out) return { fields = { { "relativeEndPosition", 0x3, System.Numerics.Vector3 }, { "toAttached", 0x3, out.Slipe.Shared.Elements.PhysicalElement } }, properties = { { "EndPosition", 0x106, System.Numerics.Vector3, getEndPosition, setEndPosition }, { "EndRadius", 0x106, System.Single, getEndRadius, setEndRadius }, { "IsAttached", 0x206, System.Boolean, getIsAttached }, { "Offset", 0x6, System.Numerics.Matrix4x4 }, { "StartPosition", 0x106, System.Numerics.Vector3, getStartPosition, setStartPosition }, { "StartRadius", 0x106, System.Single, getStartRadius, setStartRadius }, { "ToAttached", 0x206, out.Slipe.Shared.Elements.PhysicalElement, getToAttached } }, methods = { { ".ctor", 0x106, __ctor1__, out.Slipe.MtaDefinitions.MtaElement }, { ".ctor", 0x506, __ctor2__, System.Numerics.Vector3, System.Numerics.Vector3, System.Single, System.Single, System.Boolean }, { ".ctor", 0x606, __ctor3__, out.Slipe.Shared.Elements.PhysicalElement, System.Numerics.Vector3, System.Numerics.Matrix4x4, System.Single, System.Single, System.Boolean }, { "AttachTo", 0x206, AttachTo, out.Slipe.Shared.Elements.PhysicalElement, System.Numerics.Matrix4x4 }, { "AttachTo", 0x306, AttachTo1, out.Slipe.Shared.Elements.PhysicalElement, System.Numerics.Vector3, System.Numerics.Vector3 }, { "AttachTo", 0x306, AttachTo2, out.Slipe.Shared.Elements.PhysicalElement, System.Numerics.Vector3, System.Numerics.Quaternion }, { "AttachTo", 0x106, AttachTo3, out.Slipe.Shared.Elements.PhysicalElement }, { "Detach", 0x6, Detach }, { "Update", 0x203, Update, out.Slipe.Client.Elements.RootElement, out.Slipe.Client.Game.Events.OnUpdateEventArgs } }, class = { 0x6, System.new(out.Slipe.Shared.Elements.DefaultElementClassAttribute, 2, 33 --[[ElementType.SearchLight]]) } } end } end) end)
Font = class() -- - The Hershey Fonts were originally created by Dr. -- A. V. Hershey while working at the -- U. S. National Bureau of Standards. -- Useful Links: -- http://emergent.unpythonic.net/software/hershey -- http://paulbourke.net/dataformats/hershey/ -- Re-encoding of font information and other shenanigans -- by Tom Bortels [email protected] November 2011 -- all rights reversed (Hail Eris!) -- "If I have seen a little further it is by standing -- on the shoulders of Giants." -- Isaac Newton function Font:init() -- font data - 2 decimal character # of points, -- followed by 2*points of point data -- 9->-9, 8-<-8, ... 1->-1, 0->0, A->1, B->2, ... Z->26 self.code = "9876543210ABCDEFGHIJKLMNOPQRSTUVWXYZ" -- this is the Hershey Roman Simplex font for ascii 32-127 self.fontdata = "00160810EUEG11EBDAE0FAEB0516DUDN11LULN1121KYD711QYJ711DLRL11" .. "CFQF2620HYH411LYL411QROTLUHUETCRCPDNEMGLMJOIPHQFQCOAL0H0EACC" .. "3124UUC011HUJSJQIOGNENCPCRDTFUHUJTMSPSSTUU11QGOFNDNBP0R0TAUC" .. "UESGQG3426WLWMVNUNTMSKQFOCMAK0G0EADBCDCFDHEILMMNNPNRMTKUITHR" .. "HPIMKJPCRAT0V0WAWB0710ESDTEUFTFREPDO1014KYIWGTEPDKDGEBG2I5K7" .. "1014CYEWGTIPJKJGIBG2E5C70816HUHI11CRML11MRCL0526MRM011DIVI08" .. "10FAE0DAEBFAF1E3D40226DIVI0510EBDAE0FAEB0222TYB71720IUFTDQCL" .. "CIDDFAI0K0NAPDQIQLPQNTKUIU0420FQHRKUK01420DPDQESFTHULUNTOSPQ" .. "POOMMJC0Q01520EUPUJMMMOLPKQHQFPCNAK0H0EADBCD0620MUCGRG11MUM0" .. "1720OUEUDLEMHNKNNMPKQHQFPCNAK0H0EADBCD2320PROTLUJUGTEQDLDGEC" .. "GAJ0K0NAPCQFQGPJNLKMJMGLEJDG0520QUG011CUQU2920HUETDRDPENGMKL" .. "NKPIQGQDPBOAL0H0EADBCDCGDIFKILMMONPPPROTLUHU2320PNOKMIJHIHFI" .. "DKCNCODRFTIUJUMTORPNPIODMAJ0H0EADC1110ENDMELFMEN11EBDAE0FAEB" .. "1410ENDMELFMEN11FAE0DAEBFAF1E3D40324TRDIT00526DLVL11DFVF0324" .. "DRTID02018CPCQDSETGUKUMTNSOQOONMMLIJIG11IBHAI0JAIB5527RMQOOP" .. "LPJOINHKHHIFKENEPFQH11LPJNIKIHJFKE11RPQHQFSEUEWGXJXLWOVQTSRT" .. "OULUITGSEQDOCLCIDFEDGBIAL0O0RATBUC11SPRHRFSE0818IUA011IUQ011" .. "DGNG2321DUD011DUMUPTQSRQROQMPLMK11DKMKPJQIRGRDQBPAM0D01821RP" .. "QROTMUIUGTERDPCMCHDEECGAI0M0OAQCRE1521DUD011DUKUNTPRQPRMRHQE" .. "PCNAK0D01119DUD011DUQU11DKLK11D0Q00818DUD011DUQU11DKLK2221RP" .. "QROTMUIUGTERDPCMCHDEECGAI0M0OAQCRERH11MHRH0822DUD011RUR011DK" .. "RK0208DUD01016LULEKBJAH0F0DACBBEBG0821DUD011RUDG11ILR00517DU" .. "D011D0P01124DUD011DUL011TUL011TUT00822DUD011DUR011RUR02122IU" .. "GTERDPCMCHDEECGAI0M0OAQCRESHSMRPQROTMUIU1321DUD011DUMUPTQSRQ" .. "RNQLPKMJDJ2422IUGTERDPCMCHDEECGAI0M0OAQCRESHSMRPQROTMUIU11LD" .. "R21621DUD011DUMUPTQSRQROQMPLMKDK11KKR02020QROTLUHUETCRCPDNEM" .. "GLMJOIPHQFQCOAL0H0EACC0516HUH011AUOU1022DUDFECGAJ0L0OAQCRFRU" .. "0518AUI011QUI01124BUG011LUG011LUQ011VUQ00520CUQ011QUC00618AU" .. "IKI011QUIK0820QUC011CUQU11C0Q01114DYD711EYE711DYKY11D7K70214" .. "0UN31114IYI711JYJ711CYJY11C7J71016FOHRJO11CLHQML11HQH0021602" .. "P20710FUETDRDPEOFPEQ1719ONO011OKMMKNHNFMDKCHCFDCFAH0K0MAOC17" .. "19DUD011DKFMHNKNMMOKPHPFOCMAK0H0FADC1418OKMMKNHNFMDKCHCFDCFA" .. "H0K0MAOC1719OUO011OKMMKNHNFMDKCHCFDCFAH0K0MAOC1718CHOHOJNLMM" .. "KNHNFMDKCHCFDCFAH0K0MAOC0812JUHUFTEQE011BNIN2219ONO2N5M6K7H7" .. "F611OKMMKNHNFMDKCHCFDCFAH0K0MAOC1019DUD011DJGMINLNNMOJO00808" .. "CUDTEUDVCU11DND01110EUFTGUFVEU11FNF3E6C7A70817DUD011NNDD11HH" .. "O00208DUD01830DND011DJGMINLNNMOJO011OJRMTNWNYMZJZ01019DND011" .. "DJGMINLNNMOJO01719HNFMDKCHCFDCFAH0K0MAOCPFPHOKMMKNHN1719DND7" .. "11DKFMHNKNMMOKPHPFOCMAK0H0FADC1719ONO711OKMMKNHNFMDKCHCFDCFA" .. "H0K0MAOC0813DND011DHEKGMINLN1717NKMMJNGNDMCKDIFHKGMFNDNCMAJ0" .. "G0DACC0812EUEDFAH0J011BNIN1019DNDDEAG0J0LAOD11ONO00516BNH011" .. "NNH01122CNG011KNG011KNO011SNO00517CNN011NNC00916BNH011NNH0F4" .. "D6B7A70817NNC011CNNN11C0N03914IYGXFWEUESFQGPHNHLFJ11GXFVFTGR" .. "HQIOIMHKDIHGIEICHAG0F2F4G611FHHFHDGBFAE1E3F5G6I70208DYD73914" .. "EYGXHWIUISHQGPFNFLHJ11GXHVHTGRFQEOEMFKJIFGEEECFAG0H2H4G611HH" .. "FFFDGBHAI1I3H5G6E72324CFCHDKFLHLJKNHPGRGTHUJ11CHDJFKHKJJNGPF" .. "RFTGUJUL" local i=1 local c=32 self.font = {} while (i < string.len(self.fontdata)) do local cs = string.char(c) self.font[cs] = {} local points = string.sub(self.fontdata, i, i+1) self.font[cs].points = points self.font[cs].char = cs self.font[cs].ascii = c self.font[cs].width = string.sub(self.fontdata, i+2, i+3) i = i + 4 self.font[cs].data = string.sub(self.fontdata, i, i+points*2) i = i + points*2 c = c + 1 end i=-9 self.decode = {} for c in self.code:gmatch"." do self.decode[c]=i i=i+1 end end -- returns width in pixels of unscaled, strokeWidth(1) string function Font:stringwidth(s) local x, l, i = 0, string.len(s) for i = 1, l do x = x + self.font[s:sub(i, i)].width end end -- draw a string at x,y (skipping offscreen draws) function Font:drawstring(s, x, y) local l, i l = string.len(s) for i = 1, l do local c = s:sub(i, i) local w = self.font[c].width if ((x + w) >= 0) then x = x + (self:drawchar(c, x, y)) else x = x + w -- skip offscreen left (but track position) end if (x > WIDTH) then break end -- skip offscreen right end end -- optimized draw string at x,y (old version for reference) function Font:olddrawstring(s, x, y) local l, i l = string.len(s) for i = 1, l do x = x + (self:drawchar(string.sub(s, i, i), x, y)) end end function Font:drawchar(c, x, y) local ax, ay, bx, by, minx, maxx = -1, -1, -1, -1, -1, -1 local p, plot local ch = self.font[c] for p=1, ch.points do ax=bx ay=by bx=self.decode[ch.data:sub(p*2-1, p*2-1)] by=self.decode[ch.data:sub(p*2, p*2)] plot=true if ((ax==-1) and (ay==-1)) then plot=false end if ((bx==-1) and (by==-1)) then plot=false end if (plot) then line(x+ax, y+ay, x+bx, y+by) end end return ch.width -- for drawstring end
ITEM.name = "ОЦ-14 «Гроза»" ITEM.desc = "Опытный образец автоматно-гранатомётного комплекса, российская модификация стандартного «Гром-С14», созданная специально для действующих в Зоне спецподразделений. Отличается увеличенным размером магазина. \n\nБоеприпасы 9х39" ITEM.price = 40488 ITEM.class = "weapon_cop_groza" ITEM.weaponCategory = "1" ITEM.category = "Оружие" ITEM.exRender = false ITEM.weight = 4.32 ITEM.model = "models/wick/weapons/stalker/stcopwep/w_groza_model_stcop.mdl" ITEM.width = 4 ITEM.height = 2 ITEM.iconCam = { pos = Vector(1, 200, 1), ang = Angle(0, 270, 0), fov = 12.03821656051 }
--- ### Select bus driver between classic PCI and VFIO module(...,package.seeall) local ffi = require('ffi') local C = ffi.C local lib = require('core.lib') local pci = require('lib.hardware.pci') local vfio = require('lib.hardware.vfio') local memory = require("core.memory") devices = {} map_devices = {} function scan_devices () for _,device in ipairs(lib.files_in_directory("/sys/bus/pci/devices")) do local info = device_info(device) if info.driver and not map_devices[device] then table.insert(devices, info) map_devices[device] = info end end end function host_has_vfio() local files = lib.files_in_directory('/sys/kernel/iommu_groups/') return files and #files > 0 end function device_in_vfio(devicepath) local iommu_group = lib.basename(lib.readlink(devicepath..'/iommu_group')) if not iommu_group then return false end local drivername = lib.basename(lib.readlink(devicepath..'/driver')) return drivername == 'vfio-pci' end function device_info(pciaddress) if map_devices[pciaddress] then return map_devices[pciaddress] end local pcidevpath = pci.path(pciaddress) if device_in_vfio(pcidevpath) then info = vfio.device_info(pciaddress) info.bus = 'vfio' info.device_info = vfio.device_info info.map_pci_memory = vfio.map_pci_memory info.set_bus_master = vfio.set_bus_master info.dma_alloc = memory.dma_alloc else info = pci.device_info(pciaddress) info.bus = 'pci' info.device_info = pci.device_info info.map_pci_memory = pci.map_pci_memory info.set_bus_master = pci.set_bus_master info.dma_alloc = memory.dma_alloc end return info end function map_pci_memory(pciaddress, n) return map_devices[pciaddress].map_pci_memory(pciaddress, n) end function set_bus_master(pciaddress, enable) return map_devices[pciaddress].set_bus_master(pciaddress, enable) end function selftest () print("selftest: bus") scan_devices() for _,info in ipairs(devices) do print (string.format("device %s: %s", info.pciaddress, info.bus)) end end if host_has_vfio() then memory.ram_to_io_addr = vfio.set_mapping(memory.huge_page_size) else memory.set_use_physical_memory() end memory.set_default_allocator(true)
return Def.ActorFrame{ PREFSMAN:SetPreference("DisabledSongs",0); --Clean "DisabledSongs" preference LoadFont("Common normal")..{ InitCommand=cmd(x,_screen.cx;y,_screen.cy;zoom,0.9;maxwidth,_screen.w*0.9); OnCommand=cmd(settext,"DisabledSongs setting resetted\n relaunch game in order to changes make effect\n(Press CENTER to continue)"); }; };
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2012-2014 Kenny Shields -- --]]------------------------------------------------ return function(loveframes) ---------- module start ---------- -- menuoption object local newobject = loveframes.newObject("menuoption", "loveframes_object_menuoption", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize(parent, option_type, menu) self.type = "menuoption" self.text = "Option" self.width = 100 self.height = 25 self.contentwidth = 0 self.contentheight = 0 self.parent = parent self.option_type = option_type or "option" self.menu = menu self.activated = false self.internal = true self.icon = false self.func = nil self:setDrawFunc() end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the object --]]--------------------------------------------------------- function newobject:_update(dt) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end self:checkHover() local hover = self.hover local parent = self.parent local option_type = self.option_type local activated = self.activated local base = loveframes.base local update = self.update if option_type == "submenu_activator" then if hover and not activated then self.menu:setVisible(true) self.menu:moveToTop() self.activated = true elseif not hover and activated then local hoverobject = loveframes.hoverobject if hoverobject and hoverobject:getBaseParent() == self.parent then self.menu:setVisible(false) self.activated = false end elseif activated then local screen_width = love.graphics.getWidth() local screen_height = love.graphics.getHeight() local sx = self.x local sy = self.y local width = self.width local height = self.height local x1 = sx + width if x1 + self.menu.width <= screen_width then self.menu.x = x1 else self.menu.x = sx - self.menu.width end if sy + self.menu.height <= screen_height then self.menu.y = sy else self.menu.y = (sy + height) - self.menu.height end end end -- move to parent if there is a parent if parent ~= base then self.x = self.parent.x + self.staticx self.y = self.parent.y + self.staticy end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: mousepressed(x, y, button) - desc: called when the player presses a mouse button --]]--------------------------------------------------------- function newobject:mousepressed(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end end --[[--------------------------------------------------------- - func: mousereleased(x, y, button) - desc: called when the player releases a mouse button --]]--------------------------------------------------------- function newobject:mousereleased(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end local hover = self.hover local option_type = self.option_type if hover and option_type ~= "divider" and button == 1 then local func = self.func if func then local text = self.text func(self, text) end local basemenu = self.parent:getBaseMenu() basemenu:setVisible(false) end end --[[--------------------------------------------------------- - func: setText(text) - desc: sets the object's text --]]--------------------------------------------------------- function newobject:setText(text) self.text = text end --[[--------------------------------------------------------- - func: getText() - desc: gets the object's text --]]--------------------------------------------------------- function newobject:getText() return self.text end --[[--------------------------------------------------------- - func: setIcon(icon) - desc: sets the object's icon --]]--------------------------------------------------------- function newobject:setIcon(icon) if type(icon) == "string" then self.icon = love.graphics.newImage(icon) self.icon:setFilter("nearest", "nearest") elseif type(icon) == "userdata" then self.icon = icon end end --[[--------------------------------------------------------- - func: getIcon() - desc: gets the object's icon --]]--------------------------------------------------------- function newobject:getIcon() return self.icon end --[[--------------------------------------------------------- - func: setFunction(func) - desc: sets the object's function --]]--------------------------------------------------------- function newobject:setFunction(func) self.func = func end ---------- module end ---------- end
local abs = math.abs local floor = math.floor local max = math.max local min = math.min local sort = table.sort local vehicle_types = { ["locomotive"] = true, ["cargo-wagon"] = true, ["car"] = true, } local train_types = { ["locomotive"] = true, ["cargo-wagon"] = true, } local default_masses = { ["locomotive"] = LOCOMOTIVE_MASS, ["cargo-wagon"] = CARGO_WAGON_MASS, ["car"] = CAR_MASS, } -- Local function prototypes local cache_equipment local cars_tick local charge_tick local fuel_tick local on_entity_removed local read_equipment local recover_energy local update_equipment -- Table utils ------------------------------------------------------------------------------- -- These utilities assume the table is an array and each value is unique local function insert_unique_f(tbl, x, f) for k, v in pairs(tbl) do if(f(v)) then return false end end tbl[#tbl + 1] = x return true end local function erase_f(tbl, f) for k, v in pairs(tbl) do if(f(v)) then tbl[k] = nil return k end end return nil end -- Local caches ------------------------------------------------------------------------------- -- Dictionary of only those vehicles that have a transformer -- [unit-number] = transformer index local transformer_for_unit = { } -- Remember entities which were invalid in on_load to remove in the first on_tick local invalid_entities = { } function rebuild_caches() equipment_cache = { } transformer_for_unit = { } for unit, entity in pairs(global.vehicles) do if(entity.valid) then local grid = entity.grid if(grid and grid.valid) then cache_equipment(unit, read_equipment(unit, grid)) else invalid_entities[#invalid_entities + 1] = unit end else invalid_entities[#invalid_entities + 1] = unit end end end function validate_prototypes() -- Stop doing anything involving a no longer present prototypes local equipment = game.equipment_prototypes local entities = game.entity_prototypes for tbl, exists in pairs{[global.transformers] = equipment} do for name in pairs(tbl) do if(not exists[name]) then tbl[name] = nil end end end end function validate_entities() -- If any units were deleted stop processing them for unit, entity in pairs(global.vehicles) do if(not entity.valid or not entity.grid) then global.vehicles[unit] = nil else -- In case equipment was deleted update_equipment(unit, entity.grid) end end end -- Equipment handling ------------------------------------------------------------------------------- read_equipment = function(unit, grid) local equipment = grid.equipment local known_transformers = global.transformers local transformers = { } for i = 1, #equipment do local item = equipment[i] if(known_transformers[item.name] and item.prototype.energy_source) then transformers[#transformers + 1] = i end end sort(transformers, function(a, b) return equipment[a].prototype.energy_source.input_flow_limit > equipment[b].prototype.energy_source.input_flow_limit end) return transformers end cache_equipment = function(unit, transformers) transformer_for_unit[unit] = transformers[1] end function update_equipment(unit, grid) local transformers = read_equipment(unit, grid) local entity = global.vehicles[unit] cache_equipment(unit, transformers) end -- on_tick actions ------------------------------------------------------------------------------- fuel_tick = function() local vehicles = global.vehicles for unit, equipment in pairs(transformer_for_unit) do local entity = vehicles[unit] local transformer = entity.grid.equipment[equipment] local available_energy = transformer.energy local current_energy = entity.energy entity.energy = current_energy + available_energy -- The burner energy buffer is kinda weird so we have to check how much energy we actually inserted local used = entity.energy - current_energy transformer.energy = available_energy - used end end -- Entity management ------------------------------------------------------------------------------- on_entity_removed = function(entity) if(vehicle_types[entity.type]) then local unit = entity.unit_number global.vehicles[unit] = nil transformer_for_unit[unit] = nil end end -- Event entry points ------------------------------------------------------------------------------- function on_built_entity(event) local entity = event.created_entity if(vehicle_types[entity.type] and entity.grid) then global.vehicles[entity.unit_number] = entity update_equipment(entity.unit_number, entity.grid) end end function on_entity_died(event) on_entity_removed(event.entity) end function on_player_placed_equipment(event) for unit, entity in pairs(global.vehicles) do if(entity.valid and entity.grid == event.grid) then update_equipment(unit, event.grid) break end end end function on_player_removed_equipment(event) for unit, entity in pairs(global.vehicles) do if(entity.valid and entity.grid == event.grid) then update_equipment(unit, event.grid) break end end end function on_preplayer_mined_item(event) on_entity_removed(event.entity) end function on_robot_pre_mined(event) on_entity_removed(event.entity) end function on_tick(event) function real_on_tick(event) fuel_tick() end for _, unit in pairs(invalid_entities) do local unit = invalid_entities[i] if global.vehicles[unit] ~= nil then global.vehicles[unit] = nil end end invalid_entities = { } script.on_event(defines.events.on_tick, real_on_tick) real_on_tick(event) end -- Remote interface ------------------------------------------------------------------------------- function register_transformer(data) assert(type(data.name) == "string", "'name' must be a string") local prototype = game.equipment_prototypes[data.name] assert(prototype, string.format("%s is not a valid equipment prototype", data.name)) assert(prototype.energy_source, string.format("%s has no energy_source", data.name)) global.transformers[data.name] = { [1] = data.name, [2] = prototype.energy_source.input_flow_limit, } end
frenzied_donkuwah = Creature:new { objectName = "@mob/creature_names:frenzied_donkuwah", randomNameType = NAME_GENERIC, randomNameTag = true, socialGroup = "donkuwah_tribe", faction = "donkuwah_tribe", level = 39, chanceHit = 0.42, damageMin = 365, damageMax = 440, baseXp = 3915, baseHAM = 9000, baseHAMmax = 11000, armor = 0, resists = {40,0,0,50,50,-1,0,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0.0, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + KILLER, optionsBitmask = AIENABLED, diet = HERBIVORE, templates = { "object/mobile/dulok_male.iff", "object/mobile/dulok_female.iff"}, lootGroups = { { groups = { {group = "donkuwah_common", chance = 10000000} }, lootChance = 1780000 } }, weapons = {"donkuwah_weapons"}, conversationTemplate = "", attacks = merge(fencermaster,brawlermaster) } CreatureTemplates:addCreatureTemplate(frenzied_donkuwah, "frenzied_donkuwah")
function menu_load(x, y) gamestate = "menu" musicvolume = 0 menumusic:setVolume(musicvolume) playsound(menumusic) pl = nil coins = {} menuoffset = y or 0 menuoffsett = y or 0 menuoffsetx = x or 0 menuoffsetxt = x or 0 pitch = 0 rotation = pi075 wantedbackground = {0, 0, 0} coincount = 0 drawcenterX = screenwidth/2 drawcenterY = 140 boxwidth = 45 rotcenterX = menurotcenterX rotcenterY = menurotcenterY rotcenterZ = menurotcenterZ calculatevars() creditstext = { "'Ortho Robot'", "An awesome game by", "Maurice Guegan", "Level design help by ", "Visit Stabyourself.net for more"} helptext = { "You're a robot ", "You have to recharge yourself ", "Collect for bonus points", "Drag the view to activate the FSWD ", "If you're not blocked (background green),", "you can walk without depth!"} wintext = { "Congratulations!", "You have beaten every", "level and successfully", "recharged yourself!", "Try to get a gold star", "for every level!"} if x == nil and y == nil then backgroundblocks = {} for i = 1, 500 do table.insert(backgroundblocks, backgroundblock:new(unpack(newBox(true)))) end menubuttons = {} table.insert(menubuttons, menubutton:new(screenwidth/2, 300, "Play levels", button_start)) table.insert(menubuttons, menubutton:new(screenwidth/2, 400, "Help", button_help)) table.insert(menubuttons, menubutton:new(screenwidth/2, 500, "Credits", button_credits)) table.insert(menubuttons, menubutton:new(screenwidth/2, 600, "Exit", button_exit)) table.insert(menubuttons, menubutton:new(screenwidth/2, -45, "Back", button_back)) table.insert(menubuttons, menubutton:new(screenwidth/2-100, 1100, "Yes", button_yes)) table.insert(menubuttons, menubutton:new(screenwidth/2+100, 1100, "No", button_no)) table.insert(menubuttons, menubutton:new(screenwidth/2+screenwidth, 650, "< Okay I get it", button_creditsback)) table.insert(menubuttons, menubutton:new(-screenwidth/2, 685, "Let's do this >", button_creditsback)) table.insert(menubuttons, menubutton:new(screenwidth-141, -45, "Next >", button_nextpage)) table.insert(menubuttons, menubutton:new(198, -45, "< Previous", button_prevpage)) table.insert(menubuttons, menubutton:new(screenwidth/2+screenwidth, 0, "< Awesome", button_winback)) if scale == 1 then sizebutton = pausebutton:new(0, 0, "Help, this game doesn't fit on my screen!", scalebutton) else sizebutton = pausebutton:new(0, 0, "Nevermind, the game does fit on my screen.", scalebutton) end sizebutton.width = 680 sizebutton.active = true else menubuttons[5].active = true end pausebuttons = {} if soundenabled then pausebuttons["menutogglesound"] = pausebutton:new(109, 0, "Sound ON", menu_togglesound) else pausebuttons["menutogglesound"] = pausebutton:new(109, 0, "Sound OFF", menu_togglesound) end pausebuttons["menutogglesound"].active = true currentpage = math.min(math.ceil(currentmap/16), math.ceil(#filetable/16)) pages = math.ceil(#filetable/16) menubuttons[11].active = true menubuttons[10].active = true if currentpage == 1 then menubuttons[11].active = false end if currentpage == pages then menubuttons[10].active = false end levelbuttons = {} for i = 1, #filetable do if i >= (currentpage-1)*16+1 and i <= math.min(currentpage*16, #filetable) then local j = math.mod(i-1, 16)+1 local x = round(((math.mod(j-1, 4)-1)+1) * 247.5 + 125) local y = math.ceil(j/4) * 100 - 570 if i <= unlockedlevels then table.insert(levelbuttons, levelbutton:new(x, y, filetable[i].name, i, true)) else table.insert(levelbuttons, levelbutton:new(x, y, filetable[i].name, i, false)) end else if i < (currentpage-1)*16+1 then local j = math.mod(i-1, 16)+1 local x = round(((math.mod(j-1, 4)-1)+1) * 247.5 + 125 -screenwidth*math.ceil(((currentpage-1)*16+1 - i)/16)) local y = math.ceil(j/4) * 100 - 570 if i <= unlockedlevels then table.insert(levelbuttons, levelbutton:new(x, y, filetable[i].name, i, true)) else table.insert(levelbuttons, levelbutton:new(x, y, filetable[i].name, i, false)) end else local j = math.mod(i-1, 16)+1 local x = round(((math.mod(j-1, 4)-1)+1) * 247.5 + 125 + screenwidth*math.floor((i - ((currentpage-1)*16+1))/16)) local y = math.ceil(j/4) * 100 - 570 if i <= unlockedlevels then table.insert(levelbuttons, levelbutton:new(x, y, filetable[i].name, i, true)) else table.insert(levelbuttons, levelbutton:new(x, y, filetable[i].name, i, false)) end end end end fadetimer = 0 fadecolor = 0 fadetimert = 1 skipupdate = true end function scalebutton() if scale == 1 then changescale(0.75) sizebutton:changetext("Nevermind, the game does fit on my screen.") else changescale(1) sizebutton:changetext("Help, this game doesn't fit on my screen!") end end function menu_update(dt) if fadetimer ~= fadetimert then if fadetimert > fadetimer then fadetimer = fadetimer + dt if fadetimer >= fadetimert then fadetimer = fadetimert fadecolor = fadetimer menumusic:setVolume(1) else menumusic:setVolume(fadetimer) fadecolor = fadetimer end else fadetimer = fadetimer - dt if fadetimer <= fadetimert then fadetimer = fadetimert fadecolor = fadetimer menumusic:stop() if fadegoal == "startlevel" then game_load(fadei) return elseif fadegoal == "quit" then savesave() love.event.quit() return end else if menuoffsett < 0 then menumusic:setVolume(fadetimer*0.3) else menumusic:setVolume(fadetimer) end fadecolor = fadetimer end end else if menuoffsett >= 0 then menumusic:setVolume(menumusic:getVolume()+dt) if menumusic:getVolume() > 1 then menumusic:setVolume(1) end end end if menuoffsett < 0 and fadetimert ~= 0 then menumusic:setVolume(menumusic:getVolume()-dt) if menumusic:getVolume() < 0.3 then menumusic:setVolume(0.3) end end --get closest full rot local rot = rotation+pi025 while rot > math.pi/4 do rot = rot - math.pi/2 end local speed = math.abs(rot)*2+0.005 --pitch = (math.abs(rot))/pi05*0.3 pitchadd = ((love.mouse.getY()-menuoffset)-330)/screenheight * 0.2 pitchadd = math.max(math.min(pitchadd, 1), 0) pitch = pitchadd rotation = rotation + speed*dt while rotation > math.pi*2 do rotation = rotation - math.pi*2 end while rotation < 0 do rotation = rotation + math.pi*2 end calculatevars() if menuoffset ~= menuoffsett then if menuoffset < menuoffsett then menuoffset = menuoffset + (menuoffsett-menuoffset)*4*dt + 2*dt if menuoffset > menuoffsett then menuoffset = menuoffsett end else menuoffset = menuoffset + (menuoffsett-menuoffset)*4*dt - 2*dt if menuoffset < menuoffsett then menuoffset = menuoffsett end end end if menuoffsetx ~= menuoffsetxt then if menuoffsetx < menuoffsetxt then menuoffsetx = menuoffsetx + (menuoffsetxt-menuoffsetx)*4*dt + 2*dt if menuoffsetx > menuoffsetxt then menuoffsetx = menuoffsetxt end else menuoffsetx = menuoffsetx + (menuoffsetxt-menuoffsetx)*4*dt - 2*dt if menuoffsetx < menuoffsetxt then menuoffsetx = menuoffsetxt end end end for i, v in pairs(menubuttons) do v:update(dt) end for i, v in pairs(levelbuttons) do v:update(dt) end pausebuttons["menutogglesound"]:update(dt) sizebutton.x = menuoffsetx-screenwidth/2 sizebutton.y = menuoffset+615 sizebutton:update(dt) end function menu_draw() love.graphics.translate(menuoffsetx, menuoffset) love.graphics.setColor(100, 100, 100, 100*fadecolor) love.graphics.rectangle("fill", 30, 30, 964, 230) gridfadecolor = fadecolor fillfadecolor = fadecolor playerfadecolor = fadecolor local lmap = menumap --ISOMETRIC WORLD if rotation >= pi125 and rotation < pi175 then --DRAW ORDER: X, -Z, Y for cox = 1, menumapwidth do for coz = menumapdepth, 1, -1 do for coy = 1, menumapheight do drawtile(cox, coy, coz, lmap[cox][coy][coz]) end end end elseif rotation >= pi175 or rotation < pi025 then --DRAW ORDER: Z, X, Y for coz = 1, menumapdepth do for cox = 1, menumapwidth do for coy = 1, menumapheight do drawtile(cox, coy, coz, lmap[cox][coy][coz]) end end end elseif rotation >= pi025 and rotation < pi075 then --DRAW ORDER: -X, Z, Y for cox = menumapwidth, 1, -1 do for coz = 1, menumapdepth do for coy = 1, menumapheight do drawtile(cox, coy, coz, lmap[cox][coy][coz]) end end end elseif rotation >= pi075 and rotation < pi125 then --DRAW ORDER: -Z, -X, Y for coz = menumapdepth, 1, -1 do for cox = menumapwidth, 1, -1 do for coy = 1, menumapheight do drawtile(cox, coy, coz, lmap[cox][coy][coz]) end end end end love.graphics.setFont(menufont) if menuoffset < 500 and menuoffset > -650 then --MAIN MENU menubuttons[1]:draw() menubuttons[2]:draw() menubuttons[3]:draw() menubuttons[4]:draw() end if menuoffset > 0 then --LEVEL LIST if menuoffsetx < screenwidth then love.graphics.setFont( levelselectfont ) for i, v in pairs(levelbuttons) do v:draw() end love.graphics.setFont( menufont ) menubuttons[5]:draw() if currentpage ~= pages then menubuttons[10]:draw() end if currentpage ~= 1 then menubuttons[11]:draw() end end end if menuoffset > 0 and menuoffsetx < 0 and menuoffsett == 500 then --win screen love.graphics.setColor(255, 255, 255, 255*fadecolor) for x = 2, 6 do --0-4 love.graphics.draw(winplayerimg, screenwidth+screenwidth/7*x, screenheight/5-500, math.sin(creditss+(x-2)/16*math.pi*2)*0.2, 1, 1, 42, 66) end for y = 2, 4 do --5-7 love.graphics.draw(winplayerimg, screenwidth+screenwidth/7*6, screenheight/5*y-500, math.sin(creditss+(y+3)/16*math.pi*2)*0.2, 1, 1, 42, 66) end for x = 2, 6 do --8-12 love.graphics.draw(winplayerimg, screenwidth+screenwidth/7*(7-x), screenheight/5*4-500, math.sin(creditss+(x+6)/16*math.pi*2)*0.2, 1, 1, 42, 66) end for y = 2, 4 do --13-15 love.graphics.draw(winplayerimg, screenwidth+screenwidth/7, screenheight/5*(5-y)-500, math.sin(creditss+(y+11)/16*math.pi*2)*0.2, 1, 1, 42, 66) end love.graphics.setFont(helpfont) local r, g, b = unpack(getrainbowcolor(math.mod(rainbowi, 1))) love.graphics.setColor(r, g, b, 255*fadecolor) for i = 1, #wintext do love.graphics.print(wintext[i], screenwidth+screenwidth*0.5 - helpfont:getWidth(wintext[i])/2, i*45+150-500) end menubuttons[12]:draw() end if menuoffset < 0 then --ARE YOU SURE? (well are you?) love.graphics.print("Are you sure?", screenwidth/2-areyousurewidth/2, 950) menubuttons[6]:draw() menubuttons[7]:draw() end if menuoffsetx < 0 and menuoffset < 500 then --CREDITS love.graphics.translate(screenwidth+screenwidth/2, (#creditstext-1)*100-70) love.graphics.rotate(creditsr) love.graphics.translate(-screenwidth-screenwidth/2, -(#creditstext-1)*100+70) love.graphics.setColor(100, 100, 100, 100*fadecolor) love.graphics.rectangle("fill", screenwidth*1.5-480, 50, 960, 510) for i = 1, #creditstext do love.graphics.setColor(255, 255, 255, 255*fadecolor) if i == 3 then local r, g, b = unpack(getrainbowcolor(math.mod(rainbowi+.66, 1))) love.graphics.setColor(r, g, b, 255*fadecolor) love.graphics.draw(accentimg, screenwidth*1.5+100, 266) end love.graphics.print(creditstext[i], screenwidth*1.5 - menufont:getWidth(creditstext[i])/2, i*100-50) end love.graphics.setFont(winwindowfont) love.graphics.print("Menu Music: 'Trooped' by BlueAngelEagle Game Music: 'oh' by CapsAdmin", screenwidth+83, 530) love.graphics.setFont(menufont) local r, g, b = unpack(getrainbowcolor(math.mod(rainbowi+.33, 1))) love.graphics.setColor(r, g, b, 255*fadecolor) love.graphics.print("Saso", screenwidth*1.5 + 230, 350) love.graphics.draw(ssssimg, screenwidth*1.5+307, 366) love.graphics.translate(screenwidth+screenwidth/2, (#creditstext-1)*100-70) love.graphics.rotate(-creditsr) love.graphics.translate(-screenwidth-screenwidth/2, -(#creditstext-1)*100+70) menubuttons[8]:draw() end if menuoffsetx > 0 then --HELP --[[love.graphics.setFont(helpfont) for i = 1, #helptext do love.graphics.setColor(255, 255, 255, 255*fadecolor) love.graphics.print(helptext[i], -screenwidth*0.5 - helpfont:getWidth(helptext[i])/2, (i-1)*65+20) end love.graphics.setFont(menufont)--]] love.graphics.setColor(255, 255, 255, 255*fadecolor) love.graphics.draw(helptextimg, -screenwidth, 0) love.graphics.draw(helpplayerimg, -350, 60, creditsr, 1, 1, 28, 64) love.graphics.draw(helpgoalimg, -200, 80) love.graphics.draw(coinimg, -665, 130+creditsr*50, 0, 4, 4) love.graphics.draw(helpcursorimg, -110+math.cos(creditss)*10, 225+math.sin(creditss)*10, 0, 2, 2) love.graphics.draw(helpfswdimg, -900, 380, 0, 1, 1) menubuttons[9]:draw() end love.graphics.translate(-menuoffsetx, -menuoffset) pausebuttons["menutogglesound"]:draw() sizebutton:draw() love.graphics.setFont(winwindowfont) love.graphics.setColor(255, 255, 255, 100*fadecolor) love.graphics.print("2011 Stabyourself.net (v1.1.1)", screenwidth/2-140, 730) love.graphics.setColor(fillcolor[1], fillcolor[2], fillcolor[3], 255) love.graphics.draw(scanlineimg, 0, math.mod(creditss*3, 5)-5) end function loadlevels() filetable = love.filesystem.getDirectoryItems( "maps/" ) for i = 1, #filetable do local path = filetable[i] filetable[i] = {} local v = filetable[i] v.path = path end for i = #filetable, 1, -1 do if string.sub(filetable[i].path, -4 ) ~= ".txt" or filetable[i].path == "menu.txt" then table.remove(filetable, i) end end for i = 1, #filetable do local v = filetable[i] local txtcontents = love.filesystem.read("maps/" .. v.path) v.collectedcoins = {} v.coins = 0 local s1 = txtcontents:split("\n") for i = 1, #s1 do local s2 = s1[i]:split("=") if s2[1] == "name" then v.name = s2[2] elseif s2[1] == "text" then v.text = s2[2] elseif s2[1] == "time" then v.goaltime = tonumber(s2[2]) elseif s2[1] == "steps" then v.goalsteps = tonumber(s2[2]) elseif s2[1] == "warps" then v.goalwarps = tonumber(s2[2]) elseif s2[1] == "coins" then v.coins = tonumber(s2[2]) end end end end function button_start() playsound(proceedsound) menuoffsett = 500 menuoffsetxt = 0 end function button_back() playsound(backsound) menuoffsett = 0 end function button_exit() playsound(proceedsound) menuoffsett = -650 menuoffsetxt = 0 end function button_credits() playsound(proceedsound) menuoffsetxt = -screenwidth menuoffsett = 0 end function button_help() playsound(proceedsound) menuoffsetxt = screenwidth menuoffsett = 0 end function button_no() playsound(backsound) button_back() end function button_yes() menubuttons[6].active = false menubuttons[7].active = false playsound(proceedsound) fadetimer = 1 fadetimert = 0 fadegoal = "quit" end function button_creditsback() playsound(backsound) menuoffsetxt = 0 end function button_prevpage() playsound(backsound) currentpage = currentpage - 1 for i, v in pairs(levelbuttons) do v.xt = v.xt + screenwidth end if menubuttons[10].active == false then menubuttons[10].active = true menubuttons[10].value = 0 end if currentpage == 1 then menubuttons[11].active = false end end function button_nextpage() playsound(proceedsound) currentpage = currentpage + 1 for i, v in pairs(levelbuttons) do v.xt = v.xt - screenwidth end if menubuttons[11].active == false then menubuttons[11].active = true menubuttons[11].value = 0 end if currentpage == pages then menubuttons[10].active = false end end function button_winback() menuoffsetxt = 0 end function startlevel(i) playsound(proceedsound) fadetimert = 0 fadegoal = "startlevel" fadei = i end function newBox(first) local rand = math.random(4) local dir = "hor" if math.mod(rand, 2) == 1 then dir = "ver" end local x, y, width, height local speed = math.random(300, 400) if dir == "hor" then width = math.random(30, 100) height = math.random(10, 20) if first then x = math.random(-screenwidth*3-width, -width) else x = -screenwidth-width end y = math.random(-screenheight, screenheight*2) if rand/2 == 2 then if first then x = math.random(screenwidth, screenwidth*4) else x = screenwidth*2+width end speed = -speed end else width = math.random(10, 20) height = math.random(30, 100) if first then y = math.random(-screenheight*3-height, -height) else y = -screenheight - height end x = math.random(-screenwidth, screenwidth*2) if rand/2 == 1.5 then if first then y = math.random(screenheight, screenheight*4) else y = screenheight*2+height end speed = -speed end end return {x, y, width, height, dir, speed} end function menu_keypressed(key) end function menu_mousepressed(x, y, button) y = y - menuoffset x = x - menuoffsetx for i, v in pairs(levelbuttons) do if v:mousepressed(x, y, button) then return end end for i, v in pairs(menubuttons) do if v:mousepressed(x, y, button) then return end end pausebuttons["menutogglesound"]:mousepressed(x + menuoffsetx, y + menuoffset, button) sizebutton:mousepressed(x + menuoffsetx, y + menuoffset, button) end function menu_togglesound() if soundenabled then soundenabled = false menumusic:stop() pausebuttons["menutogglesound"].text = "Sound OFF" pausebuttons["menutogglesound"].textwidth = levelselectfont:getWidth(pausebuttons["menutogglesound"].text) else soundenabled = true playsound(menumusic) pausebuttons["menutogglesound"].text = "Sound ON" pausebuttons["menutogglesound"].textwidth = levelselectfont:getWidth(pausebuttons["menutogglesound"].text) end end
local assets = { Asset("ANIM", "anim/cave_exit_lightsource.zip"), } local lightColour = {180/255, 195/255, 150/255} local function TurnOn(inst) inst.AnimState:PlayAnimation("on") inst.AnimState:PushAnimation("idle_loop", false) inst.components.lighttweener:StartTween(inst.Light, 0, .9, .9, nil, 0) inst.components.lighttweener:StartTween(inst.Light, 1.5, nil, nil, nil, FRAMES*6) end local function TurnOff(inst) inst.AnimState:PlayAnimation("off") inst.components.lighttweener:StartTween(inst.Light, 0, nil, nil, nil, FRAMES*6) inst:ListenForEvent("animover", function() inst:Remove() end) end local function fn() local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() inst.TurnOn = TurnOn inst.TurnOff = TurnOff anim:SetBank("cavelight") anim:SetBuild("cave_exit_lightsource") inst:AddTag("NOCLICK") local light = inst.entity:AddLight() light:SetRadius(5) light:SetIntensity(0.9) light:SetFalloff(0.3) light:SetColour(lightColour[1], lightColour[2], lightColour[3]) inst:AddComponent("lighttweener") return inst end return Prefab("fx/chesterlight", fn, assets)
local wsmode = 1 local jpmode = 1 local gothrough = false local lotptog = false local bodyang = nil local cameratoggle = false local spintoggle = false local flytoggle = false local scg = Instance.new('ScreenGui',game.Players.LocalPlayer.PlayerGui) scg.ResetOnSpawn = false local frm = Instance.new('Frame',scg) frm.BorderSizePixel = 0 frm.BackgroundColor3 = Color3.new(255/255,122/255,122/255) frm.Size = UDim2.new(0.3,0,0.3,0) frm.Position = UDim2.new(0.35,0,0.35,0) frm.Draggable = true local topl = Instance.new('TextLabel',frm) topl.BorderSizePixel = 0 topl.BackgroundColor3 = Color3.new(255/255,70/255,70/255) topl.Size = UDim2.new(0.9,1,0.2,0) topl.Position = UDim2.new(0,0,0,0) topl.TextScaled = true topl.Font = "SourceSansLight" topl.TextColor3 = Color3.new(1,1,1) topl.Text = "Newbie's FE Gui V1.1" topl.Draggable = true local scrl = Instance.new('ScrollingFrame',frm) scrl.BorderSizePixel = 0 scrl.BackgroundColor3 = Color3.new(255/255,122/255,122/255) scrl.Size = UDim2.new(1,0,0.8,0) scrl.Position = UDim2.new(0,0,0.2,0) scrl.BottomImage = "rbxasset://textures/ui/Scroll/scroll-middle.png" scrl.TopImage = "rbxasset://textures/ui/Scroll/scroll-middle.png" local plr = Instance.new('TextBox',scrl) plr.BorderSizePixel = 0 plr.BackgroundColor3 = Color3.new(255/255,150/255,150/255) plr.Size = UDim2.new(0.425,0,0.1,0) plr.Position = UDim2.new(0.05,0,0.025,0) plr.TextScaled = true plr.Font = "SourceSansLight" plr.TextColor3 = Color3.new(1,1,1) plr.Text = "Player Name Here" local plrsp = Instance.new('TextButton',scrl) plrsp.BorderSizePixel = 0 plrsp.BackgroundColor3 = Color3.new(255/255,70/255,70/255) plrsp.Size = UDim2.new(0.425,0,0.1,0) plrsp.Position = UDim2.new(0.5,0,0.025,0) plrsp.TextScaled = true plrsp.Font = "SourceSansLight" plrsp.TextColor3 = Color3.new(1,1,1) plrsp.Text = "Spawn Blocks" local minim = Instance.new('TextButton',frm) minim.BorderSizePixel = 0 minim.BackgroundColor3 = Color3.new(200/255,50/255,50/255) minim.Size = UDim2.new(0.1,0,0.2,0) minim.Position = UDim2.new(0.9,0,0,0) minim.TextScaled = true minim.Font = "SourceSansLight" minim.TextColor3 = Color3.new(1,1,1) minim.Text = "-" function sblock() for i=1,20 do wait(1) for _,v in pairs(game.Players.LocalPlayer.Backpack:GetChildren()) do if v:IsA'Accoutrement' then v.Parent=game.Players.LocalPlayer.Character v.Parent = workspace.Terrain end end for i,v in pairs(game.Players.LocalPlayer.Character:GetChildren()) do if v:IsA'Accoutrement' then for ape,hax in pairs(v.Handle:GetChildren()) do hax:Destroy() end wait'.1' v.Parent=game.Players.LocalPlayer.StarterGear end end for _,v in pairs(game.Players.LocalPlayer.Character:GetChildren()) do v:Destroy() end local prt=Instance.new("Model", workspace); Instance.new("Part", prt).Name="Torso"; Instance.new("Part", prt).Name="Head"; Instance.new("Humanoid", prt).Name="Humanoid"; game.Players.LocalPlayer.Character=prt repeat wait(1) until game.Players.LocalPlayer.Character:FindFirstChild'Head' for lol,dad in pairs(game.Players.LocalPlayer.Backpack:GetChildren()) do if dad:IsA'Accoutrement' then dad.Parent = game.Players.LocalPlayer.StarterGear end end for _,v in pairs(game.Players.LocalPlayer.Character:GetChildren()) do v:Destroy() end local prt2=Instance.new("Model", workspace); Instance.new("Part", prt).Name="Torso"; Instance.new("Part", prt).Name="Head"; Instance.new("Humanoid", prt).Name="Humanoid"; game.Players.LocalPlayer.Character=prt end end plrsp.MouseButton1Click:connect(sblock) local spin = Instance.new('TextButton',scrl) spin.BorderSizePixel = 0 spin.BackgroundColor3 = Color3.new(255/255,70/255,70/255) spin.Size = UDim2.new(0.425,0,0.1,0) spin.Position = UDim2.new(0.05,0,0.15,0) spin.TextScaled = true spin.Font = "SourceSansLight" spin.TextColor3 = Color3.new(1,1,1) spin.Text = "Crazy Spin: OFF" local fly = Instance.new('TextButton',scrl) fly.BorderSizePixel = 0 fly.BackgroundColor3 = Color3.new(255/255,70/255,70/255) fly.Size = UDim2.new(0.425,0,0.1,0) fly.Position = UDim2.new(0.5,0,0.15,0) fly.TextScaled = true fly.Font = "SourceSansLight" fly.TextColor3 = Color3.new(1,1,1) fly.Text = "Fly: OFF" local seethr = Instance.new('TextButton',scrl) seethr.BorderSizePixel = 0 seethr.BackgroundColor3 = Color3.new(255/255,70/255,70/255) seethr.Size = UDim2.new(0.425,0,0.1,0) seethr.Position = UDim2.new(0.05,0,0.275,0) seethr.TextScaled = true seethr.Font = "SourceSansLight" seethr.TextColor3 = Color3.new(1,1,1) seethr.Text = "See-Through: OFF" local tpto = Instance.new('TextButton',scrl) tpto.BorderSizePixel = 0 tpto.BackgroundColor3 = Color3.new(255/255,70/255,70/255) tpto.Size = UDim2.new(0.425,0,0.1,0) tpto.Position = UDim2.new(0.5,0,0.275,0) tpto.TextScaled = true tpto.Font = "SourceSansLight" tpto.TextColor3 = Color3.new(1,1,1) tpto.Text = "Teleport To" local ws = Instance.new('TextButton',scrl) ws.BorderSizePixel = 0 ws.BackgroundColor3 = Color3.new(255/255,70/255,70/255) ws.Size = UDim2.new(0.425,0,0.1,0) ws.Position = UDim2.new(0.05,0,0.4,0) ws.TextScaled = true ws.Font = "SourceSansLight" ws.TextColor3 = Color3.new(1,1,1) ws.Text = "WalkSpeed: Normal" local jp = Instance.new('TextButton',scrl) jp.BorderSizePixel = 0 jp.BackgroundColor3 = Color3.new(255/255,70/255,70/255) jp.Size = UDim2.new(0.425,0,0.1,0) jp.Position = UDim2.new(0.5,0,0.4,0) jp.TextScaled = true jp.Font = "SourceSansLight" jp.TextColor3 = Color3.new(1,1,1) jp.Text = "JumpPower: Normal" local lotp = Instance.new('TextButton',scrl) lotp.BorderSizePixel = 0 lotp.BackgroundColor3 = Color3.new(255/255,70/255,70/255) lotp.Size = UDim2.new(0.425,0,0.1,0) lotp.Position = UDim2.new(0.05,0,0.525,0) lotp.TextScaled = true lotp.Font = "SourceSansLight" lotp.TextColor3 = Color3.new(1,1,1) lotp.Text = "Loop-Teleport: OFF" local sb = Instance.new('TextButton',scrl) sb.BorderSizePixel = 0 sb.BackgroundColor3 = Color3.new(255/255,70/255,70/255) sb.Size = UDim2.new(0.425,0,0.1,0) sb.Position = UDim2.new(0.5,0,0.525,0) sb.TextScaled = true sb.Font = "SourceSansLight" sb.TextColor3 = Color3.new(1,1,1) sb.Text = "Noclip" local cr = Instance.new('TextLabel',scrl) cr.BorderSizePixel = 0 cr.BackgroundColor3 = Color3.new(255/255,70/255,70/255) cr.Size = UDim2.new(0.875,0,0.225,0) cr.Position = UDim2.new(0.05,0,0.65,0) cr.TextScaled = true cr.Font = "SourceSansLight" cr.TextColor3 = Color3.new(1,1,1) cr.Text = "Gui Created by Newbie15. Credit Goes to RGeeneus/Ignoramical for the Fly Script and Natural Modder for leaking the block spam script. but most importantly credits go to the users of this Gui." local fl = Instance.new('TextLabel',scrl) fl.BorderSizePixel = 0 fl.BackgroundColor3 = Color3.new(255/255,70/255,70/255) fl.Size = UDim2.new(0.875,0,0.075,0) fl.Position = UDim2.new(0.05,0,0.9,0) fl.TextScaled = true fl.Font = "SourceSansLight" fl.TextColor3 = Color3.new(1,1,1) if game.Workspace.FilteringEnabled == true then fl.Text = "Filtering is Enabled" else fl.Text = "Filtering is Disabled" end local gui2 = Instance.new('ScreenGui',game.Players.LocalPlayer.PlayerGui) gui2.ResetOnSpawn = false local oc = Instance.new('TextButton',gui2) oc.BorderSizePixel = 0 oc.BackgroundColor3 = Color3.new(255/255,70/255,70/255) oc.Size = UDim2.new(0,50,0,50) oc.Position = UDim2.new(0,0,0,0) oc.TextScaled = true oc.Font = "SourceSansLight" oc.TextColor3 = Color3.new(1,1,1) oc.Text = "Close" oc.Draggable = true -- FLY SCRIPT BY RGEENEUS -- The following code should be in a local script. -- Only works on PC, not xbox or mobile. I do not have devices to test on. -- Call the start fly function AFTER the character exists to fly. The function does not run if there is no character. local speed = 50 -- This is the fly speed. Change it to whatever you like. The variable can be changed while running local c local h local bv local bav local cam local flying local p = game.Players.LocalPlayer local buttons = {W = false, S = false, A = false, D = false, Moving = false} local startFly = function () -- Call this function to begin flying if not p.Character or not p.Character.Head or flying then return end c = p.Character h = c.Humanoid h.PlatformStand = true cam = workspace:WaitForChild('Camera') bv = Instance.new("BodyVelocity") bav = Instance.new("BodyAngularVelocity") bv.Velocity, bv.MaxForce, bv.P = Vector3.new(0, 0, 0), Vector3.new(10000, 10000, 10000), 1000 bav.AngularVelocity, bav.MaxTorque, bav.P = Vector3.new(0, 0, 0), Vector3.new(10000, 10000, 10000), 1000 bv.Parent = c.Head bav.Parent = c.Head flying = true h.Died:connect(function() flying = false end) end local endFly = function () -- Call this function to stop flying if not p.Character or not flying then return end h.PlatformStand = false bv:Destroy() bav:Destroy() flying = false end game:GetService("UserInputService").InputBegan:connect(function (input, GPE) if GPE then return end for i, e in pairs(buttons) do if i ~= "Moving" and input.KeyCode == Enum.KeyCode[i] then buttons[i] = true buttons.Moving = true end end end) game:GetService("UserInputService").InputEnded:connect(function (input, GPE) if GPE then return end local a = false for i, e in pairs(buttons) do if i ~= "Moving" then if input.KeyCode == Enum.KeyCode[i] then buttons[i] = false end if buttons[i] then a = true end end end buttons.Moving = a end) local setVec = function (vec) return vec * (speed / vec.Magnitude) end game:GetService("RunService").Heartbeat:connect(function (step) -- The actual fly function, called every frame if flying and c and c.PrimaryPart then local p = c.PrimaryPart.Position local cf = cam.CFrame local ax, ay, az = cf:toEulerAnglesXYZ() c:SetPrimaryPartCFrame(CFrame.new(p.x, p.y, p.z) * CFrame.Angles(ax, ay, az)) if buttons.Moving then local t = Vector3.new() if buttons.W then t = t + (setVec(cf.lookVector)) end if buttons.S then t = t - (setVec(cf.lookVector)) end if buttons.A then t = t - (setVec(cf.rightVector)) end if buttons.D then t = t + (setVec(cf.rightVector)) end c:TranslateBy(t * step) end end end) function spintogl() if spintoggle == true then spintoggle = false spin.Text = "Crazy Spin: OFF" else spintoggle = true spin.Text = "Crazy Spin: ON" local bodyang = Instance.new('BodyAngularVelocity',game.Players.LocalPlayer.Character.PrimaryPart) bodyang.AngularVelocity = Vector3.new(90,999,0) bodyang.MaxTorque = Vector3.new(60000,100,3000) bodyang.P = 5000000 repeat wait(0.001) until spintoggle == false bodyang:Destroy() end end spin.MouseButton1Click:connect(spintogl) function flytogl() if flytoggle == true then flytoggle = false fly.Text = "Fly: OFF" else flytoggle = true fly.Text = "Fly: ON" startFly() repeat wait(0.001) until flytoggle == false endFly() end end fly.MouseButton1Click:connect(flytogl) function opctogl() if scg.Enabled == true then scg.Enabled = false oc.Text = "Open" else scg.Enabled = true oc.Text = "Close" end end oc.MouseButton1Click:connect(opctogl) function telep() game.Players.LocalPlayer.Character:MoveTo(game.Players:FindFirstChild(plr.Text).Character.PrimaryPart.Position) end tpto.MouseButton1Click:connect(telep) function camtogl() if cameratoggle == false then cameratoggle = true game.Workspace.CurrentCamera.CameraType = "Follow" seethr.Text = "See-Through: ON" else cameratoggle = false game.Workspace.CurrentCamera.CameraType = "Custom" seethr.Text = "See-Through: OFF" end end seethr.MouseButton1Click:connect(camtogl) function wsp() if wsmode ~= 5 then wsmode = wsmode + 1 else wsmode = 1 end if wsmode == 1 then ws.Text = "WalkSpeed: Normal" game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 16 end if wsmode == 2 then ws.Text = "WalkSpeed: Fast" game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 32 end if wsmode == 3 then ws.Text = "WalkSpeed: FASTER" game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 70 end if wsmode == 4 then ws.Text = "WalkSpeed: EXTREME" game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 150 end if wsmode == 5 then ws.Text = "WalkSpeed: The Speed of Light" game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 4357234785243 end end ws.MouseButton1Click:connect(wsp) function jpp() if jpmode ~= 5 then jpmode = jpmode + 1 else jpmode = 1 end if jpmode == 1 then jp.Text = "JumpPower: Normal" game.Players.LocalPlayer.Character.Humanoid.JumpPower = 50 end if jpmode == 2 then jp.Text = "JumpPower: Trampoline" game.Players.LocalPlayer.Character.Humanoid.JumpPower = 100 end if jpmode == 3 then jp.Text = "JumpPower: Big Trampoline" game.Players.LocalPlayer.Character.Humanoid.JumpPower = 200 end if jpmode == 4 then jp.Text = "JumpPower: Bigger Trampoline" game.Players.LocalPlayer.Character.Humanoid.JumpPower = 400 end if jpmode == 5 then jp.Text = "JumpPower: Bounce into Heaven" game.Players.LocalPlayer.Character.Humanoid.JumpPower = 80000 end end jp.MouseButton1Click:connect(jpp) function spawnblock() if gothrough == false then gothrough = true sb.Text = "Noclip" local gc = game.Players.LocalPlayer.Character:GetChildren() for i = 1,#gc,1 do if (gc[i].ClassName == "Part") or (gc[i].ClassName == "MeshPart") then gc[i].CollisionGroupId = 29 end end game:service("RunService").Stepped:wait() else gothrough = false sb.Text = "Noclip" local gc = game.Players.LocalPlayer.Character:GetChildren() for i = 1,#gc,1 do if (gc[i].ClassName == "Part") or (gc[i].ClassName == "MeshPart") then gc[i].CollisionGroupId = 1 game:service("RunService").Stepped:wait() end end end end sb.MouseButton1Click:connect(spawnblock) function looptelep() if lotptog == false then lotptog = true lotp.Text = "Loop-Teleport: ON" repeat game.Players.LocalPlayer.Character:MoveTo(game.Players:FindFirstChild(plr.Text).Character.PrimaryPart.Position) wait(0.001) until lotptog == false else lotptog = false lotp.Text = "Loop-Teleport: OFF" end end lotp.MouseButton1Click:connect(looptelep) function minimi() scg.Enabled = false oc.Text = "Open" end minim.MouseButton1Click:connect(minimi)
if not modules then modules = { } end modules ['luatex-font-mis'] = { version = 1.001, comment = "companion to luatex-*.tex", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } if context then os.exit() end local currentfont = font.current local hashes = fonts.hashes local identifiers = hashes.identifiers or { } local marks = hashes.marks or { } hashes.identifiers = identifiers hashes.marks = marks table.setmetatableindex(marks,function(t,k) if k == true then return marks[currentfont()] else local resources = identifiers[k].resources or { } local marks = resources.marks or { } t[k] = marks return marks end end) function font.each() return table.sortedhash(fonts.hashes.identifiers) end
local sound = require 'vendor/TEsound' local Dialog = require 'dialog' local Timer = require 'vendor/timer' local Gamestate = require 'vendor/gamestate' local Prompt = require 'prompt' local fonts = require 'fonts' local Dealer = {} Dealer.__index = Dealer -- Nodes with 'isInteractive' are nodes which the player can interact with, but not pick up in any way Dealer.isInteractive = true function Dealer.new(node, collider) local dealer = {} setmetatable(dealer, Dealer) dealer.x = node.x dealer.y = node.y dealer.height = node.height dealer.width = node.width dealer.bb = collider:addRectangle(node.x, node.y, node.width, node.height) dealer.bb.node = dealer collider:setPassive(dealer.bb) return dealer end function Dealer:enter(previous) fonts.reset() --Dealer says "Let's play poker" after a few seconds when player enters the tavern. if not self.dialog then self.dialog = Timer.add(math.random(3,4), function() self.poker_dialog = Dialog.new("Let's play {{yellow}}poker{{white}}.") sound.playSfx("letsPlayPoker") end) end end function Dealer:leave() --The timers are canceled upon leaving so the dialog and sound don't occur outside the tavern. Timer.cancel(self.dialog) if self.poker_dialog then self.poker_dialog:close() end end function Dealer:keypressed( button, player ) if button == 'INTERACT' then player.freeze = true --Timers for "Let's play poker" cancel upon interaction with the dealer. Timer.cancel(self.dialog) local message = {'Choose a card game to play'} local options = {'Poker', 'Blackjack', 'Exit'} if player.money == 0 then message = {'You dont have enough money!','Come back again...'} options = {'Exit'} end local callback = function(result) self.prompt = nil player.freeze = false if result == 'Poker' or result == 'Blackjack' then local screenshot = love.graphics.newImage( love.graphics.newScreenshot() ) Gamestate.stack(result:lower() .. 'game', player, screenshot) end end self.prompt = Prompt.new(message, callback, options) return true end end return Dealer
-- misc. functions supplementing os table -- utility metatable for making tables key-weak aux.weak_k_mt = { __mode = "k" } -- utility metatable for making tables fully weak aux.weak_mt = { __mode = "kv" } -- code to normalize paths function aux.absPath(path) local dir, name = path:match("^(.-/?)([^/]-)$") if #dir == 0 then --TODO: we presumably want to use some default directory -- in these cases besides cwd dir = "./" end -- normalize directory, including a trailing slash -- (but leave "/" as-is, not "//") dir = aux.cAbsPath(dir):gsub("^(.-)/?$", "%1/") path = dir .. name return path, dir end function aux.resolvePath(base, path) if path:match("^/") then return path end return base .. "/" .. path end -- code for shutting down cleanly aux.exitHooks = {} function aux.addExitHook(hook) aux.exitHooks[#aux.exitHooks + 1] = hook end function aux.shutdown() for i = 1,#aux.exitHooks do aux.exitHooks[i]() end os.exit() end
jedi_earings = { description = "", minimumLevel = 0, maximumLevel = 0, lootItems = { {itemTemplate = "earingLST", weight = 3500000}, {itemTemplate = "ch_earing", weight = 3000000}, {itemTemplate = "earingJT", weight = 3500000} } } addLootGroupTemplate("jedi_earings", jedi_earings)
object_tangible_loot_creature_loot_collections_treasure_hunter_stone_03 = object_tangible_loot_creature_loot_collections_shared_treasure_hunter_stone_03:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_treasure_hunter_stone_03, "object/tangible/loot/creature/loot/collections/treasure_hunter_stone_03.iff")
AddCSLuaFile() DEFINE_BASECLASS("emod_base") EMod.RegisterComponent(ENT, "E-Battery", EMod.ComponentsTypes.Source, "Energy Sources", true, "EMod Official Pack") function ENT:EModSetup() self:AddPin(EMod.Plus, Vector(-4.902077, -6.536953, 1.198760)) self:AddPin(EMod.Zero, Vector(-4.902195, 6.757458, 1.200500)) self:AddScheme(1,nil) self:AddScheme(2,nil) self.State = false if SERVER then self:SetUseType(SIMPLE_USE) end self:EModSetModel("models/Items/car_battery01.mdl") end function ENT:EModSettings(settings) self:EModSetModel(settings.model) end function ENT:Use(_, caller) self.State = not self.State self:EmitSound("buttons/button14.wav", 75, 150) end -- if SERVER then -- function ENT:Initialize() -- self:SetModel("models/Items/car_battery01.mdl") -- self:PhysicsInit(SOLID_VPHYSICS) -- self:SetMoveType(MOVETYPE_VPHYSICS) -- self:SetSolid(SOLID_VPHYSICS) -- self:SetUseType(SIMPLE_USE) -- self:PhysWake() -- self:SetCollisionGroup(COLLISION_GROUP_NONE) -- self.Temperature = 25.0 -- self:SetCapacity(1000) -- self:SetAvailable(1000) -- self:RegisterCallback(2,function(edata) -- if edata.I == math.huge then -- util.BlastDamage(self:GetPlayer() or self.Player,self:GetPlayer() or self.Player,self:GetPos()+Vector(0,0,100),100,50) self.Think = nil -- local effectdata = EffectData() -- effectdata:SetOrigin(self:GetPos()) -- util.Effect( "Explosion", effectdata ) -- self:Remove() -- return -- end -- EModPerformDischarge(self,edata.I) -- if self:GetAvailable() == 0 or edata.I == 0 then return end -- self:MakeTick(edata) -- end) -- end -- function ENT:Use(_,caller) -- self:SetState(!self:GetState()) -- self:EmitSound("buttons/button14.wav",75,150) -- end -- function ENT:Think() -- if self:GetState() then -- self:FlowCurrent(1,{ChargeOwner=self,ChargeID=SysTime(),Route={},I=math.huge,U=58}) -- self:NextThink(CurTime() + EMODTick) -- return true -- end -- end -- end -- if CLIENT then -- function ENT:Think() -- if self:GetState() then -- local dlight = DynamicLight(self:EntIndex()) -- if ( dlight ) then -- dlight.pos = self:LocalToWorld(Vector(0,0,10)) -- dlight.r = self:GetAvailable() == 0 and 100 or 0 -- dlight.g = self:GetAvailable() != 0 and 100 or 0 -- dlight.b = 0 -- dlight.brightness = 1 -- dlight.Decay = 0 -- dlight.Size = 100 -- dlight.DieTime = CurTime() + EMODTick -- end -- end -- end -- function ENT:Draw() -- self:DrawModel() -- cam.Start3D2D(self:LocalToWorld(Vector(-4,5.4,4.7)),self:LocalToWorldAngles(Angle(0,0,0)),0.1) -- local percent = self:GetAvailable()*100/self:GetCapacity() -- local light = GetLightAmount(self:GetPos()) -- draw.RoundedBox(2,0,53*(percent/100),35,53-53*(percent/100),Color(255,0,0,light)) -- draw.RoundedBox(2,0,0,35,53*(percent/100),Color(0,255,0,light)) -- -- draw.SimpleText(math.Round(self:GetAvailable(),3),"DermaLarge",50,50,Color(255,255,255),1,1) |Debug| -- cam.End3D2D() -- end -- end -- function ENT:SetupDataTables() -- self:NetworkVar("Bool",0,"State") -- self:NetworkVar("Float",0,"Capacity") -- self:NetworkVar("Float",1,"Available") -- if SERVER then -- self:SetState(false) -- end -- end
local ffi = require( "ffi" ) -- Normal bindings local overlay = require "ffi.overlay" -- Kbd table local kbd = {} function kbd.keyboardIterator(keyboards) local current = 0 return function() if current == 0 then -- The first element. current = keyboards.keyboards else -- Elements after the current one. current = current.next end -- Only if there is a keyboard - the iterator is over in any other case. if current ~= nil then return current end end end return kbd
for i = 1, 10, 2 do print(i) end local obj = { } obj[1] = 3.14 obj[2] = "nihaop" -- print(obj[1]) -- print(obj["1"]) print(obj[2.0]) -- assert(obj[1] == 13.14)
ENT.Type = 'anim' ENT.Base = 'bw_machine_base' ENT.PrintName = 'Drink Mixer' ENT.Author = 'n00bmobile' ENT.Category = 'n00bmobile' ENT.Spawnable = true ENT.AdminSpawnable = true --[Customizable Values]-- ENT.MaxPower = 100 ENT.Cooldown = 600 ------------------------- function ENT:SetupDataTables() self:NetworkVar('Bool', 0, 'TurnedOn') self:NetworkVar('Int', 0, 'PowerStored') self:NetworkVar('Int', 1, 'Countdown') if SERVER then self:SetCountdown(self.Cooldown) end end if CLIENT then ENT.StatusBars = { [1] = { name = 'HEALTH', color = Color(255, 0, 0), getWidth = function(ent) return 186 *(ent:Health() /ent:GetMaxHealth()) end }, [2] = { name = 'DRINK', color = Color(0, 255, 255), getWidth = function(ent) local countdown = ent:GetCountdown() if countdown == 0 then ent.StatusBars[2].name = 'DRINK READY' else ent.StatusBars[2].name = 'DRINK ('..string.ToMinutesSeconds(countdown)..')' end return 186 -186 *(countdown /ent.Cooldown) end } } end
local _, ns = ... ns.L = {} local localizations = {} local locale = GetLocale() setmetatable(ns.L, { __call = function(_, newLocale) localizations[newLocale] = {} return localizations[newLocale] end, __index = function(_, key) local localeTable = localizations[locale] return localeTable and localeTable[key] or tostring(key) end })
-- slb_racing trigger ENT.Base = "base_entity" ENT.Type = "brush" function ENT:Initialize() end function ENT:StartTouch( entity ) if entity:IsPlayer() then entity:SetNetworkedBool( "IsRacing", true ) entity:SetTeam(TEAM_RACING) end if not entity:IsPlayer() then local phys = entity:GetPhysicsObject() if ( phys && phys:IsValid() ) then phys:SetMaterial("gmod_ice") end end end function ENT:EndTouch( entity ) if entity:IsPlayer() then entity:SetTeam(TEAM_BUILDING) entity:SetNetworkedBool( "IsRacing", false ) end local phys = entity:GetPhysicsObject() if ( phys && phys:IsValid() && !entity:IsPlayer() ) then phys:SetMaterial("dirt") -- Reset physprops when not racing. end end function ENT:Touch( entity ) -- we don't want to use this function... server lag. end /*--------------------------------------------------------- Name: PassesTriggerFilters Desc: Return true if this object should trigger us ---------------------------------------------------------*/ function ENT:PassesTriggerFilters( entity ) return true end /*--------------------------------------------------------- Name: KeyValue Desc: Called when a keyvalue is added to us ---------------------------------------------------------*/ function ENT:KeyValue( key, value ) end /*--------------------------------------------------------- Name: Think Desc: Entity's think function. ---------------------------------------------------------*/ function ENT:Think() end /*--------------------------------------------------------- Name: OnRemove Desc: Called just before entity is deleted ---------------------------------------------------------*/ function ENT:OnRemove() end
local Input = {} local self = Input -- TODO: rebinding Input.key_down = {} Input.key_pressed = {} Input.key_released = {} Input.aliases = { ["up"] = {"up"}, ["down"] = {"down"}, ["left"] = {"left"}, ["right"] = {"right"}, ["confirm"] = {"z", "return"}, ["cancel"] = {"x", "lshift", "rshift"}, ["menu"] = {"c", "lctrl", "rctrl"} } Input.lock_stack = {} function Input.clearPressed() self.key_pressed = {} self.key_released = {} end function Input.lock(target) table.insert(self.lock_stack, target) end function Input.release(target) if not target then table.remove(self.lock_stack, #self.lock_stack) else Utils.removeFromTable(self.lock_stack, target) end end function Input.check(target) return self.lock_stack[#self.lock_stack] == target end function Input.onKeyPressed(key) self.key_down[key] = true self.key_pressed[key] = true end function Input.onKeyReleased(key) self.key_down[key] = false self.key_released[key] = true end function Input.down(key) if self.aliases[key] then for _,k in ipairs(self.aliases[key]) do if self.key_down[k] then return true end end return false else return self.key_down[key] end end function Input.keyDown(key) return self.key_down[key] end function Input.pressed(key) if self.aliases[key] then for _,k in ipairs(self.aliases[key]) do if self.key_pressed[k] then return true end end return false else return self.key_down[key] end end function Input.keyPressed(key) return self.key_pressed[key] end function Input.released(key) if self.aliases[key] then for _,k in ipairs(self.aliases[key]) do if self.key_released[k] then return true end end return false else return self.key_released[key] end end function Input.keyReleased(key) return self.key_released[key] end function Input.up(key) if self.aliases[key] then for _,k in ipairs(self.aliases[key]) do if self.key_down[k] then return false end end return true else return not self.key_down[key] end end function Input.keyUp(key) return not self.key_down[key] end function Input.is(alias, key) return self.aliases[alias] and Utils.containsValue(self.aliases[alias], key) end function Input.getText(alias) local name = self.aliases[alias] and self.aliases[alias][1] or alias return "["..name:upper().."]" end function Input.isConfirm(key) return Utils.containsValue(self.aliases["confirm"], key) end function Input.isCancel(key) return Utils.containsValue(self.aliases["cancel"], key) end function Input.isMenu(key) return Utils.containsValue(self.aliases["menu"], key) end function Input.getMousePosition() return love.mouse.getX() / (Kristal.Config["windowScale"] or 1), love.mouse.getY() / (Kristal.Config["windowScale"] or 1) end return Input
local Model = require "meiru.db.model" local Session = Model("Session") function Session:ctor() -- log("Session:ctor id =",self.id) end return Session
-- Tencent is pleased to support the open source community by making LuaPanda available. -- Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. -- Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -- https://opensource.org/licenses/BSD-3-Clause -- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- API: -- LuaPanda.printToVSCode(logStr, printLevel, type) -- 打印日志到VSCode Output下 LuaPanda Debugger 中 -- @printLevel: debug(0)/info(1)/error(2) 这里的日志等级需高于launch.json中配置等级日志才能输出 (可选参数,默认0) -- @type(可选参数,默认0): 0:VSCode output console 1:VSCode tip 2:VSCode debug console -- LuaPanda.BP() -- 强制打断点,可以在协程中使用。建议使用以下写法: -- local ret = LuaPanda and LuaPanda.BP and LuaPanda.BP(); -- 如果成功加入断点ret返回true,否则是nil -- LuaPanda.getInfo() -- 返回获取调试器信息。包括版本号,是否使用lib库,系统是否支持loadstring(load方法)。返回值类型string, 推荐在调试控制台中使用。 -- LuaPanda.testBreakpoint() -- 测试断点,用于分析路径错误导致断点无法停止的情况。测试方法是 -- 1. launch.json 中开启 stopOnEntry, 或者在代码中加入LuaPanda.BP()。 -- 2. 运行调试器和 lua 进程,当停止在 stopOnEntry 或者 LuaPanda.BP() 时在调试控制台输入 LuaPanda.testBreakpoint() -- 3. 根据提示更新断点后再次输入 LuaPanda.testBreakpoint()。此时系统会输出一些提示,帮助用户分析断点可能无法停止的原因。 -- LuaPanda.doctor() -- 返回对当前环境的诊断信息,提示可能存在的问题。返回值类型string, 推荐在调试控制台中使用。 -- LuaPanda.getBreaks() -- 获取断点信息,推荐在调试控制台中使用。 -- LuaPanda.serializeTable(table) -- 把table序列化为字符串,返回值类型是string。 -- LuaPanda.stopAttach() -- 断开连接,停止attach,本次被调试程序运行过程无法再次进行attach连接。 -- 其他说明: -- 关于真机调试,首次使用真机调试时要注意下方"用户设置项"中的配置 -- 1. 确定 attach 开关打开: openAttachMode = true; 这样可以避免先启动手机app之后启动调试器无法连接。 -- 2. 把连接时间放长: connectTimeoutSec 设置为 0.5 或者 1。首次尝试真机调试时这个值可以设置大一点,之后再根据自己的网络状况向下调整。 -- 调试方法可以参考 github 文档 --用户设置项 local openAttachMode = true; --是否开启attach模式。attach模式开启后可以在任意时刻启动vscode连接调试。缺点是没有连接调试时也会略降低lua执行效率(会不断进行attach请求) local attachInterval = 1; --attach间隔时间(s) local connectTimeoutSec = 0.005; --lua进程作为Client时, 连接超时时间, 单位s. 时间过长等待attach时会造成卡顿,时间过短可能无法连接。建议值0.005 - 0.05 local listeningTimeoutSec = 0.5; -- lua进程作为Server时,连接超时时间, 单位s. 时间过长等待attach时会造成卡顿,时间过短可能无法连接。建议值0.1 - 1 local userDotInRequire = true; --兼容require中使用 require(a.b) 和 require(a/b) 的形式引用文件夹中的文件,默认无需修改 local traversalUserData = false; --如果可以的话(取决于userdata原表中的__pairs),展示userdata中的元素。 如果在调试器中展开userdata时有错误,请关闭此项. local customGetSocketInstance = nil; --支持用户实现一个自定义调用luasocket的函数,函数返回值必须是一个socket实例。例: function() return require("socket.core").tcp() end; local consoleLogLevel = 2; --打印在控制台(print)的日志等级 0 : all/ 1: info/ 2: error. --用户设置项END local debuggerVer = "3.2.0"; --debugger版本号 LuaPanda = {}; local this = LuaPanda; local tools = {}; --引用的开源工具,包括json解析和table展开工具等 this.tools = tools; this.curStackId = 0; --json处理 local json; --hook状态列表 local hookState = { DISCONNECT_HOOK = 0, --断开连接 LITE_HOOK = 1, --全局无断点 MID_HOOK = 2, --全局有断点,本文件无断点 ALL_HOOK = 3, --本文件有断点 }; --运行状态列表 local runState = { DISCONNECT = 0, --未连接 WAIT_CMD = 1, --已连接,等待命令 STOP_ON_ENTRY = 2, --初始状态 RUN = 3, STEPOVER = 4, STEPIN = 5, STEPOUT = 6, STEPOVER_STOP = 7, STEPIN_STOP = 8, STEPOUT_STOP = 9, HIT_BREAKPOINT = 10 }; local TCPSplitChar = "|*|"; --json协议分隔符,请不要修改 local MAX_TIMEOUT_SEC = 3600 * 24; --网络最大超时等待时间 --当前运行状态 local currentRunState; local currentHookState; --断点信息 local breaks = {}; --保存断点的数组 this.breaks = breaks; --供hookLib调用 local recCallbackId = ""; --VSCode端传过来的配置,在VSCode端的launch配置,传过来并赋值 local luaFileExtension = ""; --vscode传过来的脚本后缀 local cwd = ""; --工作路径 local DebuggerFileName = ""; --Debugger文件名(原始,未经path处理), 函数中会自动获取 local DebuggerToolsName = ""; local lastRunFunction = {}; --上一个执行过的函数。在有些复杂场景下(find,getcomponent)一行会挺两次 local currentCallStack = {}; --获取当前调用堆栈信息 local hitBP = false; --BP()中的强制断点命中标记 local TempFilePath_luaString = ""; --VSCode端配置的临时文件存放路径 local recordHost; --记录连接端IP local recordPort; --记录连接端口号 local sock; --lua socket 文件描述符 local server; --server 描述符 local OSType; --VSCode识别出的系统类型,也可以自行设置。Windows_NT | Linux | Darwin local clibPath; --chook库在VScode端的路径,也可自行设置。 local hookLib; --chook库的引用实例 local adapterVer; --VScode传来的adapter版本号 local truncatedOPath; --VScode中用户设置的用于截断opath路径的标志,注意这里可以接受lua魔法字符 local distinguishSameNameFile = false; --是否区分lua同名文件中的断点,在VScode launch.json 中 distinguishSameNameFile 控制 --标记位 local logLevel = 1; --日志等级all/info/error. 此设置对应的是VSCode端设置的日志等级. local variableRefIdx = 1; --变量索引 local variableRefTab = {}; --变量记录table local lastRunFilePath = ""; --最后执行的文件路径 local pathCaseSensitivity = true; --路径是否发大小写敏感,这个选项接收VScode设置,请勿在此处更改 local recvMsgQueue = {}; --接收的消息队列 local coroutinePool = {}; --保存用户协程的队列 local winDiskSymbolUpper = false;--设置win下盘符的大小写。以此确保从VSCode中传入的断点路径,cwd和从lua虚拟机获得的文件路径盘符大小写一致 local isNeedB64EncodeStr = false;-- 记录是否使用base64编码字符串 local loadclibErrReason = 'launch.json文件的配置项useCHook被设置为false.'; local OSTypeErrTip = ""; local pathErrTip = "" local winDiskSymbolTip = ""; local isAbsolutePath = false; local stopOnEntry; --用户在VSCode端设置的是否打开stopOnEntry local userSetUseClib; --用户在VSCode端设置的是否是用clib库 local autoPathMode = false; local autoExt; --调试器启动时自动获取到的后缀, 用于检测lua虚拟机返回的路径是否带有文件后缀。他可以是空值或者".lua"等 local luaProcessAsServer; local testBreakpointFlag = false; -- 测试断点的标志位。结合 LuaPanda.testBreakpoint() 测试断点无法停止的原因 --Step控制标记位 local stepOverCounter = 0; --STEPOVER over计数器 local stepOutCounter = 0; --STEPOVER out计数器 local HOOK_LEVEL = 3; --调用栈偏移量,使用clib时为3,lua中不再使用此变量,而是通过函数getSpecificFunctionStackLevel获取 local isUseLoadstring = 0; local debugger_loadString; --临时变量 local recordBreakPointPath; --记录最后一个[可能命中]的断点,用于getInfo以及doctor的断点测试 local coroutineCreate; --用来记录lua原始的coroutine.create函数 local stopConnectTime = 0; --用来临时记录stop断开连接的时间 local isInMainThread; local receiveMsgTimer = 0; local isUserSetClibPath = false; --用户是否在本文件中自设了clib路径 local hitBpTwiceCheck; -- 命中断点的Vscode校验结果,默认true (true是命中,false是未命中) local formatPathCache = {}; -- getinfo -> format function this.formatPathCache() return formatPathCache; end local fakeBreakPointCache = {}; --其中用 路径-{行号列表} 形式保存错误命中信息 function this.fakeBreakPointCache() return fakeBreakPointCache; end --5.1/5.3兼容 if _VERSION == "Lua 5.1" then debugger_loadString = loadstring; else debugger_loadString = load; end --用户在控制台输入信息的环境变量 local env = setmetatable({ }, { __index = function( _ , varName ) local ret = this.getWatchedVariable( varName, _G.LuaPanda.curStackId , false); return ret; end, __newindex = function( _ , varName, newValue ) this.setVariableValue( varName, _G.LuaPanda.curStackId, newValue); end }); ----------------------------------------------------------------------------- -- 流程 ----------------------------------------------------------------------------- ---this.bindServer 当lua进程作为Server时,server绑定函数 --- server 在bind时创建, 连接成功后关闭listen , disconnect时置空。reconnect时会查询server,没有的话重新绑定,如果已存在直接accept function this.bindServer(host, port) server = sock server:settimeout(listeningTimeoutSec); assert(server:bind(host, port)); server:setoption("reuseaddr", true); --防止已连接状态下新的连接进入,不再reuse assert(server:listen(0)); end -- 以lua作为服务端的形式启动调试器 -- @host 绑定ip , 默认 0.0.0.0 -- @port 绑定port, 默认 8818 function this.startServer(host, port) host = tostring(host or "0.0.0.0") ; port = tonumber(port) or 8818; luaProcessAsServer = true; this.printToConsole("Debugger start as SERVER. bind host:" .. host .. " port:".. tostring(port), 1); if sock ~= nil then this.printToConsole("[Warning] 调试器已经启动,请不要再次调用start()" , 1); return; end --尝试初次连接 this.changeRunState(runState.DISCONNECT); if not this.reGetSock() then this.printToConsole("[Error] LuaPanda debugger start success , but get Socket fail , please install luasocket!", 2); return; end recordHost = host; recordPort = port; this.bindServer(recordHost, recordPort); local connectSuccess = server:accept(); sock = connectSuccess; if connectSuccess then this.printToConsole("First connect success!"); this.connectSuccess(); else this.printToConsole("First connect failed!"); this.changeHookState(hookState.DISCONNECT_HOOK); end end -- 启动调试器 -- @host adapter端ip, 默认127.0.0.1 -- @port adapter端port ,默认8818 function this.start(host, port) host = tostring(host or "127.0.0.1") ; port = tonumber(port) or 8818; this.printToConsole("Debugger start as CLIENT. connect host:" .. host .. " port:".. tostring(port), 1); if sock ~= nil then this.printToConsole("[Warning] 调试器已经启动,请不要再次调用start()" , 1); return; end --尝试初次连接 this.changeRunState(runState.DISCONNECT); if not this.reGetSock() then this.printToConsole("[Error] Start debugger but get Socket fail , please install luasocket!", 2); return; end recordHost = host; recordPort = port; sock:settimeout(connectTimeoutSec); local connectSuccess = this.sockConnect(sock); if connectSuccess then this.printToConsole("First connect success!"); this.connectSuccess(); else this.printToConsole("First connect failed!"); this.changeHookState(hookState.DISCONNECT_HOOK); end end function this.sockConnect(sock) if sock then local connectSuccess, status = sock:connect(recordHost, recordPort); if status == "connection refused" then this.reGetSock(); end return connectSuccess; end return nil; end -- 连接成功,开始初始化 function this.connectSuccess() if server then server:close(); -- 停止listen end this.changeRunState(runState.WAIT_CMD); this.printToConsole("connectSuccess", 1); --设置初始状态 local ret = this.debugger_wait_msg(); --获取debugger文件路径 if DebuggerFileName == "" then local info = debug.getinfo(1, "S") for k,v in pairs(info) do if k == "source" then DebuggerFileName = tostring(v); -- 从代码中去后缀 autoExt = DebuggerFileName:gsub('.*[Ll][Uu][Aa][Pp][Aa][Nn][Dd][Aa]', ''); if hookLib ~= nil then hookLib.sync_debugger_path(DebuggerFileName); end end end end if DebuggerToolsName == "" then DebuggerToolsName = tools.getFileSource(); if hookLib ~= nil then hookLib.sync_tools_path(DebuggerToolsName); end end if ret == false then this.printToVSCode("[debugger error]初始化未完成, 建立连接但接收初始化消息失败。请更换端口重试", 2); return; end this.printToVSCode("debugger init success", 1); this.changeHookState(hookState.ALL_HOOK); if hookLib == nil then --协程调试 if coroutineCreate == nil and type(coroutine.create) == "function" then this.printToConsole("change coroutine.create"); coroutineCreate = coroutine.create; coroutine.create = function(...) local co = coroutineCreate(...) table.insert(coroutinePool, co); --运行状态下,创建协程即启动hook this.changeCoroutineHookState(); return co; end else this.printToConsole("restart coroutine"); this.changeCoroutineHookState(); end end end --重置数据 function this.clearData() OSType = nil; clibPath = nil; -- reset breaks breaks = {}; formatPathCache = {}; fakeBreakPointCache = {}; this.breaks = breaks; if hookLib ~= nil then hookLib.sync_breakpoints(); --清空断点信息 hookLib.clear_pathcache(); --清空路径缓存 end end -- 本次连接过程中停止attach ,以提高运行效率 function this.stopAttach() openAttachMode = false; this.printToConsole("Debugger stopAttach", 1); this.clearData() this.changeHookState( hookState.DISCONNECT_HOOK ); stopConnectTime = os.time(); this.changeRunState(runState.DISCONNECT); if sock ~= nil then sock:close(); if luaProcessAsServer and server then server = nil; end; end end --断开连接 function this.disconnect() this.printToConsole("Debugger disconnect", 1); this.clearData() this.changeHookState( hookState.DISCONNECT_HOOK ); stopConnectTime = os.time(); this.changeRunState(runState.DISCONNECT); if sock ~= nil then sock:close(); sock = nil; server = nil; end if recordHost == nil or recordPort == nil then --异常情况处理, 在调用LuaPanda.start()前首先调用了LuaPanda.disconnect() this.printToConsole("[Warning] User call LuaPanda.disconnect() before set debug ip & port, please call LuaPanda.start() first!", 2); return; end this.reGetSock(); end ----------------------------------------------------------------------------- -- 调试器通用方法 ----------------------------------------------------------------------------- -- 返回断点信息 function this.getBreaks() return breaks; end ---testBreakpoint 测试断点 function this.testBreakpoint() if recordBreakPointPath and recordBreakPointPath ~= "" then -- testBreakpointFlag = false; return this.breakpointTestInfo(); else local strTable = {}; strTable[#strTable + 1] = "正在准备进行断点测试,请按照如下步骤操作\n" strTable[#strTable + 1] = "1. 请[删除]当前项目中所有断点;\n" strTable[#strTable + 1] = "2. 在当前停止行打一个断点;\n" strTable[#strTable + 1] = "3. 再次运行 'LuaPanda.testBreakpoint()'" testBreakpointFlag = true; return table.concat(strTable); end end -- 返回路径相关信息 -- cwd:配置的工程路径 | info["source"]:通过 debug.getinfo 获得执行文件的路径 | format:格式化后的文件路径 function this.breakpointTestInfo() local ly = this.getSpecificFunctionStackLevel(lastRunFunction.func); if type(ly) ~= "number" then ly = 2; end local runSource = lastRunFunction["source"]; if runSource == nil and hookLib ~= nil then runSource = this.getPath(tostring(hookLib.get_last_source())); end local info = debug.getinfo(ly, "S"); local NormalizedPath = this.formatOpath(info["source"]); NormalizedPath = this.truncatedPath(NormalizedPath, truncatedOPath); local strTable = {} local FormatedPath = tostring(runSource); strTable[#strTable + 1] = "\n- BreakPoint Test:" strTable[#strTable + 1] = "\nUser set lua extension: ." .. tostring(luaFileExtension); strTable[#strTable + 1] = "\nAuto get lua extension: " .. tostring(autoExt); if truncatedOPath and truncatedOPath ~= '' then strTable[#strTable + 1] = "\nUser set truncatedOPath: " .. truncatedOPath; end strTable[#strTable + 1] = "\nGetInfo: ".. info["source"]; strTable[#strTable + 1] = "\nNormalized: " .. NormalizedPath; strTable[#strTable + 1] = "\nFormated: " .. FormatedPath; if recordBreakPointPath and recordBreakPointPath ~= "" then strTable[#strTable + 1] = "\nBreakpoint: " .. recordBreakPointPath; end if not autoPathMode then if isAbsolutePath then strTable[#strTable + 1] = "\n说明:从lua虚拟机获取到的是绝对路径,Formated使用GetInfo路径。" .. winDiskSymbolTip; else strTable[#strTable + 1] = "\n说明:从lua虚拟机获取到的路径(GetInfo)是相对路径,调试器运行依赖的绝对路径(Formated)是来源于cwd+GetInfo拼接。如Formated路径错误请尝试调整cwd或改变VSCode打开文件夹的位置。也可以在Formated对应的文件下打一个断点,调整直到Formated和Breaks Info中断点路径完全一致。" .. winDiskSymbolTip; end else strTable[#strTable + 1] = "\n说明:自动路径(autoPathMode)模式已开启。"; if recordBreakPointPath and recordBreakPointPath ~= "" then if string.find(recordBreakPointPath , FormatedPath, (-1) * string.len(FormatedPath) , true) then -- 短路径断点命中 if distinguishSameNameFile == false then strTable[#strTable + 1] = "本文件中断点可正常命中。" strTable[#strTable + 1] = "同名文件中的断点识别(distinguishSameNameFile) 未开启,请确保 VSCode 断点不要存在于同名 lua 文件中。"; else strTable[#strTable + 1] = "同名文件中的断点识别(distinguishSameNameFile) 已开启。"; if string.find(recordBreakPointPath, NormalizedPath, 1, true) then strTable[#strTable + 1] = "本文件中断点可被正常命中" else strTable[#strTable + 1] = "断点可能无法被命中,因为 lua 虚拟机中获得的路径 Normalized 不是断点路径 Breakpoint 的子串。 如有需要,可以在 launch.json 中设置 truncatedOPath 来去除 Normalized 部分路径。" end end else strTable[#strTable + 1] = "断点未被命中,原因是 Formated 不是 Breakpoint 路径的子串,或者 Formated 和 Breakpoint 文件后缀不一致" end else strTable[#strTable + 1] = "如果要进行断点测试,请使用 LuaPanda.testBreakpoint()。" end end return table.concat(strTable) end --返回版本号等配置 function this.getBaseInfo() local strTable = {}; local jitVer = ""; if jit and jit.version then jitVer = "," .. tostring(jit.version); end strTable[#strTable + 1] = "Lua Ver:" .. _VERSION .. jitVer .." | Adapter Ver:" .. tostring(adapterVer) .. " | Debugger Ver:" .. tostring(debuggerVer); local moreInfoStr = ""; if hookLib ~= nil then local clibVer, forluaVer = hookLib.sync_getLibVersion(); local clibStr = forluaVer ~= nil and tostring(clibVer) .. " for " .. tostring(math.ceil(forluaVer)) or tostring(clibVer); strTable[#strTable + 1] = " | hookLib Ver:" .. clibStr; moreInfoStr = moreInfoStr .. "说明: 已加载 libpdebug 库."; else moreInfoStr = moreInfoStr .. "说明: 未能加载 libpdebug 库。原因请使用 LuaPanda.doctor() 查看"; end local outputIsUseLoadstring = false if type(isUseLoadstring) == "number" and isUseLoadstring == 1 then outputIsUseLoadstring = true; end strTable[#strTable + 1] = " | supportREPL:".. tostring(outputIsUseLoadstring); strTable[#strTable + 1] = " | useBase64EncodeString:".. tostring(isNeedB64EncodeStr); strTable[#strTable + 1] = " | codeEnv:" .. tostring(OSType); strTable[#strTable + 1] = " | distinguishSameNameFile:" .. tostring(distinguishSameNameFile) .. '\n'; strTable[#strTable + 1] = moreInfoStr; if OSTypeErrTip ~= nil and OSTypeErrTip ~= '' then strTable[#strTable + 1] = '\n' ..OSTypeErrTip; end return table.concat(strTable); end --自动诊断当前环境的错误,并输出信息 function this.doctor() local strTable = {}; if debuggerVer ~= adapterVer then strTable[#strTable + 1] = "\n- 建议更新版本\nLuaPanda VSCode插件版本是" .. adapterVer .. ", LuaPanda.lua文件版本是" .. debuggerVer .. "。建议检查并更新到最新版本。"; strTable[#strTable + 1] = "\n更新方式 : https://github.com/Tencent/LuaPanda/blob/master/Docs/Manual/update.md"; strTable[#strTable + 1] = "\nRelease版本: https://github.com/Tencent/LuaPanda/releases"; end --plibdebug if hookLib == nil then strTable[#strTable + 1] = "\n\n- libpdebug 库没有加载\n"; if userSetUseClib then --用户允许使用clib插件 if isUserSetClibPath == true then --用户自设了clib地址 strTable[#strTable + 1] = "用户使用 LuaPanda.lua 中 clibPath 变量指定了 plibdebug 的位置: " .. clibPath; if this.tryRequireClib("libpdebug", clibPath) then strTable[#strTable + 1] = "\n引用成功"; else strTable[#strTable + 1] = "\n引用错误:" .. loadclibErrReason; end else --使用默认clib地址 local clibExt, platform; if OSType == "Darwin" then clibExt = "/?.so;"; platform = "mac"; elseif OSType == "Linux" then clibExt = "/?.so;"; platform = "linux"; else clibExt = "/?.dll;"; platform = "win"; end local lua_ver; if _VERSION == "Lua 5.1" then lua_ver = "501"; else lua_ver = "503"; end local x86Path = clibPath .. platform .."/x86/".. lua_ver .. clibExt; local x64Path = clibPath .. platform .."/x86_64/".. lua_ver .. clibExt; strTable[#strTable + 1] = "尝试引用x64库: ".. x64Path; if this.tryRequireClib("libpdebug", x64Path) then strTable[#strTable + 1] = "\n引用成功"; else strTable[#strTable + 1] = "\n引用错误:" .. loadclibErrReason; strTable[#strTable + 1] = "\n尝试引用x86库: ".. x86Path; if this.tryRequireClib("libpdebug", x86Path) then strTable[#strTable + 1] = "\n引用成功"; else strTable[#strTable + 1] = "\n引用错误:" .. loadclibErrReason; end end end else strTable[#strTable + 1] = "原因是" .. loadclibErrReason; end end --path --尝试直接读当前getinfo指向的文件,看能否找到。如果能,提示正确,如果找不到,给出提示,建议玩家在这个文件中打一个断点 --检查断点,文件和当前文件的不同,给出建议 local runSource = lastRunFilePath; if hookLib ~= nil then runSource = this.getPath(tostring(hookLib.get_last_source())); end -- 在精确路径模式下的路径错误检测 if not autoPathMode and runSource and runSource ~= "" then -- 读文件 local isFileExist = this.fileExists(runSource); if not isFileExist then strTable[#strTable + 1] = "\n\n- 路径存在问题\n"; --解析路径,得到文件名,到断点路径中查这个文件名 local pathArray = this.stringSplit(runSource, '/'); --如果pathArray和断点能匹配上 local fileMatch= false; for key, _ in pairs(this.getBreaks()) do if string.find(key, pathArray[#pathArray], 1, true) then --和断点匹配了 fileMatch = true; -- retStr = retStr .. "\n请对比如下路径:\n"; strTable[#strTable + 1] = this.breakpointTestInfo(); strTable[#strTable + 1] = "\nfilepath: " .. key; if isAbsolutePath then strTable[#strTable + 1] = "\n说明:从lua虚拟机获取到的是绝对路径,format使用getinfo路径。"; else strTable[#strTable + 1] = "\n说明:从lua虚拟机获取到的是相对路径,调试器运行依赖的绝对路径(format)是来源于cwd+getinfo拼接。"; end strTable[#strTable + 1] = "\nfilepath是VSCode通过获取到的文件正确路径 , 对比format和filepath,调整launch.json中CWD,或改变VSCode打开文件夹的位置。使format和filepath一致即可。\n如果format和filepath路径仅大小写不一致,设置launch.json中 pathCaseSensitivity:false 可忽略路径大小写"; end end if fileMatch == false then --未能和断点匹配 strTable[#strTable + 1] = "\n找不到文件:" .. runSource .. ", 请检查路径是否正确。\n或者在VSCode文件" .. pathArray[#pathArray] .. "中打一个断点后,再执行一次doctor命令,查看路径分析结果。"; end end end --日志等级对性能的影响 if logLevel < 1 or consoleLogLevel < 1 then strTable[#strTable + 1] = "\n\n- 日志等级\n"; if logLevel < 1 then strTable[#strTable + 1] = "当前日志等级是" .. logLevel .. ", 会产生大量日志,降低调试速度。建议调整launch.json中logLevel:1"; end if consoleLogLevel < 1 then strTable[#strTable + 1] = "当前console日志等级是" .. consoleLogLevel .. ", 过低的日志等级会降低调试速度,建议调整LuaPanda.lua文件头部consoleLogLevel=2"; end end if #strTable == 0 then strTable[#strTable + 1] = "未检测出问题"; end return table.concat(strTable); end function this.fileExists(path) local f=io.open(path,"r"); if f~= nil then io.close(f) return true else return false end end --返回一些信息,帮助用户定位问题 function this.getInfo() --用户设置项 local strTable = {}; strTable[#strTable + 1] = "\n- Base Info: \n"; strTable[#strTable + 1] = this.getBaseInfo(); --已经加载C库,x86/64 未能加载,原因 strTable[#strTable + 1] = "\n\n- User Setting: \n"; strTable[#strTable + 1] = "stopOnEntry:" .. tostring(stopOnEntry) .. ' | '; -- strTable[#strTable + 1] = "luaFileExtension:" .. luaFileExtension .. ' | '; strTable[#strTable + 1] = "logLevel:" .. logLevel .. ' | ' ; strTable[#strTable + 1] = "consoleLogLevel:" .. consoleLogLevel .. ' | '; strTable[#strTable + 1] = "pathCaseSensitivity:" .. tostring(pathCaseSensitivity) .. ' | '; strTable[#strTable + 1] = "attachMode:".. tostring(openAttachMode).. ' | '; strTable[#strTable + 1] = "autoPathMode:".. tostring(autoPathMode).. ' | '; if userSetUseClib then strTable[#strTable + 1] = "useCHook:true"; else strTable[#strTable + 1] = "useCHook:false"; end if logLevel == 0 or consoleLogLevel == 0 then strTable[#strTable + 1] = "\n说明:日志等级过低,会影响执行效率。请调整logLevel和consoleLogLevel值 >= 1"; end strTable[#strTable + 1] = "\n\n- Path Info: \n"; strTable[#strTable + 1] = "clibPath: " .. tostring(clibPath) .. '\n'; strTable[#strTable + 1] = "debugger: " .. DebuggerFileName .. " | " .. this.getPath(DebuggerFileName) .. '\n'; strTable[#strTable + 1] = "cwd : " .. cwd .. '\n'; strTable[#strTable + 1] = this.breakpointTestInfo(); if pathErrTip ~= nil and pathErrTip ~= '' then strTable[#strTable + 1] = '\n' .. pathErrTip; end strTable[#strTable + 1] = "\n\n- Breaks Info: \nUse 'LuaPanda.getBreaks()' to watch."; return table.concat(strTable); end --判断是否在协程中 function this.isInMain() return isInMainThread; end --添加路径,尝试引用库。完成后把cpath还原,返回引用结果true/false -- @libName 库名 -- path lib的cpath路径 function this.tryRequireClib(libName , libPath) this.printToVSCode("tryRequireClib search : [" .. libName .. "] in "..libPath); local savedCpath = package.cpath; package.cpath = package.cpath .. ';' .. libPath; this.printToVSCode("package.cpath:" .. package.cpath); local status, err = pcall(function() hookLib = require(libName) end); if status then if type(hookLib) == "table" and this.getTableMemberNum(hookLib) > 0 then this.printToVSCode("tryRequireClib success : [" .. libName .. "] in "..libPath); package.cpath = savedCpath; return true; else loadclibErrReason = "tryRequireClib fail : require success, but member function num <= 0; [" .. libName .. "] in "..libPath; this.printToVSCode(loadclibErrReason); hookLib = nil; package.cpath = savedCpath; return false; end else -- 此处考虑到tryRequireClib会被调用两次,日志级别设置为0,防止输出不必要的信息。 loadclibErrReason = err; this.printToVSCode("[Require clib error]: " .. err, 0); end package.cpath = savedCpath; return false end ------------------------字符串处理------------------------- -- 倒序查找字符串 a.b/c查找/ , 返回4 -- @str 被查找的长串 -- @subPattern 查找的子串, 也可以是pattern -- @plain plane text / pattern -- @return 未找到目标串返回nil. 否则返回倒序找到的字串位置 function this.revFindString(str, subPattern, plain) local revStr = string.reverse(str); local _, idx = string.find(revStr, subPattern, 1, plain); if idx == nil then return nil end; return string.len(revStr) - idx + 1; end -- 反序裁剪字符串 如:print(subString("a.b/c", "/"))输出c -- @return 未找到目标串返回nil. 否则返回被裁剪后的字符串 function this.revSubString(str, subStr, plain) local idx = this.revFindString(str, subStr, plain) if idx == nil then return nil end; return string.sub(str, idx + 1, str.length) end -- 把字符串按reps分割成并放入table -- @str 目标串 -- @reps 分割符。注意这个分隔符是一个pattern function this.stringSplit( str, separator ) local retStrTable = {} string.gsub(str, '[^' .. separator ..']+', function ( word ) table.insert(retStrTable, word) end) return retStrTable; end -- 保存CallbackId(通信序列号) function this.setCallbackId( id ) if id ~= nil and id ~= "0" then recCallbackId = tostring(id); end end -- 读取CallbackId(通信序列号)。读取后记录值将被置空 function this.getCallbackId() if recCallbackId == nil then recCallbackId = "0"; end local id = recCallbackId; recCallbackId = "0"; return id; end -- reference from https://www.lua.org/pil/20.1.html function this.trim (s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end --返回table中成员数量(数字key和非数字key之和) -- @t 目标table -- @return 元素数量 function this.getTableMemberNum(t) local retNum = 0; if type(t) ~= "table" then this.printToVSCode("[debugger Error] getTableMemberNum get "..tostring(type(t)), 2) return retNum; end for k,v in pairs(t) do retNum = retNum + 1; end return retNum; end -- 生成一个消息Table function this.getMsgTable(cmd ,callbackId) callbackId = callbackId or 0; local msgTable = {}; msgTable["cmd"] = cmd; msgTable["callbackId"] = callbackId; msgTable["info"] = {}; return msgTable; end function this.serializeTable(tab, name) local sTable = tools.serializeTable(tab, name); return sTable; end ------------------------日志打印相关------------------------- -- 把日志打印在VSCode端 -- @str: 日志内容 -- @printLevel: all(0)/info(1)/error(2) -- @type: 0:vscode console 1:vscode tip function this.printToVSCode(str, printLevel, type) type = type or 0; printLevel = printLevel or 0; if currentRunState == runState.DISCONNECT or logLevel > printLevel then return; end local sendTab = {}; sendTab["callbackId"] = "0"; if type == 0 then sendTab["cmd"] = "output"; elseif type == 1 then sendTab["cmd"] = "tip"; else -- type == 2 sendTab["cmd"] = "debug_console"; end sendTab["info"] = {}; sendTab["info"]["logInfo"] = tostring(str); this.sendMsg(sendTab); end -- 把日志打印在控制台 -- @str: 日志内容 -- @printLevel: all(0)/info(1)/error(2) function this.printToConsole(str, printLevel) printLevel = printLevel or 0; if consoleLogLevel > printLevel then return; end print("[LuaPanda] ".. tostring(str)); end ----------------------------------------------------------------------------- -- 提升兼容性方法 ----------------------------------------------------------------------------- --生成平台无关的路径。 --return:nil(error)/path function this.genUnifiedPath(path) if path == "" or path == nil then return ""; end --大小写不敏感时,路径全部转为小写 if pathCaseSensitivity == false then path = string.lower(path); end --统一路径全部替换成/ path = string.gsub(path, [[\]], "/"); --处理 /../ /./ local pathTab = this.stringSplit(path, '/'); local newPathTab = {}; for k, v in ipairs(pathTab) do if v == '.' then --continue elseif v == ".." and #newPathTab >= 1 and newPathTab[#newPathTab]:sub(2,2) ~= ':' then --newPathTab有元素,最后一项不是X: table.remove(newPathTab); else table.insert(newPathTab, v); end end --重新拼合后如果是mac路径第一位是/ local newpath = table.concat(newPathTab, '/'); if path:sub(1,1) == '/' then newpath = '/'.. newpath; end --win下按照winDiskSymbolUpper的设置修改盘符大小 if "Windows_NT" == OSType then if winDiskSymbolUpper then newpath = newpath:gsub("^%a:", string.upper); winDiskSymbolTip = "路径中Windows盘符已转为大写。" else newpath = newpath:gsub("^%a:", string.lower); winDiskSymbolTip = "路径中Windows盘符已转为小写。" end end return newpath; end function this.getCacheFormatPath(source) if source == nil then return formatPathCache end; return formatPathCache[source]; end function this.setCacheFormatPath(source, dest) formatPathCache[source] = dest; end -- 处理 opath(info.source) 的函数, 生成一个规范的路径函数(和VScode端checkRightPath逻辑完全一致) function this.formatOpath(opath) -- delete @ if opath:sub(1,1) == '@' then opath = opath:sub(2); end -- change ./ to / if opath:sub(1,2) == './' then opath = opath:sub(2); end opath = this.genUnifiedPath(opath); -- lower if pathCaseSensitivity == false then opath = string.lower(opath); end --把filename去除后缀 if autoExt == nil or autoExt == '' then -- 在虚拟机返回路径没有后缀的情况下,用户必须自设后缀 -- 确定filePath中最后一个.xxx 不等于用户配置的后缀, 则把所有的. 转为 / if not opath:find(luaFileExtension , (-1) * luaFileExtension:len(), true) then -- getinfo 路径没有后缀,把 . 全部替换成 / ,我们不允许用户在文件(或文件夹)名称中出现"." , 因为无法区分 opath = string.gsub(opath, "%.", "/"); else -- 有后缀,那么把除后缀外的部分中的. 转为 / opath = this.changePotToSep(opath, luaFileExtension); end else -- 虚拟机路径有后缀 opath = this.changePotToSep(opath, autoExt); end -- 截取 路径+文件名 (不带后缀) -- change pot to / -- opath = string.gsub(opath, "%.", "/"); return opath; end ----------------------------------------------------------------------------- -- 内存相关 ----------------------------------------------------------------------------- function this.sendLuaMemory() local luaMem = collectgarbage("count"); local sendTab = {}; sendTab["callbackId"] = "0"; sendTab["cmd"] = "refreshLuaMemory"; sendTab["info"] = {}; sendTab["info"]["memInfo"] = tostring(luaMem); this.sendMsg(sendTab); end ----------------------------------------------------------------------------- -- 网络相关方法 ----------------------------------------------------------------------------- -- 刷新socket -- @return true/false 刷新成功/失败 function this.reGetSock() if server then return true end if sock ~= nil then pcall(function() sock:close() end); end --call slua-unreal luasocket sock = lua_extension and lua_extension.luasocket and lua_extension.luasocket().tcp(); if sock == nil then --call normal luasocket if pcall(function() sock = require("socket.core").tcp(); end) then this.printToConsole("reGetSock success"); else --call custom function to get socket if customGetSocketInstance and pcall( function() sock = customGetSocketInstance(); end ) then this.printToConsole("reGetSock custom success"); else this.printToConsole("[Error] reGetSock fail", 2); return false; end end else --set ue4 luasocket this.printToConsole("reGetSock ue4 success"); end return true; end -- 定时(以函数return为时机) 进行attach连接 -- 返回值 hook 可以继续往下走时返回1 ,无需继续时返回0 function this.reConnect() if currentHookState == hookState.DISCONNECT_HOOK then if os.time() - stopConnectTime < attachInterval then -- 未到重连时间 -- this.printToConsole("Reconnect time less than 1s"); -- this.printToConsole("os.time:".. os.time() .. " | stopConnectTime:" ..stopConnectTime); return 0; end this.printToConsole("Reconnect !"); if sock == nil then this.reGetSock(); end local connectSuccess; if luaProcessAsServer == true and currentRunState == runState.DISCONNECT then -- 在 Server 模式下,以及当前处于未连接状态下,才尝试accept新链接。如果不判断可能会出现多次连接,导致sock被覆盖 if server == nil then this.bindServer(recordHost, recordPort); end sock = server:accept(); connectSuccess = sock; else sock:settimeout(connectTimeoutSec); connectSuccess = this.sockConnect(sock); end if connectSuccess then this.printToConsole("reconnect success"); this.connectSuccess(); return 1; else this.printToConsole("reconnect failed" ); stopConnectTime = os.time(); return 0; end end -- 不必重连,正常继续运行 return 1; end -- 向adapter发消息 -- @sendTab 消息体table function this.sendMsg( sendTab ) if isNeedB64EncodeStr and sendTab["info"] ~= nil then for _, v in ipairs(sendTab["info"]) do if v["type"] == "string" then v["value"] = tools.base64encode(v["value"]) end end end local sendStr = json.encode(sendTab); if currentRunState == runState.DISCONNECT then this.printToConsole("[debugger error] disconnect but want sendMsg:" .. sendStr, 2); this.disconnect(); return; end local succ,err; if pcall(function() succ,err = sock:send(sendStr..TCPSplitChar.."\n"); end) then if succ == nil then if err == "closed" then this.disconnect(); end end end end -- 处理 收到的消息 -- @dataStr 接收的消息json function this.dataProcess( dataStr ) this.printToVSCode("debugger get:"..dataStr); local dataTable = json.decode(dataStr); if dataTable == nil then this.printToVSCode("[error] Json is error", 2); return; end if dataTable.callbackId ~= "0" then this.setCallbackId(dataTable.callbackId); end if dataTable.cmd == "continue" then local info = dataTable.info; if info.isFakeHit == "true" and info.fakeBKPath and info.fakeBKLine then -- 设置校验结果标志位,以便hook流程知道结果 hitBpTwiceCheck = false; if hookLib ~= nil and hookLib.set_bp_twice_check_res then -- 把结果同步给C hookLib.set_bp_twice_check_res(0); end -- 把假断点的信息加入cache if nil == fakeBreakPointCache[info.fakeBKPath] then fakeBreakPointCache[info.fakeBKPath] = {}; end table.insert(fakeBreakPointCache[info.fakeBKPath] ,info.fakeBKLine); else this.changeRunState(runState.RUN); end local msgTab = this.getMsgTable("continue", this.getCallbackId()); this.sendMsg(msgTab); elseif dataTable.cmd == "stopOnStep" then this.changeRunState(runState.STEPOVER); local msgTab = this.getMsgTable("stopOnStep", this.getCallbackId()); this.sendMsg(msgTab); this.changeHookState(hookState.ALL_HOOK); elseif dataTable.cmd == "stopOnStepIn" then this.changeRunState(runState.STEPIN); local msgTab = this.getMsgTable("stopOnStepIn", this.getCallbackId()); this.sendMsg(msgTab); this.changeHookState(hookState.ALL_HOOK); elseif dataTable.cmd == "stopOnStepOut" then this.changeRunState(runState.STEPOUT); local msgTab = this.getMsgTable("stopOnStepOut", this.getCallbackId()); this.sendMsg(msgTab); this.changeHookState(hookState.ALL_HOOK); elseif dataTable.cmd == "setBreakPoint" then this.printToVSCode("dataTable.cmd == setBreakPoint"); -- 设置断点时,把 fakeBreakPointCache 清空。这是一个简单的做法,也可以清除具体的条目 fakeBreakPointCache = {} local bkPath = dataTable.info.path; bkPath = this.genUnifiedPath(bkPath); if testBreakpointFlag then recordBreakPointPath = bkPath; end if autoPathMode then -- 自动路径模式下,仅保留文件名 -- table[文件名.后缀] -- [fullpath] -- [line , type] -- | - [fullpath] -- [line , type] local bkShortPath = this.getFilenameFromPath(bkPath); if breaks[bkShortPath] == nil then breaks[bkShortPath] = {}; end breaks[bkShortPath][bkPath] = dataTable.info.bks; -- 当v为空时,从断点列表中去除文件 for k, v in pairs(breaks[bkShortPath]) do if next(v) == nil then breaks[bkShortPath][k] = nil; end end else if breaks[bkPath] == nil then breaks[bkPath] = {}; end -- 两级 bk path 是为了和自动路径模式结构保持一致 breaks[bkPath][bkPath] = dataTable.info.bks; -- 当v为空时,从断点列表中去除文件 for k, v in pairs(breaks[bkPath]) do if next(v) == nil then breaks[bkPath][k] = nil; end end end -- 当v为空时,从断点列表中去除文件 for k, v in pairs(breaks) do if next(v) == nil then breaks[k] = nil; end end --sync breaks to c if hookLib ~= nil then hookLib.sync_breakpoints(); end if currentRunState ~= runState.WAIT_CMD then if hookLib == nil then local fileBP, G_BP =this.checkHasBreakpoint(lastRunFilePath); if fileBP == false then if G_BP == true then this.changeHookState(hookState.MID_HOOK); else this.changeHookState(hookState.LITE_HOOK); end else this.changeHookState(hookState.ALL_HOOK); end end else local msgTab = this.getMsgTable("setBreakPoint", this.getCallbackId()); this.sendMsg(msgTab); return; end --其他时机收到breaks消息 local msgTab = this.getMsgTable("setBreakPoint", this.getCallbackId()); this.sendMsg(msgTab); -- 打印调试信息 this.printToVSCode("LuaPanda.getInfo()\n" .. this.getInfo()) this.debugger_wait_msg(); elseif dataTable.cmd == "setVariable" then if currentRunState == runState.STOP_ON_ENTRY or currentRunState == runState.HIT_BREAKPOINT or currentRunState == runState.STEPOVER_STOP or currentRunState == runState.STEPIN_STOP or currentRunState == runState.STEPOUT_STOP then local msgTab = this.getMsgTable("setVariable", this.getCallbackId()); local varRefNum = tonumber(dataTable.info.varRef); local newValue = tostring(dataTable.info.newValue); local needFindVariable = true; --如果变量是基础类型,直接赋值,needFindVariable = false; 如果变量是引用类型,needFindVariable = true local varName = tostring(dataTable.info.varName); -- 根据首末含有" ' 判断 newValue 是否是字符串 local first_chr = string.sub(newValue, 1, 1); local end_chr = string.sub(newValue, -1, -1); if first_chr == end_chr then if first_chr == "'" or first_chr == '"' then newValue = string.sub(newValue, 2, -2); needFindVariable = false; end end --数字,nil,false,true的处理 if newValue == "nil" and needFindVariable == true then newValue = nil; needFindVariable = false; elseif newValue == "true" and needFindVariable == true then newValue = true; needFindVariable = false; elseif newValue == "false" and needFindVariable == true then newValue = false; needFindVariable = false; elseif tonumber(newValue) and needFindVariable == true then newValue = tonumber(newValue); needFindVariable = false; end -- 如果新值是基础类型,则不需遍历 if dataTable.info.stackId ~= nil and tonumber(dataTable.info.stackId) ~= nil and tonumber(dataTable.info.stackId) > 1 then this.curStackId = tonumber(dataTable.info.stackId); else this.printToVSCode("未能获取到堆栈层级,默认使用 this.curStackId;") end if varRefNum < 10000 then -- 如果修改的是一个 引用变量,那么可直接赋值。但还是要走变量查询过程。查找和赋值过程都需要steakId。 目前给引用变量赋值Object,steak可能有问题 msgTab.info = this.createSetValueRetTable(varName, newValue, needFindVariable, this.curStackId, variableRefTab[varRefNum]); else -- 如果修改的是一个基础类型 local setLimit; --设置检索变量的限定区域 if varRefNum >= 10000 and varRefNum < 20000 then setLimit = "local"; elseif varRefNum >= 20000 and varRefNum < 30000 then setLimit = "global"; elseif varRefNum >= 30000 then setLimit = "upvalue"; end msgTab.info = this.createSetValueRetTable(varName, newValue, needFindVariable, this.curStackId, nil, setLimit); end this.sendMsg(msgTab); this.debugger_wait_msg(); end elseif dataTable.cmd == "getVariable" then --仅在停止时处理消息,其他时刻收到此消息,丢弃 if currentRunState == runState.STOP_ON_ENTRY or currentRunState == runState.HIT_BREAKPOINT or currentRunState == runState.STEPOVER_STOP or currentRunState == runState.STEPIN_STOP or currentRunState == runState.STEPOUT_STOP then --发送变量给游戏,并保持之前的状态,等待再次接收数据 --dataTable.info.varRef 10000~20000局部变量 -- 20000~30000全局变量 -- 30000~ upvalue -- 1000~2000局部变量的查询,2000~3000全局,3000~4000upvalue local msgTab = this.getMsgTable("getVariable", this.getCallbackId()); local varRefNum = tonumber(dataTable.info.varRef); if varRefNum < 10000 then --查询变量, 此时忽略 stackId local varTable = this.getVariableRef(dataTable.info.varRef, true); msgTab.info = varTable; elseif varRefNum >= 10000 and varRefNum < 20000 then --局部变量 if dataTable.info.stackId ~= nil and tonumber(dataTable.info.stackId) > 1 then this.curStackId = tonumber(dataTable.info.stackId); if type(currentCallStack[this.curStackId - 1]) ~= "table" or type(currentCallStack[this.curStackId - 1].func) ~= "function" then local str = "getVariable getLocal currentCallStack " .. this.curStackId - 1 .. " Error\n" .. this.serializeTable(currentCallStack, "currentCallStack"); this.printToVSCode(str, 2); msgTab.info = {}; else local stackId = this.getSpecificFunctionStackLevel(currentCallStack[this.curStackId - 1].func); --去除偏移量 local varTable = this.getVariable(stackId, true); msgTab.info = varTable; end end elseif varRefNum >= 20000 and varRefNum < 30000 then --全局变量 local varTable = this.getGlobalVariable(); msgTab.info = varTable; elseif varRefNum >= 30000 then --upValue if dataTable.info.stackId ~= nil and tonumber(dataTable.info.stackId) > 1 then this.curStackId = tonumber(dataTable.info.stackId); if type(currentCallStack[this.curStackId - 1]) ~= "table" or type(currentCallStack[this.curStackId - 1].func) ~= "function" then local str = "getVariable getUpvalue currentCallStack " .. this.curStackId - 1 .. " Error\n" .. this.serializeTable(currentCallStack, "currentCallStack"); this.printToVSCode(str, 2); msgTab.info = {}; else local varTable = this.getUpValueVariable(currentCallStack[this.curStackId - 1 ].func, true); msgTab.info = varTable; end end end this.sendMsg(msgTab); this.debugger_wait_msg(); end elseif dataTable.cmd == "initSuccess" then --初始化会传过来一些变量,这里记录这些变量 --Base64 if dataTable.info.isNeedB64EncodeStr == "true" then isNeedB64EncodeStr = true; else isNeedB64EncodeStr = false; end --path luaFileExtension = dataTable.info.luaFileExtension; local TempFilePath = dataTable.info.TempFilePath; if TempFilePath:sub(-1, -1) == [[\]] or TempFilePath:sub(-1, -1) == [[/]] then TempFilePath = TempFilePath:sub(1, -2); end TempFilePath_luaString = TempFilePath; cwd = this.genUnifiedPath(dataTable.info.cwd); --logLevel logLevel = tonumber(dataTable.info.logLevel) or 1; --autoPathMode if dataTable.info.autoPathMode == "true" then autoPathMode = true; else autoPathMode = false; end if dataTable.info.pathCaseSensitivity == "true" then pathCaseSensitivity = true; truncatedOPath = dataTable.info.truncatedOPath or ""; else pathCaseSensitivity = false; truncatedOPath = string.lower(dataTable.info.truncatedOPath or ""); end if dataTable.info.distinguishSameNameFile == "true" then distinguishSameNameFile = true; else distinguishSameNameFile = false; end --OS type if nil == OSType then --用户未主动设置OSType, 接收VSCode传来的数据 if type(dataTable.info.OSType) == "string" then OSType = dataTable.info.OSType; else OSType = "Windows_NT"; OSTypeErrTip = "未能检测出OSType, 可能是node os库未能加载,系统使用默认设置Windows_NT" end else --用户自设OSType, 使用用户的设置 end --检测用户是否自设了clib路径 isUserSetClibPath = false; if nil == clibPath then --用户未设置clibPath, 接收VSCode传来的数据 if type(dataTable.info.clibPath) == "string" then clibPath = dataTable.info.clibPath; else clibPath = ""; pathErrTip = "未能正确获取libpdebug库所在位置, 可能无法加载libpdebug库。"; end else --用户自设clibPath isUserSetClibPath = true; end --查找c++的hook库是否存在. 当lua5.4时默认不使用c库 if tostring(dataTable.info.useCHook) == "true" and "Lua 5.4" ~= _VERSION then userSetUseClib = true; --用户确定使用clib if isUserSetClibPath == true then --如果用户自设了clib路径 if luapanda_chook ~= nil then hookLib = luapanda_chook; else if not(this.tryRequireClib("libpdebug", clibPath)) then this.printToVSCode("Require clib failed, use Lua to continue debug, use LuaPanda.doctor() for more information.", 1); end end else local clibExt, platform; if OSType == "Darwin" then clibExt = "/?.so;"; platform = "mac"; elseif OSType == "Linux" then clibExt = "/?.so;"; platform = "linux"; else clibExt = "/?.dll;"; platform = "win"; end local lua_ver; if _VERSION == "Lua 5.1" then lua_ver = "501"; else lua_ver = "503"; end local x86Path = clibPath.. platform .."/x86/".. lua_ver .. clibExt; local x64Path = clibPath.. platform .."/x86_64/".. lua_ver .. clibExt; if luapanda_chook ~= nil then hookLib = luapanda_chook; else if not(this.tryRequireClib("libpdebug", x64Path) or this.tryRequireClib("libpdebug", x86Path)) then this.printToVSCode("Require clib failed, use Lua to continue debug, use LuaPanda.doctor() for more information.", 1); end end end else userSetUseClib = false; end --adapter版本信息 adapterVer = tostring(dataTable.info.adapterVersion); local msgTab = this.getMsgTable("initSuccess", this.getCallbackId()); --回传是否使用了lib,是否有loadstring函数 local isUseHookLib = 0; if hookLib ~= nil then isUseHookLib = 1; --同步数据给c hook local luaVerTable = this.stringSplit(debuggerVer , '%.'); local luaVerNum = luaVerTable[1] * 10000 + luaVerTable[2] * 100 + luaVerTable[3]; if hookLib.sync_lua_debugger_ver then hookLib.sync_lua_debugger_ver(luaVerNum); end -- hookLib.sync_config(logLevel, pathCaseSensitivity and 1 or 0, autoPathMode and 1 or 0); hookLib.sync_config(logLevel, pathCaseSensitivity and 1 or 0); hookLib.sync_tempfile_path(TempFilePath_luaString); hookLib.sync_cwd(cwd); hookLib.sync_file_ext(luaFileExtension); end --detect LoadString isUseLoadstring = 0; if debugger_loadString ~= nil and type(debugger_loadString) == "function" then if(pcall(debugger_loadString("return 0"))) then isUseLoadstring = 1; end end local tab = { debuggerVer = tostring(debuggerVer) , UseHookLib = tostring(isUseHookLib) , UseLoadstring = tostring(isUseLoadstring), isNeedB64EncodeStr = tostring(isNeedB64EncodeStr) }; msgTab.info = tab; this.sendMsg(msgTab); --上面getBK中会判断当前状态是否WAIT_CMD, 所以最后再切换状态。 stopOnEntry = dataTable.info.stopOnEntry; if dataTable.info.stopOnEntry == "true" then this.changeRunState(runState.STOP_ON_ENTRY); --停止在STOP_ON_ENTRY再接收breaks消息 else this.debugger_wait_msg(1); --等待1s bk消息 如果收到或超时(没有断点)就开始运行 this.changeRunState(runState.RUN); end elseif dataTable.cmd == "getWatchedVariable" then local msgTab = this.getMsgTable("getWatchedVariable", this.getCallbackId()); local stackId = tonumber(dataTable.info.stackId); --loadstring系统函数, watch插件加载 if isUseLoadstring == 1 then --使用loadstring this.curStackId = stackId; local retValue = this.processWatchedExp(dataTable.info); msgTab.info = retValue this.sendMsg(msgTab); this.debugger_wait_msg(); return; else --旧的查找方式 local wv = this.getWatchedVariable(dataTable.info.varName, stackId, true); if wv ~= nil then msgTab.info = wv; end this.sendMsg(msgTab); this.debugger_wait_msg(); end elseif dataTable.cmd == "stopRun" then --停止hook,已不在处理任何断点信息,也就不会产生日志等。发送消息后等待前端主动断开连接 local msgTab = this.getMsgTable("stopRun", this.getCallbackId()); this.sendMsg(msgTab); if not luaProcessAsServer then this.disconnect(); end elseif "LuaGarbageCollect" == dataTable.cmd then this.printToVSCode("collect garbage!"); collectgarbage("collect"); --回收后刷一下内存 this.sendLuaMemory(); this.debugger_wait_msg(); elseif "runREPLExpression" == dataTable.cmd then this.curStackId = tonumber(dataTable.info.stackId); local retValue = this.processExp(dataTable.info); local msgTab = this.getMsgTable("runREPLExpression", this.getCallbackId()); msgTab.info = retValue this.sendMsg(msgTab); this.debugger_wait_msg(); else end end -- 变量赋值的处理函数。基本逻辑是先从当前栈帧(curStackId)中取 newValue 代表的变量,找到之后再把找到的值通过setVariableValue写回。 -- @varName 被设置值的变量名 -- @newValue 新值的名字,它是一个string -- @needFindVariable 是否需要查找引用变量。(用户输入的是否是一个Object) -- @curStackId 当前栈帧(查找和变量赋值用) -- @assigndVar 被直接赋值(省去查找过程) -- @setLimit 赋值时的限制范围(local upvalue global) function this.createSetValueRetTable(varName, newValue, needFindVariable, curStackId, assigndVar , setLimit) local info; local getVarRet; -- needFindVariable == true,则使用getWatchedVariable处理(可选, 用来支持 a = b (b为变量的情况))。 if needFindVariable == false then getVarRet = {}; getVarRet[1] = {variablesReference = 0, value = newValue, name = varName, type = type(newValue)}; else getVarRet = this.getWatchedVariable( tostring(newValue), curStackId, true); end if getVarRet ~= nil then -- newValue赋变量真实值 local realVarValue; local displayVarValue = getVarRet[1].value; if needFindVariable == true then if tonumber(getVarRet[1].variablesReference) > 0 then realVarValue = variableRefTab[tonumber(getVarRet[1].variablesReference)]; else if getVarRet[1].type == 'number' then realVarValue = tonumber(getVarRet[1].value) end if getVarRet[1].type == 'string' then realVarValue = tostring(getVarRet[1].value); local first_chr = string.sub(realVarValue, 1, 1); local end_chr = string.sub(realVarValue, -1, -1); if first_chr == end_chr then if first_chr == "'" or first_chr == '"' then realVarValue = string.sub(realVarValue, 2, -2); displayVarValue = realVarValue; end end end if getVarRet[1].type == 'boolean' then if getVarRet[1].value == "true" then realVarValue = true; else realVarValue = false; end end if getVarRet[1].type == 'nil' then realVarValue = nil end end else realVarValue = getVarRet[1].value; end local setVarRet; if type(assigndVar) ~= table then setVarRet = this.setVariableValue( varName, curStackId, realVarValue, setLimit ); else assigndVar[varName] = realVarValue; setVarRet = true; end if getVarRet[1].type == "string" then displayVarValue = '"' .. displayVarValue .. '"'; end if setVarRet ~= false and setVarRet ~= nil then local retTip = "变量 ".. varName .." 赋值成功"; info = { success = "true", name = getVarRet[1].name , type = getVarRet[1].type , value = displayVarValue, variablesReference = tostring(getVarRet[1].variablesReference), tip = retTip}; else info = { success = "false", type = type(realVarValue), value = displayVarValue, tip = "找不到要设置的变量"}; end else info = { success = "false", type = nil, value = nil, tip = "输入的值无意义"}; end return info end --接收消息 --这里维护一个接收消息队列,因为Lua端未做隔断符保护,变量赋值时请注意其中不要包含隔断符 |*| -- @timeoutSec 超时时间 -- @return boolean 成功/失败 function this.receiveMessage( timeoutSec ) timeoutSec = timeoutSec or MAX_TIMEOUT_SEC; sock:settimeout(timeoutSec); --如果队列中还有消息,直接取出来交给dataProcess处理 if #recvMsgQueue > 0 then local saved_cmd = recvMsgQueue[1]; table.remove(recvMsgQueue, 1); this.dataProcess(saved_cmd); return true; end if currentRunState == runState.DISCONNECT then this.disconnect(); return false; end if sock == nil then this.printToConsole("[debugger error]接收信息失败 | reason: socket == nil", 2); return; end local response, err = sock:receive(); if response == nil then if err == "closed" then this.printToConsole("[debugger error]接收信息失败 | reason:"..err, 2); this.disconnect(); end return false; else --判断是否是一条消息,分拆 local proc_response = string.sub(response, 1, -1 * (TCPSplitChar:len() + 1 )); local match_res = string.find(proc_response, TCPSplitChar, 1, true); if match_res == nil then --单条 this.dataProcess(proc_response); else --有粘包 repeat --待处理命令 local str1 = string.sub(proc_response, 1, match_res - 1); table.insert(recvMsgQueue, str1); --剩余匹配 local str2 = string.sub(proc_response, match_res + TCPSplitChar:len() , -1); match_res = string.find(str2, TCPSplitChar, 1, true); until not match_res this.receiveMessage(); end return true; end end --这里不用循环,在外面处理完消息会在调用回来 -- @timeoutSec 等待时间s -- @entryFlag 入口标记,用来标识是从哪里调入的 function this.debugger_wait_msg(timeoutSec) timeoutSec = timeoutSec or MAX_TIMEOUT_SEC; if currentRunState == runState.WAIT_CMD then local ret = this.receiveMessage(timeoutSec); return ret; end if currentRunState == runState.STEPOVER or currentRunState == runState.STEPIN or currentRunState == runState.STEPOUT or currentRunState == runState.RUN then this.receiveMessage(0); return end if currentRunState == runState.STEPOVER_STOP or currentRunState == runState.STEPIN_STOP or currentRunState == runState.STEPOUT_STOP or currentRunState == runState.HIT_BREAKPOINT or currentRunState == runState.STOP_ON_ENTRY then this.sendLuaMemory(); this.receiveMessage(MAX_TIMEOUT_SEC); return end end ----------------------------------------------------------------------------- -- 调试器核心方法 ----------------------------------------------------------------------------- ------------------------堆栈管理------------------------- --getStackTable需要建立stackTable,保存每层的lua函数实例(用来取upvalue),保存函数展示层级和ly的关系(便于根据前端传来的stackId查局部变量) -- @level 要获取的层级 function this.getStackTable( level ) local functionLevel = 0 if hookLib ~= nil then functionLevel = level or HOOK_LEVEL; else functionLevel = level or this.getSpecificFunctionStackLevel(lastRunFunction.func); end local stackTab = {}; local userFuncSteakLevel = 0; --用户函数的steaklevel repeat local info = debug.getinfo(functionLevel, "SlLnf") if info == nil then break; end if info.source == "=[C]" then break; end local ss = {}; ss.file = this.getPath(info); local oPathFormated = this.formatOpath(info.source) ; --从lua虚拟机获得的原始路径, 它用于帮助定位VScode端原始lua文件的位置(存在重名文件的情况)。 ss.oPath = this.truncatedPath(oPathFormated, truncatedOPath); ss.name = "文件名"; --这里要做截取 ss.line = tostring(info.currentline); --使用hookLib时,堆栈有偏移量,这里统一调用栈顶编号2 local ssindex = functionLevel - 3; if hookLib ~= nil then ssindex = ssindex + 2; end ss.index = tostring(ssindex); table.insert(stackTab,ss); --把数据存入currentCallStack local callStackInfo = {}; callStackInfo.name = ss.file; callStackInfo.line = ss.line; callStackInfo.func = info.func; --保存的function callStackInfo.realLy = functionLevel; --真实堆栈层functionLevel(仅debug时用) table.insert(currentCallStack, callStackInfo); --level赋值 if userFuncSteakLevel == 0 then userFuncSteakLevel = functionLevel; end functionLevel = functionLevel + 1; until info == nil return stackTab, userFuncSteakLevel; end -- 把路径中去除后缀部分的.变为/, -- @filePath 被替换的路径 -- @ext 后缀(后缀前的 . 不会被替换) function this.changePotToSep(filePath, ext) local idx = filePath:find(ext, (-1) * ext:len() , true) if idx then local tmp = filePath:sub(1, idx - 1):gsub("%.", "/"); filePath = tmp .. ext; end return filePath; end --- this.truncatedPath 从 beTruncatedPath 字符串中去除 rep 匹配到的部分 function this.truncatedPath(beTruncatedPath, rep) if beTruncatedPath and beTruncatedPath ~= '' and rep and rep ~= "" then local _, lastIdx = string.find(beTruncatedPath , rep); if lastIdx then beTruncatedPath = string.sub(beTruncatedPath, lastIdx + 1); end end return beTruncatedPath; end --这个方法是根据的cwd和luaFileExtension对getInfo获取到的路径进行标准化 -- @info getInfo获取的包含调用信息table function this.getPath( info ) local filePath = info; if type(info) == "table" then filePath = info.source; end --尝试从Cache中获取路径 local cachePath = this.getCacheFormatPath(filePath); if cachePath~= nil and type(cachePath) == "string" then return cachePath; end -- originalPath是getInfo的原始路径,后面用来填充路径缓存的key local originalPath = filePath; --如果路径头部有@,去除 if filePath:sub(1,1) == '@' then filePath = filePath:sub(2); end --如果路径头部有./,去除 if filePath:sub(1,2) == './' then filePath = filePath:sub(3); end -- getPath的参数路径可能来自于hook, 也可能是一个已标准的路径 if userDotInRequire then if autoExt == nil or autoExt == '' then -- 在虚拟机返回路径没有后缀的情况下,用户必须自设后缀 -- 确定filePath中最后一个.xxx 不等于用户配置的后缀, 则把所有的. 转为 / if not filePath:find(luaFileExtension , (-1) * luaFileExtension:len(), true) then -- getinfo 路径没有后缀,把 . 全部替换成 / ,我们不允许用户在文件(或文件夹)名称中出现"." , 因为无法区分 filePath = string.gsub(filePath, "%.", "/"); else -- 有后缀,那么把除后缀外的部分中的. 转为 / filePath = this.changePotToSep(filePath, luaFileExtension); end else -- 虚拟机路径有后缀 filePath = this.changePotToSep(filePath, autoExt); end end --后缀处理 if luaFileExtension ~= "" then --判断后缀中是否包含%1等魔法字符.用于从lua虚拟机获取到的路径含.的情况 if string.find(luaFileExtension, "%%%d") then filePath = string.gsub(filePath, "%.[%w%.]+$", luaFileExtension); else filePath = string.gsub(filePath, "%.[%w%.]+$", ""); filePath = filePath .. "." .. luaFileExtension; end end if not autoPathMode then --绝对路径和相对路径的处理 | 若在Mac下以/开头,或者在Win下以*:开头,说明是绝对路径,不需要再拼。 if filePath:sub(1,1) == [[/]] or filePath:sub(1,2):match("^%a:") then isAbsolutePath = true; else isAbsolutePath = false; if cwd ~= "" then --查看filePath中是否包含cwd local matchRes = string.find(filePath, cwd, 1, true); if matchRes == nil then filePath = cwd.."/"..filePath; end end end end filePath = this.genUnifiedPath(filePath); if autoPathMode then -- 自动路径模式下,只保留文件名 filePath = this.getFilenameFromPath(filePath) end --放入Cache中缓存 this.setCacheFormatPath(originalPath, filePath); return filePath; end --从路径中获取[文件名.后缀] function this.getFilenameFromPath(path) if path == nil then return ''; end return string.match(path, "([^/]*)$"); end --获取当前函数的堆栈层级 --原理是向上查找,遇到DebuggerFileName就调过。但是可能存在代码段和C导致不确定性。目前使用getSpecificFunctionStackLevel代替。 function this.getCurrentFunctionStackLevel() -- print(debug.traceback("===getCurrentFunctionStackLevel Stack trace===")) local funclayer = 2; repeat local info = debug.getinfo(funclayer, "S"); --通过name来判断 if info ~= nil then local matchRes = ((info.source == DebuggerFileName) or (info.source == DebuggerToolsName)); if matchRes == false then return (funclayer - 1); end end funclayer = funclayer + 1; until not info return 0; end --获取指定函数的堆栈层级 --通常用来获取最后一个用户函数的层级,用法是从currentCallStack取用户点击的栈,再使用本函数取对应层级。 -- @func 被获取层级的function function this.getSpecificFunctionStackLevel( func ) local funclayer = 2; repeat local info = debug.getinfo(funclayer, "f"); --通过name来判断 if info ~= nil then if info.func == func then return (funclayer - 1); end end funclayer = funclayer + 1; until not info return 0; end --检查当前堆栈是否是Lua -- @checkLayer 指定的栈层 function this.checkCurrentLayerisLua( checkLayer ) local info = debug.getinfo(checkLayer, "S"); if info == nil then return nil; end info.source = this.genUnifiedPath(info.source); if info ~= nil then for k,v in pairs(info) do if k == "what" then if v == "C" then return false; else return true; end end end end return nil; end -- 在 fakeBreakPointCache 中查询此断点是否真实存在 -- 因为同名文件的影响, 有些断点是命中错误的。经过VScode校验后,这些错误命中的断点信息被存在fakeBreakPointCache中 function this.checkRealHitBreakpoint( oPath, line ) -- 在假命中列表中搜索,如果本行有过假命中记录,返回 false if oPath and fakeBreakPointCache[oPath] then for _, value in ipairs(fakeBreakPointCache[oPath]) do if tonumber(value) == tonumber(line) then this.printToVSCode("cache hit bp in same name file. source:" .. tostring(oPath) .. " line:" .. tostring(line)); return false; end end end return true; end ------------------------断点处理------------------------- --- this.isHitBreakpoint 判断断点是否命中。这个方法在c mod以及lua中都有调用 -- @param breakpointPath 文件名+后缀 -- @param opath getinfo path -- @param curLine 当前执行行号 function this.isHitBreakpoint(breakpointPath, opath, curLine) if breaks[breakpointPath] then local oPathFormated; for fullpath, fullpathNode in pairs(breaks[breakpointPath]) do recordBreakPointPath = fullpath; --这里是为了兼容用户断点行号没有打对的情况 local line_hit = false, cur_node; for _, node in ipairs(fullpathNode) do if tonumber(node["line"]) == tonumber(curLine) then line_hit = true; -- fullpath 文件中 有行号命中 cur_node = node; recordBreakPointPath = fullpath; --行号命中后,再设置一次,保证路径准确 break; end end -- 在lua端不知道是否有同名文件,基本思路是先取文件名,用文件名和breakpointArray 进行匹配。 -- 当文件名匹配上时,可能存在多个同名文件中存在断点的情况。这时候需要用 oPath 和 fullpath 进行对比,取出正确的。 -- 当本地文件中有断点,lua做了初步命中后,可能存在 stack , 断点文件有同名的情况。这就需要vscode端也需要checkfullpath函数,使用opath进行文件校验。 if line_hit then if oPathFormated == nil then -- 为了避免性能消耗,仅在行号命中时才处理 opath 到标准化路径 oPathFormated = this.formatOpath(opath); -- 截取 oPathFormated = this.truncatedPath(oPathFormated, truncatedOPath); end if (not distinguishSameNameFile) or (string.match(fullpath, oPathFormated ) and this.checkRealHitBreakpoint(opath, curLine)) then -- type是TS中的枚举类型,其定义在BreakPoint.tx文件中 -- enum BreakpointType { -- conditionBreakpoint = 0, -- logPoint, -- lineBreakpoint -- } -- 处理断点 if cur_node["type"] == "0" then -- condition breakpoint -- 注意此处不要使用尾调用,否则会影响调用栈,导致Lua5.3和Lua5.1中调用栈层级不同 local conditionRet = this.IsMeetCondition(cur_node["condition"]); -- this.printToVSCode("Condition BK: condition:" .. cur_node["condition"] .. " conditionRet " .. tostring(conditionRet)); return conditionRet; elseif cur_node["type"] == "1" then -- log point this.printToVSCode("[LogPoint Output]: " .. cur_node["logMessage"], 2, 2); return false; else -- line breakpoint return true; end end end end else testBreakpointFlag = false; --如果用户打开了测试断点的标志位而未主动关闭,会在lua继续运行时关闭。 recordBreakPointPath = ''; --当切换文件时置空,避免提示给用户错误信息 end return false; end -- 条件断点处理函数 -- 返回true表示条件成立 -- @conditionExp 条件表达式 function this.IsMeetCondition(conditionExp) -- 判断条件之前更新堆栈信息 currentCallStack = {}; variableRefTab = {}; variableRefIdx = 1; if hookLib then this.getStackTable(4); else this.getStackTable(); end this.curStackId = 2; --在用户空间最上层执行 local conditionExpTable = {["varName"] = conditionExp} local retTable = this.processWatchedExp(conditionExpTable) local isMeetCondition = false; local function HandleResult() if retTable[1]["isSuccess"] == "true" then if retTable[1]["value"] == "nil" or (retTable[1]["value"] == "false" and retTable[1]["type"] == "boolean") then isMeetCondition = false; else isMeetCondition = true; end else isMeetCondition = false; end end xpcall(HandleResult, function() isMeetCondition = false; end) return isMeetCondition; end --加入断点函数 function this.BP() this.printToConsole("BP()"); if hookLib == nil then if currentHookState == hookState.DISCONNECT_HOOK then this.printToConsole("BP() but NO HOOK"); return; end local co, isMain = coroutine.running(); if _VERSION == "Lua 5.1" then if co == nil then isMain = true; else isMain = false; end end if isMain == true then this.printToConsole("BP() in main"); else this.printToConsole("BP() in coroutine"); debug.sethook(co, this.debug_hook, "lrc"); end hitBP = true; else if hookLib.get_libhook_state() == hookState.DISCONNECT_HOOK then this.printToConsole("BP() but NO C HOOK"); return; end --clib, set hitBP hookLib.sync_bp_hit(1); end this.changeHookState(hookState.ALL_HOOK); return true; end -- 检查当前文件中是否有断点 -- 如果填写参数fileName 返回fileName中有无断点, 全局有无断点 -- fileName为空,返回全局是否有断点 function this.checkHasBreakpoint(fileName) local hasBk = false; --有无全局断点 if next(breaks) == nil then hasBk = false; else hasBk = true; end --当前文件中是否有断点 if fileName ~= nil then return breaks[fileName] ~= nil, hasBk; else return hasBk; end end function this.checkfuncHasBreakpoint(sLine, eLine, fileName) if breaks[fileName] == nil then return false; end sLine = tonumber(sLine); eLine = tonumber(eLine); --起始行号>结束行号,或者sLine = eLine = 0 if sLine >= eLine then return true; end if this.getTableMemberNum(breaks[fileName]) <= 0 then return false; else for k,v in pairs(breaks[fileName]) do for _, node in ipairs(v) do if tonumber(node.line) > sLine and tonumber(node.line) <= eLine then return true; end end end end return false; end ------------------------HOOK模块------------------------- -- 钩子函数 -- @event 执行状态(call,return,line) -- @line 行号 function this.debug_hook(event, line) if this.reConnect() == 0 then return; end if logLevel == 0 then local logTable = {"-----enter debug_hook-----\n", "event:", event, " line:", tostring(line), " currentHookState:",currentHookState," currentRunState:", currentRunState}; local logString = table.concat(logTable); this.printToVSCode(logString); end --litehook 仅非阻塞接收断点 if currentHookState == hookState.LITE_HOOK then local ti = os.time(); if ti - receiveMsgTimer > 1 then this.debugger_wait_msg(0); receiveMsgTimer = ti; end return; end --运行中 local info; local co, isMain = coroutine.running(); if _VERSION == "Lua 5.1" then if co == nil then isMain = true; else isMain = false; end end isInMainThread = isMain; if isMain == true then info = debug.getinfo(2, "Slf") else info = debug.getinfo(co, 2, "Slf") end info.event = event; this.real_hook_process(info); end function this.real_hook_process(info) local jumpFlag = false; local event = info.event; --如果当前行在Debugger中,不做处理 local matchRes = ((info.source == DebuggerFileName) or (info.source == DebuggerToolsName)); if matchRes == true then return; end --即使MID hook在C中, 或者是Run或者单步时也接收消息 if currentRunState == runState.RUN or currentRunState == runState.STEPOVER or currentRunState == runState.STEPIN or currentRunState == runState.STEPOUT then local ti = os.time(); if ti - receiveMsgTimer > 1 then this.debugger_wait_msg(0); receiveMsgTimer = ti; end end --不处理C函数 if info.source == "=[C]" then this.printToVSCode("current method is C"); return; end --不处理 slua "temp buffer" if info.source == "temp buffer" then this.printToVSCode("current method is in temp buffer"); return; end --不处理 xlua "chunk" if info.source == "chunk" then this.printToVSCode("current method is in chunk"); return; end --lua 代码段的处理,目前暂不调试代码段。 if info.short_src:match("%[string \"") then --当shortSrc中出现[string时]。要检查一下source, 区别是路径还是代码段. 方法是看路径中有没有\t \n ; if info.source:match("[\n;=]") then --是代码段,调过 this.printToVSCode("hook jump Code String!"); jumpFlag = true; end end --标准路径处理 if jumpFlag == false then info.orininal_source = info.source; --使用 info.orininal_source 记录lua虚拟机传来的原始路径 info.source = this.getPath(info); end --本次执行的函数和上次执行的函数作对比,防止在一行停留两次 if lastRunFunction["currentline"] == info["currentline"] and lastRunFunction["source"] == info["source"] and lastRunFunction["func"] == info["func"] and lastRunFunction["event"] == event then this.printToVSCode("run twice"); end --记录最后一次调用信息 if jumpFlag == false then lastRunFunction = info; lastRunFunction["event"] = event; lastRunFilePath = info.source; end --输出函数信息到前台 if logLevel == 0 and jumpFlag == false then local logTable = {"[lua hook] event:", tostring(event), " currentRunState:",tostring(currentRunState)," currentHookState:",tostring(currentHookState)," jumpFlag:", tostring(jumpFlag)}; for k,v in pairs(info) do table.insert(logTable, tostring(k)); table.insert(logTable, ":"); table.insert(logTable, tostring(v)); table.insert(logTable, " "); end local logString = table.concat(logTable); this.printToVSCode(logString); end --仅在line时做断点判断。进了断点之后不再进入本次STEP类型的判断,用Aflag做标记 local isHit = false; if tostring(event) == "line" and jumpFlag == false then if currentRunState == runState.RUN or currentRunState == runState.STEPOVER or currentRunState == runState.STEPIN or currentRunState == runState.STEPOUT then --断点判断 isHit = this.isHitBreakpoint(info.source, info.orininal_source, info.currentline) or hitBP; if isHit == true then this.printToVSCode("HitBreakpoint!"); --备份信息 local recordStepOverCounter = stepOverCounter; local recordStepOutCounter = stepOutCounter; local recordCurrentRunState = currentRunState; --计数器清0 stepOverCounter = 0; stepOutCounter = 0; this.changeRunState(runState.HIT_BREAKPOINT); hitBpTwiceCheck = true; -- 命中标志默认设置为true, 如果校验通过,会保留这个标记,校验失败会修改 if hitBP then hitBP = false; --hitBP是断点硬性命中标记 --发消息并等待 this.SendMsgWithStack("stopOnCodeBreakpoint"); else --发消息并等待 this.SendMsgWithStack("stopOnBreakpoint"); --若二次校验未命中,恢复状态 if hitBpTwiceCheck == false then isHit = false; -- 确认未命中,把状态恢复,继续运行 this.changeRunState(recordCurrentRunState); stepOverCounter = recordStepOverCounter; stepOutCounter = recordStepOutCounter; end end end end end if isHit == true then return; end if currentRunState == runState.STEPOVER then -- line stepOverCounter!= 0 不作操作 -- line stepOverCounter == 0 停止 if event == "line" and stepOverCounter <= 0 and jumpFlag == false then stepOverCounter = 0; this.changeRunState(runState.STEPOVER_STOP) this.SendMsgWithStack("stopOnStep"); elseif event == "return" or event == "tail return" then --5.1中是tail return if stepOverCounter ~= 0 then stepOverCounter = stepOverCounter - 1; end elseif event == "call" then stepOverCounter = stepOverCounter + 1; end elseif currentRunState == runState.STOP_ON_ENTRY then --在Lua入口点处直接停住 if event == "line" and jumpFlag == false then --初始化内存分析的变量 -- MemProfiler.getSystemVar(); --这里要判断一下是Lua的入口点,否则停到 this.SendMsgWithStack("stopOnEntry"); end elseif currentRunState == runState.STEPIN then if event == "line" and jumpFlag == false then this.changeRunState(runState.STEPIN_STOP) this.SendMsgWithStack("stopOnStepIn"); end elseif currentRunState == runState.STEPOUT then --line 不做操作 --in 计数器+1 --out 计数器-1 if jumpFlag == false then if stepOutCounter <= -1 then stepOutCounter = 0; this.changeRunState(runState.STEPOUT_STOP) this.SendMsgWithStack("stopOnStepOut"); end end if event == "return" or event == "tail return" then stepOutCounter = stepOutCounter - 1; elseif event == "call" then stepOutCounter = stepOutCounter + 1; end end --在RUN时检查并改变状态 if hookLib == nil then if currentRunState == runState.RUN and jumpFlag == false and currentHookState ~= hookState.DISCONNECT_HOOK then local fileBP, G_BP = this.checkHasBreakpoint(lastRunFilePath); if fileBP == false then --文件无断点 if G_BP == true then this.changeHookState(hookState.MID_HOOK); else this.changeHookState(hookState.LITE_HOOK); end else --文件有断点, 判断函数内是否有断点 local funHasBP = this.checkfuncHasBreakpoint(lastRunFunction.linedefined, lastRunFunction.lastlinedefined, lastRunFilePath); if funHasBP then --函数定义范围内 this.changeHookState(hookState.ALL_HOOK); else this.changeHookState(hookState.MID_HOOK); end end --MID_HOOK状态下,return需要在下一次hook检查文件(return时,还是当前文件,检查文件时状态无法转换) if (event == "return" or event == "tail return") and currentHookState == hookState.MID_HOOK then this.changeHookState(hookState.ALL_HOOK); end end end end -- 向Vscode发送标准通知消息,cmdStr是消息类型 -- @cmdStr 命令字 function this.SendMsgWithStack(cmdStr) local msgTab = this.getMsgTable(cmdStr); local userFuncLevel = 0; msgTab["stack"] , userFuncLevel= this.getStackTable(); if userFuncLevel ~= 0 then lastRunFunction["func"] = debug.getinfo( (userFuncLevel - 1) , 'f').func; end this.sendMsg(msgTab); this.debugger_wait_msg(); end -- hook状态改变 -- @s 目标状态 function this.changeHookState( s ) if hookLib == nil and currentHookState == s then return; end this.printToConsole("change hook state :"..s) if s ~= hookState.DISCONNECT_HOOK then this.printToVSCode("change hook state : "..s) end currentHookState = s; if s == hookState.DISCONNECT_HOOK then --为了实现通用attach模式,require即开始hook,利用r作为时机发起连接 if openAttachMode == true then if hookLib then hookLib.lua_set_hookstate(hookState.DISCONNECT_HOOK); else debug.sethook(this.debug_hook, "r", 1000000); end else if hookLib then hookLib.endHook(); else debug.sethook(); end end elseif s == hookState.LITE_HOOK then if hookLib then hookLib.lua_set_hookstate(hookState.LITE_HOOK); else debug.sethook(this.debug_hook, "r"); end elseif s == hookState.MID_HOOK then if hookLib then hookLib.lua_set_hookstate(hookState.MID_HOOK); else debug.sethook(this.debug_hook, "rc"); end elseif s == hookState.ALL_HOOK then if hookLib then hookLib.lua_set_hookstate(hookState.ALL_HOOK); else debug.sethook(this.debug_hook, "lrc");end end --coroutine if hookLib == nil then this.changeCoroutineHookState(); end end -- 运行状态机,状态变更 -- @s 目标状态 -- @isFromHooklib 1:从libc库中发来的状态改变 | 0:lua发来的状态改变 function this.changeRunState(s , isFromHooklib) local msgFrom; if isFromHooklib == 1 then msgFrom = "libc"; else msgFrom = "lua"; end --WAIT_CMD状态会等待接收消息,以下两个状态下不能发消息 this.printToConsole("changeRunState :"..s.. " | from:"..msgFrom); if s ~= runState.DISCONNECT and s ~= runState.WAIT_CMD then this.printToVSCode("changeRunState :"..s.." | from:"..msgFrom); end if hookLib ~= nil and isFromHooklib ~= 1 then hookLib.lua_set_runstate(s); end currentRunState = s; --状态切换时,清除记录栈信息的状态 currentCallStack = {}; variableRefTab = {}; variableRefIdx = 1; end -- 修改协程状态 -- @s hook标志位 function this.changeCoroutineHookState(s) s = s or currentHookState; this.printToConsole("change [Coroutine] HookState: "..tostring(s)); for k ,co in pairs(coroutinePool) do if coroutine.status(co) == "dead" then table.remove(coroutinePool, k) else if s == hookState.DISCONNECT_HOOK then if openAttachMode == true then debug.sethook(co, this.debug_hook, "r", 1000000); else debug.sethook(co, this.debug_hook, ""); end elseif s == hookState.LITE_HOOK then debug.sethook(co , this.debug_hook, "r"); elseif s == hookState.MID_HOOK then debug.sethook(co , this.debug_hook, "rc"); elseif s == hookState.ALL_HOOK then debug.sethook(co , this.debug_hook, "lrc"); end end end end -------------------------变量处理相关----------------------------- --清空REPL的env环境 function this.clearEnv() if this.getTableMemberNum(env) > 0 then --清空env table env = setmetatable({}, getmetatable(env)); end end --返回REPL的env环境 function this.showEnv() return env; end -- 用户观察table的查找函数。用tableVarName作为key去查逐层级查找realVar是否匹配 -- @tableVarName 是用户观察的变量名,已经按层级被解析成table。比如用户输出a.b.c,tableVarName是 a = { b = { c } } -- @realVar 是待查询 table -- @return 返回查到的table。没查到返回nil function this.findTableVar( tableVarName, realVar) if type(tableVarName) ~= "table" or type(realVar) ~= "table" then return nil; end local layer = 2; local curVar = realVar; local jumpOutFlag = false; repeat if tableVarName[layer] ~= nil then --这里优先展示数字key,比如a{"1" = "aa", [1] = "bb"} 会展示[1]的值 local tmpCurVar = nil; xpcall(function() tmpCurVar = curVar[tonumber(tableVarName[layer])]; end , function() tmpCurVar = nil end ); if tmpCurVar == nil then xpcall(function() curVar = curVar[tostring(tableVarName[layer])]; end , function() curVar = nil end ); else curVar = tmpCurVar; end layer = layer + 1; if curVar == nil then return nil; end else --找到 jumpOutFlag = true; end until(jumpOutFlag == true) return curVar; end -- 根据传入信息生成返回的变量信息 -- @variableName 变量名 -- @variableIns 变量实例 -- @return 包含变量信息的格式化table function this.createWatchedVariableInfo(variableName, variableIns) local var = {}; var.name = variableName; var.type = tostring(type(variableIns)); xpcall(function() var.value = tostring(variableIns) end , function() var.value = tostring(type(variableIns)) .. " [value can't trans to string]" end ); var.variablesReference = "0"; --这个地方必须用“0”, 以免variableRefTab[0]出错 if var.type == "table" or var.type == "function" or var.type == "userdata" then var.variablesReference = variableRefIdx; variableRefTab[variableRefIdx] = variableIns; variableRefIdx = variableRefIdx + 1; if var.type == "table" then local memberNum = this.getTableMemberNum(variableIns); var.value = memberNum .." Members ".. var.value; end elseif var.type == "string" then var.value = '"' ..variableIns.. '"'; end return var; end -- 设置 global 变量 -- @varName 被修改的变量名 -- @newValue 新的值 function this.setGlobal(varName, newValue) _G[varName] = newValue; this.printToVSCode("[setVariable success] 已设置 _G.".. varName .. " = " .. tostring(newValue) ); return true; end -- 设置 upvalue 变量 -- @varName 被修改的变量名 -- @newValue 新的值 -- @stackId 变量所在stack栈层 -- @tableVarName 变量名拆分成的数组 function this.setUpvalue(varName, newValue, stackId, tableVarName) local ret = false; local upTable = this.getUpValueVariable(currentCallStack[stackId - 1 ].func, true); for i, realVar in ipairs(upTable) do if realVar.name == varName then if #tableVarName > 0 and type(realVar) == "table" then --处理a.b.c的table类型 local findRes = this.findTableVar(tableVarName, variableRefTab[realVar.variablesReference]); if findRes ~= nil then --命中 local setVarRet = debug.setupvalue (currentCallStack[stackId - 1 ].func, i, newValue); if setVarRet == varName then this.printToConsole("[setVariable success1] 已设置 upvalue ".. varName .. " = " .. tostring(newValue) ); ret = true; else this.printToConsole("[setVariable error1] 未能设置 upvalue ".. varName .. " = " .. tostring(newValue).." , 返回结果: ".. tostring(setVarRet)); end return ret; end else --命中 local setVarRet = debug.setupvalue (currentCallStack[stackId - 1 ].func, i, newValue); if setVarRet == varName then this.printToConsole("[setVariable success] 已设置 upvalue ".. varName .. " = " .. tostring(newValue) ); ret = true; else this.printToConsole("[setVariable error] 未能设置 upvalue ".. varName .. " = " .. tostring(newValue).." , 返回结果: ".. tostring(setVarRet)); end return ret; end end end return ret; end -- 设置local 变量 -- @varName 被修改的变量名 -- @newValue 新的值 -- @tableVarName 变量名拆分成的数组 function this.setLocal( varName, newValue, tableVarName, stackId) local istackId = tonumber(stackId); local offset = (istackId and istackId - 2) or 0; local layerVarTab, ly = this.getVariable(nil , true, offset); local ret = false; for i, realVar in ipairs(layerVarTab) do if realVar.name == varName then if #tableVarName > 0 and type(realVar) == "table" then --处理a.b.c的table类型 local findRes = this.findTableVar(tableVarName, variableRefTab[realVar.variablesReference]); if findRes ~= nil then --命中 local setVarRet = debug.setlocal(ly , layerVarTab[i].index, newValue); if setVarRet == varName then this.printToConsole("[setVariable success1] 已设置 local ".. varName .. " = " .. tostring(newValue) ); ret = true; else this.printToConsole("[setVariable error1] 未能设置 local ".. varName .. " = " .. tostring(newValue).." , 返回结果: ".. tostring(setVarRet)); end return ret; end else local setVarRet = debug.setlocal(ly , layerVarTab[i].index, newValue); if setVarRet == varName then this.printToConsole("[setVariable success] 已设置 local ".. varName .. " = " .. tostring(newValue) ); ret = true; else this.printToConsole("[setVariable error] 未能设置 local ".. varName .. " = " .. tostring(newValue) .." , 返回结果: ".. tostring(setVarRet)); end return ret; end end end return ret; end -- 设置变量的值 -- @varName 被修改的变量名 -- @curStackId 调用栈层级(仅在固定栈层查找) -- @newValue 新的值 -- @limit 限制符, 10000表示仅在局部变量查找 ,20000 global, 30000 upvalue function this.setVariableValue (varName, stackId, newValue , limit) this.printToConsole("setVariableValue | varName:" .. tostring(varName) .. " stackId:".. tostring(stackId) .." newValue:" .. tostring(newValue) .." limit:"..tostring(limit) ) if tostring(varName) == nil or tostring(varName) == "" then --赋值错误 this.printToConsole("[setVariable Error] 被赋值的变量名为空", 2 ); this.printToVSCode("[setVariable Error] 被赋值的变量名为空", 2 ); return false; end --支持a.b.c形式。切割varName local tableVarName = {}; if varName:match('%.') then tableVarName = this.stringSplit(varName , '%.'); if type(tableVarName) ~= "table" or #tableVarName < 1 then return false; end varName = tableVarName[1]; end if limit == "local" then local ret = this.setLocal( varName, newValue, tableVarName, stackId); return ret; elseif limit == "upvalue" then local ret = this.setUpvalue(varName, newValue, stackId, tableVarName); return ret elseif limit == "global" then local ret = this.setGlobal(varName, newValue); return ret; else local ret = this.setLocal( varName, newValue, tableVarName, stackId) or this.setUpvalue(varName, newValue, stackId, tableVarName) or this.setGlobal(varName, newValue); this.printToConsole("set Value res :".. tostring(ret)); return ret; end end -- 按照local -> upvalue -> _G 顺序查找观察变量 -- @varName 用户输入的变量名 -- @stackId 调用栈层级(仅在固定栈层查找) -- @isFormatVariable 是否把变量格式化为VSCode接收的形式 -- @return 查到返回信息,查不到返回nil function this.getWatchedVariable( varName , stackId , isFormatVariable ) this.printToConsole("getWatchedVariable | varName:" .. tostring(varName) .. " stackId:".. tostring(stackId) .." isFormatVariable:" .. tostring(isFormatVariable) ) if tostring(varName) == nil or tostring(varName) == "" then return nil; end if type(currentCallStack[stackId - 1]) ~= "table" or type(currentCallStack[stackId - 1].func) ~= "function" then local str = "getWatchedVariable currentCallStack " .. stackId - 1 .. " Error\n" .. this.serializeTable(currentCallStack, "currentCallStack"); this.printToVSCode(str, 2); return nil; end --orgname 记录原名字. 用来处理a.b.c的形式 local orgname = varName; --支持a.b.c形式。切割varName local tableVarName = {}; if varName:match('%.') then tableVarName = this.stringSplit(varName , '%.'); if type(tableVarName) ~= "table" or #tableVarName < 1 then return nil; end varName = tableVarName[1]; end --用来返回,带有查到变量的table local varTab = {}; local ly = this.getSpecificFunctionStackLevel(currentCallStack[stackId - 1].func); local layerVarTab = this.getVariable(ly, isFormatVariable); local upTable = this.getUpValueVariable(currentCallStack[stackId - 1 ].func, isFormatVariable); local travelTab = {}; table.insert(travelTab, layerVarTab); table.insert(travelTab, upTable); for _, layerVarTab in ipairs(travelTab) do for i,realVar in ipairs(layerVarTab) do if realVar.name == varName then if #tableVarName > 0 and type(realVar) == "table" then --处理a.b.c的table类型 local findRes = this.findTableVar(tableVarName, variableRefTab[realVar.variablesReference]); if findRes ~= nil then --命中 if isFormatVariable then local var = this.createWatchedVariableInfo( orgname , findRes ); table.insert(varTab, var); return varTab; else return findRes.value; end end else --命中 if isFormatVariable then table.insert(varTab, realVar); return varTab; else return realVar.value; end end end end end --在全局变量_G中查找 if _G[varName] ~= nil then --命中 if #tableVarName > 0 and type(_G[varName]) == "table" then local findRes = this.findTableVar(tableVarName, _G[varName]); if findRes ~= nil then if isFormatVariable then local var = this.createWatchedVariableInfo( orgname , findRes ); table.insert(varTab, var); return varTab; else return findRes; end end else if isFormatVariable then local var = this.createWatchedVariableInfo( varName , _G[varName] ); table.insert(varTab, var); return varTab; else return _G[varName]; end end end this.printToConsole("getWatchedVariable not find variable"); return nil; end -- 查询引用变量 -- @refStr 变量记录id(variableRefTab索引) -- @return 格式化的变量信息table function this.getVariableRef( refStr ) local varRef = tonumber(refStr); local varTab = {}; if tostring(type(variableRefTab[varRef])) == "table" then for n,v in pairs(variableRefTab[varRef]) do local var = {}; if type(n) == "string" then var.name = '"' .. tostring(n) .. '"'; else var.name = tostring(n); end var.type = tostring(type(v)); xpcall(function() var.value = tostring(v) end , function() var.value = tostring(type(v)) .. " [value can't trans to string]" end ); var.variablesReference = "0"; if var.type == "table" or var.type == "function" or var.type == "userdata" then var.variablesReference = variableRefIdx; variableRefTab[variableRefIdx] = v; variableRefIdx = variableRefIdx + 1; if var.type == "table" then local memberNum = this.getTableMemberNum(v); var.value = memberNum .." Members ".. ( var.value or '' ); end elseif var.type == "string" then var.value = '"' ..v.. '"'; end table.insert(varTab, var); end --获取一下mtTable local mtTab = getmetatable(variableRefTab[varRef]); if mtTab ~= nil and type(mtTab) == "table" then local var = {}; var.name = "_Metatable_"; var.type = tostring(type(mtTab)); xpcall(function() var.value = "元表 "..tostring(mtTab); end , function() var.value = "元表 [value can't trans to string]" end ); var.variablesReference = variableRefIdx; variableRefTab[variableRefIdx] = mtTab; variableRefIdx = variableRefIdx + 1; table.insert(varTab, var); end elseif tostring(type(variableRefTab[varRef])) == "function" then --取upvalue varTab = this.getUpValueVariable(variableRefTab[varRef], true); elseif tostring(type(variableRefTab[varRef])) == "userdata" then --取mt table local udMtTable = getmetatable(variableRefTab[varRef]); if udMtTable ~= nil and type(udMtTable) == "table" then local var = {}; var.name = "_Metatable_"; var.type = tostring(type(udMtTable)); xpcall(function() var.value = "元表 "..tostring(udMtTable); end , function() var.value = "元表 [value can't trans to string]" end ); var.variablesReference = variableRefIdx; variableRefTab[variableRefIdx] = udMtTable; variableRefIdx = variableRefIdx + 1; table.insert(varTab, var); if traversalUserData and udMtTable.__pairs ~= nil and type(udMtTable.__pairs) == "function" then for n,v in pairs(variableRefTab[varRef]) do local var = {}; var.name = tostring(n); var.type = tostring(type(v)); xpcall(function() var.value = tostring(v) end , function() var.value = tostring(type(v)) .. " [value can't trans to string]" end ); var.variablesReference = "0"; if var.type == "table" or var.type == "function" or var.type == "userdata" then var.variablesReference = variableRefIdx; variableRefTab[variableRefIdx] = v; variableRefIdx = variableRefIdx + 1; if var.type == "table" then local memberNum = this.getTableMemberNum(v); var.value = memberNum .." Members ".. ( var.value or '' ); end elseif var.type == "string" then var.value = '"' ..v.. '"'; end table.insert(varTab, var); end end end end return varTab; end -- 获取全局变量。方法和内存管理中获取全局变量的方法一样 -- @return 格式化的信息, 若未找到返回空table function this.getGlobalVariable( ... ) --成本比较高,这里只能遍历_G中的所有变量,并去除系统变量,再返回给客户端 local varTab = {}; for k,v in pairs(_G) do local var = {}; var.name = tostring(k); var.type = tostring(type(v)); xpcall(function() var.value = tostring(v) end , function() var.value = tostring(type(v)) .." [value can't trans to string]" end ); var.variablesReference = "0"; if var.type == "table" or var.type == "function" or var.type == "userdata" then var.variablesReference = variableRefIdx; variableRefTab[variableRefIdx] = v; variableRefIdx = variableRefIdx + 1; if var.type == "table" then local memberNum = this.getTableMemberNum(v); var.value = memberNum .." Members ".. ( var.value or '' ); end elseif var.type == "string" then var.value = '"' ..v.. '"'; end table.insert(varTab, var); end return varTab; end -- 获取upValues -- @isFormatVariable true返回[值] true返回[格式化的数据] function this.getUpValueVariable( checkFunc , isFormatVariable) local isGetValue = true; if isFormatVariable == true then isGetValue = false; end --通过Debug获取当前函数的Func checkFunc = checkFunc or lastRunFunction.func; local varTab = {}; if checkFunc == nil then return varTab; end local i = 1 repeat local n, v = debug.getupvalue(checkFunc, i) if n then local var = {}; var.name = n; var.type = tostring(type(v)); var.variablesReference = "0"; if isGetValue == false then xpcall(function() var.value = tostring(v) end , function() var.value = tostring(type(v)) .. " [value can't trans to string]" end ); if var.type == "table" or var.type == "function" or var.type == "userdata" then var.variablesReference = variableRefIdx; variableRefTab[variableRefIdx] = v; variableRefIdx = variableRefIdx + 1; if var.type == "table" then local memberNum = this.getTableMemberNum(v); var.value = memberNum .." Members ".. ( var.value or '' ); end elseif var.type == "string" then var.value = '"' ..v.. '"'; end else var.value = v; end table.insert(varTab, var); i = i + 1 end until not n return varTab; end -- 获取局部变量 checkLayer是要查询的层级,如果不设置则查询当前层级 -- @isFormatVariable 是否取值,true:取值的tostring function this.getVariable( checkLayer, isFormatVariable , offset) local isGetValue = true; if isFormatVariable == true then isGetValue = false; end local ly = 0; if checkLayer ~= nil and type(checkLayer) == "number" then ly = checkLayer + 1; else ly = this.getSpecificFunctionStackLevel(lastRunFunction.func); end if ly == 0 then this.printToVSCode("[error]获取层次失败!", 2); return; end local varTab = {}; local stacklayer = ly; local k = 1; if type(offset) == 'number' then stacklayer = stacklayer + offset; end repeat local n, v = debug.getlocal(stacklayer, k) if n == nil then break; end --(*temporary)是系统变量,过滤掉。这里假设(*temporary)仅出现在最后 if "(*temporary)" ~= tostring(n) then local var = {}; var.name = n; var.type = tostring(type(v)); var.variablesReference = "0"; var.index = k; if isGetValue == false then xpcall(function() var.value = tostring(v) end , function() var.value = tostring(type(v)) .. " [value can't trans to string]" end ); if var.type == "table" or var.type == "function" or var.type == "userdata" then var.variablesReference = variableRefIdx; variableRefTab[variableRefIdx] = v; variableRefIdx = variableRefIdx + 1; if var.type == "table" then local memberNum = this.getTableMemberNum(v); var.value = memberNum .." Members ".. ( var.value or '' ); end elseif var.type == "string" then var.value = '"' ..v.. '"'; end else var.value = v; end local sameIdx = this.checkSameNameVar(varTab, var); if sameIdx ~= 0 then varTab[sameIdx] = var; else table.insert(varTab, var); end end k = k + 1 until n == nil return varTab, stacklayer - 1; end --检查变量列表中的同名变量 function this.checkSameNameVar(varTab, var) for k , v in pairs(varTab) do if v.name == var.name then return k; end end return 0; end -- 执行表达式 function this.processExp(msgTable) local retString; local var = {}; var.isSuccess = "true"; if msgTable ~= nil then local expression = this.trim(tostring(msgTable.Expression)); local isCmd = false; if isCmd == false then --兼容旧版p 命令 if expression:find("p ", 1, true) == 1 then expression = expression:sub(3); end local expressionWithReturn = "return " .. expression; local f = debugger_loadString(expressionWithReturn) or debugger_loadString(expression); --判断结果,如果表达式错误会返回nil if type(f) == "function" then if _VERSION == "Lua 5.1" then setfenv(f , env); else debug.setupvalue(f, 1, env); end --表达式要有错误处理 xpcall(function() retString = f() end , function() retString = "输入错误指令。\n + 请检查指令是否正确\n + 指令仅能在[暂停在断点时]输入, 请不要在程序持续运行时输入"; var.isSuccess = false; end) else retString = "指令执行错误。\n + 请检查指令是否正确\n + 可以直接输入表达式,执行函数或变量名,并观察执行结果"; var.isSuccess = false; end end end var.name = "Exp"; var.type = tostring(type(retString)); xpcall(function() var.value = tostring(retString) end , function(e) var.value = tostring(type(retString)) .. " [value can't trans to string] ".. e; var.isSuccess = false; end); var.variablesReference = "0"; if var.type == "table" or var.type == "function" or var.type == "userdata" then variableRefTab[variableRefIdx] = retString; var.variablesReference = variableRefIdx; variableRefIdx = variableRefIdx + 1; if var.type == "table" then local memberNum = this.getTableMemberNum(retString); var.value = memberNum .." Members ".. var.value; end elseif var.type == "string" then var.value = '"' ..retString.. '"'; end --string执行完毕后清空env环境 this.clearEnv(); local retTab = {} table.insert(retTab ,var); return retTab; end --执行变量观察表达式 function this.processWatchedExp(msgTable) local retString; local expression = "return ".. tostring(msgTable.varName) this.printToConsole("processWatchedExp | expression: " .. expression); local f = debugger_loadString(expression); local var = {}; var.isSuccess = "true"; --判断结果,如果表达式错误会返回nil if type(f) == "function" then --表达式正确 if _VERSION == "Lua 5.1" then setfenv(f , env); else debug.setupvalue(f, 1, env); end xpcall(function() retString = f() end , function() retString = "输入了错误的变量信息"; var.isSuccess = "false"; end) else retString = "未能找到变量的值"; var.isSuccess = "false"; end var.name = msgTable.varName; var.type = tostring(type(retString)); xpcall(function() var.value = tostring(retString) end , function() var.value = tostring(type(retString)) .. " [value can't trans to string]"; var.isSuccess = "false"; end ); var.variablesReference = "0"; if var.type == "table" or var.type == "function" or var.type == "userdata" then variableRefTab[variableRefIdx] = retString; var.variablesReference = variableRefIdx; variableRefIdx = variableRefIdx + 1; if var.type == "table" then local memberNum = this.getTableMemberNum(retString); var.value = memberNum .." Members ".. var.value; end elseif var.type == "string" then var.value = '"' ..retString.. '"'; end local retTab = {} table.insert(retTab ,var); return retTab; end function tools.getFileSource() local info = debug.getinfo(1, "S") for k,v in pairs(info) do if k == "source" then return v; end end end --序列化并打印table function tools.printTable(t, name ,indent) local str = (tools.show(t, name, indent)); print(str); end --序列化并返回table function tools.serializeTable(t, name, indent) local str = (tools.show(t, name, indent)) return str end --[[ Author: Julio Manuel Fernandez-Diaz Date: January 12, 2007 Modified slightly by RiciLake to avoid the unnecessary table traversal in tablecount() Formats tables with cycles recursively to any depth. The output is returned as a string. References to other tables are shown as values. Self references are indicated. The string returned is "Lua code", which can be procesed (in the case in which indent is composed by spaces or "--"). Userdata and function keys and values are shown as strings, which logically are exactly not equivalent to the original code. This routine can serve for pretty formating tables with proper indentations, apart from printing them: print(table.show(t, "t")) -- a typical use Heavily based on "Saving tables with cycles", PIL2, p. 113. Arguments: t is the table. name is the name of the table (optional) indent is a first indentation (optional). --]] function tools.show(t, name, indent) local cart -- a container local autoref -- for self references local function isemptytable(t) return next(t) == nil end local function basicSerialize (o) local so = tostring(o) if type(o) == "function" then local info = debug.getinfo(o, "S") -- info.name is nil because o is not a calling level if info.what == "C" then return string.format("%q", so .. ", C function") else -- the information is defined through lines return string.format("%q", so .. ", defined in (" .. info.linedefined .. "-" .. info.lastlinedefined .. ")" .. info.source) end elseif type(o) == "number" or type(o) == "boolean" then return so else return string.format("%q", so) end end local function addtocart (value, name, indent, saved, field) indent = indent or "" saved = saved or {} field = field or name cart = cart .. indent .. field if type(value) ~= "table" then cart = cart .. " = " .. basicSerialize(value) .. ";\n" else if saved[value] then cart = cart .. " = {}; -- " .. saved[value] .. " (self reference)\n" autoref = autoref .. name .. " = " .. saved[value] .. ";\n" else saved[value] = name --if tablecount(value) == 0 then if isemptytable(value) then cart = cart .. " = {};\n" else cart = cart .. " = {\n" for k, v in pairs(value) do k = basicSerialize(k) local fname = string.format("%s[%s]", name, k) field = string.format("[%s]", k) -- three spaces between levels addtocart(v, fname, indent .. " ", saved, field) end cart = cart .. indent .. "};\n" end end end end name = name or "PRINT_Table" if type(t) ~= "table" then return name .. " = " .. basicSerialize(t) end cart, autoref = "", "" addtocart(t, name, indent) return cart .. autoref end ----------------------------------------------------------------------------- -- JSON4Lua: JSON encoding / decoding support for the Lua language. -- json Module. -- Author: Craig Mason-Jones -- Homepage: http://github.com/craigmj/json4lua/ -- Version: 1.0.0 -- This module is released under the MIT License (MIT). -- Please see LICENCE.txt for details. -- -- USAGE: -- This module exposes two functions: -- json.encode(o) -- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string. -- json.decode(json_string) -- Returns a Lua object populated with the data encoded in the JSON string json_string. -- -- REQUIREMENTS: -- compat-5.1 if using Lua 5.0 -- -- CHANGELOG -- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix). -- Fixed Lua 5.1 compatibility issues. -- Introduced json.null to have null values in associative arrays. -- json.encode() performance improvement (more than 50%) through table.concat rather than .. -- Introduced decode ability to ignore /**/ comments in the JSON string. -- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays. ----------------------------------------------------------------------------- function tools.createJson() ----------------------------------------------------------------------------- -- Imports and dependencies ----------------------------------------------------------------------------- local math = require('math') local string = require("string") local table = require("table") ----------------------------------------------------------------------------- -- Module declaration ----------------------------------------------------------------------------- local json = {} -- Public namespace local json_private = {} -- Private namespace -- Public constants json.EMPTY_ARRAY={} json.EMPTY_OBJECT={} -- Public functions -- Private functions local decode_scanArray local decode_scanComment local decode_scanConstant local decode_scanNumber local decode_scanObject local decode_scanString local decode_scanWhitespace local encodeString local isArray local isEncodable ----------------------------------------------------------------------------- -- PUBLIC FUNCTIONS ----------------------------------------------------------------------------- --- Encodes an arbitrary Lua object / variable. -- @param v The Lua object / variable to be JSON encoded. -- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode) function json.encode (v) -- Handle nil values if v==nil then return "null" end local vtype = type(v) -- Handle strings if vtype=='string' then return '"' .. json_private.encodeString(v) .. '"' -- Need to handle encoding in string end -- Handle booleans if vtype=='number' or vtype=='boolean' then return tostring(v) end -- Handle tables if vtype=='table' then local rval = {} -- Consider arrays separately local bArray, maxCount = isArray(v) if bArray then for i = 1,maxCount do table.insert(rval, json.encode(v[i])) end else -- An object, not an array for i,j in pairs(v) do if isEncodable(i) and isEncodable(j) then table.insert(rval, '"' .. json_private.encodeString(i) .. '":' .. json.encode(j)) end end end if bArray then return '[' .. table.concat(rval,',') ..']' else return '{' .. table.concat(rval,',') .. '}' end end -- Handle null values if vtype=='function' and v==json.null then return 'null' end assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. tostring(v)) end --- Decodes a JSON string and returns the decoded value as a Lua data structure / value. -- @param s The string to scan. -- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1. -- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil, -- and the position of the first character after -- the scanned JSON object. function json.decode(s, startPos) startPos = startPos and startPos or 1 startPos = decode_scanWhitespace(s,startPos) assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']') local curChar = string.sub(s,startPos,startPos) -- Object if curChar=='{' then return decode_scanObject(s,startPos) end -- Array if curChar=='[' then return decode_scanArray(s,startPos) end -- Number if string.find("+-0123456789.e", curChar, 1, true) then return decode_scanNumber(s,startPos) end -- String if curChar==[["]] or curChar==[[']] then return decode_scanString(s,startPos) end if string.sub(s,startPos,startPos+1)=='/*' then return json.decode(s, decode_scanComment(s,startPos)) end -- Otherwise, it must be a constant return decode_scanConstant(s,startPos) end --- The null function allows one to specify a null value in an associative array (which is otherwise -- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null } function json.null() return json.null -- so json.null() will also return null ;-) end ----------------------------------------------------------------------------- -- Internal, PRIVATE functions. -- Following a Python-like convention, I have prefixed all these 'PRIVATE' -- functions with an underscore. ----------------------------------------------------------------------------- --- Scans an array from JSON into a Lua object -- startPos begins at the start of the array. -- Returns the array and the next starting position -- @param s The string being scanned. -- @param startPos The starting position for the scan. -- @return table, int The scanned array as a table, and the position of the next character to scan. function decode_scanArray(s,startPos) local array = {} -- The return value local stringLen = string.len(s) assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s ) startPos = startPos + 1 -- Infinite loop for array elements local index = 1 repeat startPos = decode_scanWhitespace(s,startPos) assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.') local curChar = string.sub(s,startPos,startPos) if (curChar==']') then return array, startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.') local object object, startPos = json.decode(s,startPos) array[index] = object index = index + 1 until false end --- Scans a comment and discards the comment. -- Returns the position of the next character following the comment. -- @param string s The JSON string to scan. -- @param int startPos The starting position of the comment function decode_scanComment(s, startPos) assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos) local endPos = string.find(s,'*/',startPos+2) assert(endPos~=nil, "Unterminated comment in string at " .. startPos) return endPos+2 end --- Scans for given constants: true, false or null -- Returns the appropriate Lua type, and the position of the next character to read. -- @param s The string being scanned. -- @param startPos The position in the string at which to start scanning. -- @return object, int The object (true, false or nil) and the position at which the next character should be -- scanned. function decode_scanConstant(s, startPos) local consts = { ["true"] = true, ["false"] = false, ["null"] = nil } local constNames = {"true","false","null"} for i,k in pairs(constNames) do if string.sub(s,startPos, startPos + string.len(k) -1 )==k then return consts[k], startPos + string.len(k) end end assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos) end --- Scans a number from the JSON encoded string. -- (in fact, also is able to scan numeric +- eqns, which is not -- in the JSON spec.) -- Returns the number, and the position of the next character -- after the number. -- @param s The string being scanned. -- @param startPos The position at which to start scanning. -- @return number, int The extracted number and the position of the next character to scan. function decode_scanNumber(s,startPos) local endPos = startPos+1 local stringLen = string.len(s) local acceptableChars = "+-0123456789.e" while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true) and endPos<=stringLen ) do endPos = endPos + 1 end -- local stringValue = 'return ' .. string.sub(s, startPos, endPos - 1) -- local stringEval = loadstring(stringValue) -- assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos) local numberValue = string.sub(s, startPos, endPos - 1) return numberValue, endPos end --- Scans a JSON object into a Lua object. -- startPos begins at the start of the object. -- Returns the object and the next starting position. -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return table, int The scanned object as a table and the position of the next character to scan. function decode_scanObject(s,startPos) local object = {} local stringLen = string.len(s) local key, value assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s) startPos = startPos + 1 repeat startPos = decode_scanWhitespace(s,startPos) assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.') local curChar = string.sub(s,startPos,startPos) if (curChar=='}') then return object,startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.') -- Scan the key key, startPos = json.decode(s,startPos) assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) startPos = decode_scanWhitespace(s,startPos) assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos) startPos = decode_scanWhitespace(s,startPos+1) assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) value, startPos = json.decode(s,startPos) object[key]=value until false -- infinite loop while key-value pairs are found end -- START SoniEx2 -- Initialize some things used by decode_scanString -- You know, for efficiency local escapeSequences = { ["\\t"] = "\t", ["\\f"] = "\f", ["\\r"] = "\r", ["\\n"] = "\n", ["\\b"] = "\b" } setmetatable(escapeSequences, {__index = function(t,k) -- skip "\" aka strip escape return string.sub(k,2) end}) -- END SoniEx2 --- Scans a JSON string from the opening inverted comma or single quote to the -- end of the string. -- Returns the string extracted as a Lua string, -- and the position of the next non-string character -- (after the closing inverted comma or single quote). -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return string, int The extracted string as a Lua string, and the next character to parse. function decode_scanString(s,startPos) assert(startPos, 'decode_scanString(..) called without start position') local startChar = string.sub(s,startPos,startPos) -- START SoniEx2 -- PS: I don't think single quotes are valid JSON assert(startChar == [["]] or startChar == [[']],'decode_scanString called for a non-string') --assert(startPos, "String decoding failed: missing closing " .. startChar .. " for string at position " .. oldStart) local t = {} local i,j = startPos,startPos while string.find(s, startChar, j+1) ~= j+1 do local oldj = j i,j = string.find(s, "\\.", j+1) local x,y = string.find(s, startChar, oldj+1) if not i or x < i then i,j = x,y-1 end table.insert(t, string.sub(s, oldj+1, i-1)) if string.sub(s, i, j) == "\\u" then local a = string.sub(s,j+1,j+4) j = j + 4 local n = tonumber(a, 16) assert(n, "String decoding failed: bad Unicode escape " .. a .. " at position " .. i .. " : " .. j) -- math.floor(x/2^y) == lazy right shift -- a % 2^b == bitwise_and(a, (2^b)-1) -- 64 = 2^6 -- 4096 = 2^12 (or 2^6 * 2^6) local x if n < 0x80 then x = string.char(n % 0x80) elseif n < 0x800 then -- [110x xxxx] [10xx xxxx] x = string.char(0xC0 + (math.floor(n/64) % 0x20), 0x80 + (n % 0x40)) else -- [1110 xxxx] [10xx xxxx] [10xx xxxx] x = string.char(0xE0 + (math.floor(n/4096) % 0x10), 0x80 + (math.floor(n/64) % 0x40), 0x80 + (n % 0x40)) end table.insert(t, x) else table.insert(t, escapeSequences[string.sub(s, i, j)]) end end table.insert(t,string.sub(j, j+1)) assert(string.find(s, startChar, j+1), "String decoding failed: missing closing " .. startChar .. " at position " .. j .. "(for string at position " .. startPos .. ")") return table.concat(t,""), j+2 -- END SoniEx2 end --- Scans a JSON string skipping all whitespace from the current start position. -- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached. -- @param s The string being scanned -- @param startPos The starting position where we should begin removing whitespace. -- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string -- was reached. function decode_scanWhitespace(s,startPos) local whitespace=" \n\r\t" local stringLen = string.len(s) while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do startPos = startPos + 1 end return startPos end --- Encodes a string to be JSON-compatible. -- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-) -- @param s The string to return as a JSON encoded (i.e. backquoted string) -- @return The string appropriately escaped. local escapeList = { ['"'] = '\\"', ['\\'] = '\\\\', ['/'] = '\\/', ['\b'] = '\\b', ['\f'] = '\\f', ['\n'] = '\\n', ['\r'] = '\\r', ['\t'] = '\\t' } function json_private.encodeString(s) local s = tostring(s) return s:gsub(".", function(c) return escapeList[c] end) -- SoniEx2: 5.0 compat end -- Determines whether the given Lua type is an array or a table / dictionary. -- We consider any table an array if it has indexes 1..n for its n items, and no -- other data in the table. -- I think this method is currently a little 'flaky', but can't think of a good way around it yet... -- @param t The table to evaluate as an array -- @return boolean, number True if the table can be represented as an array, false otherwise. If true, -- the second returned value is the maximum -- number of indexed elements in the array. function isArray(t) -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable -- (with the possible exception of 'n') if (t == json.EMPTY_ARRAY) then return true, 0 end if (t == json.EMPTY_OBJECT) then return false end local maxIndex = 0 for k,v in pairs(t) do if (type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair if (not isEncodable(v)) then return false end -- All array elements must be encodable maxIndex = math.max(maxIndex,k) else if (k=='n') then if v ~= (t.n or #t) then return false end -- False if n does not hold the number of elements else -- Else of (k=='n') if isEncodable(v) then return false end end -- End of (k~='n') end -- End of k,v not an indexed pair end -- End of loop across all pairs return true, maxIndex end --- Determines whether the given Lua object / table / variable can be JSON encoded. The only -- types that are JSON encodable are: string, boolean, number, nil, table and json.null. -- In this implementation, all other types are ignored. -- @param o The object to examine. -- @return boolean True if the object should be JSON encoded, false if it should be ignored. function isEncodable(o) local t = type(o) return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==json.null) end return json end -- Sourced from http://lua-users.org/wiki/BaseSixtyFour -- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <[email protected]> -- licensed under the terms of the LGPL2 -- character table string local base64CharTable='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- encoding function tools.base64encode(data) return ((data:gsub('.', function(x) local r,b='',x:byte() for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end return r; end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x) if (#x < 6) then return '' end local c=0 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end return base64CharTable:sub(c+1,c+1) end)..({ '', '==', '=' })[#data%3+1]) end -- decoding function tools.base64decode(data) data = string.gsub(data, '[^'..base64CharTable..'=]', '') return (data:gsub('.', function(x) if (x == '=') then return '' end local r,f='',(base64CharTable:find(x)-1) for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end return r; end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) if (#x ~= 8) then return '' end local c=0 for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end return string.char(c) end)) end -- tools变量 json = tools.createJson(); --json处理 this.printToConsole("load LuaPanda success", 1); return this;
-- don't bother for Casual gamemode if SL.Global.GameMode == "Casual" then return end local player = ... local judgments = {} for i=1,GAMESTATE:GetCurrentStyle():ColumnsPerPlayer() do judgments[#judgments+1] = { W1=0, W2=0, W3=0, W4=0, W5=0, Miss=0 } end return Def.Actor{ JudgmentMessageCommand=function(self, params) if params.Player == player and params.Notes then for i,col in pairs(params.Notes) do local tns = ToEnumShortString(params.TapNoteScore) judgments[i][tns] = judgments[i][tns] + 1 end end end, OffCommand=function(self) local storage = SL[ToEnumShortString(player)].Stages.Stats[SL.Global.Stages.PlayedThisGame + 1] storage.column_judgments = judgments end }
----------------------------------------------------------------------------------------------- local title = "Trunks" local version = "0.1.4" local mname = "trunks" ----------------------------------------------------------------------------------------------- -- Code by Mossmanikin & Neuromancer abstract_trunks = {} dofile(minetest.get_modpath("trunks").."/trunks_settings.txt") dofile(minetest.get_modpath("trunks").."/generating.lua") dofile(minetest.get_modpath("trunks").."/nodes.lua") dofile(minetest.get_modpath("trunks").."/crafting.lua") ----------------------------------------------------------------------------------------------- minetest.log("action", "[Mod] "..title.." ["..version.."] ["..mname.."] Loaded...") -----------------------------------------------------------------------------------------------
--[[ Copyright (C) 2018-2020 The DMLab2D Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] local file_system = require 'system.file_system' local asserts = require 'testing.asserts' local test_runner = require 'testing.test_runner' local paths = require 'common.paths' local FILE_NAME = ... local TEST_DIR = test_runner.testDir(FILE_NAME) local EMPTY_FILE_NAME = TEST_DIR .. "empty_test_file" local TEXT_FILE_NAME = TEST_DIR .. "file_with_text.txt" local tests = {} local function readFile(file) local f = io.open(file, "rb") local content = f:read("*all") f:close() return content end function tests:readEmpty() local emptyFileContent = file_system:loadFileToString(EMPTY_FILE_NAME) asserts.EQ(emptyFileContent, '') end function tests:readBinaryFile() local textFileContent = file_system:loadFileToString(TEXT_FILE_NAME) asserts.EQ(textFileContent, readFile(TEXT_FILE_NAME)) end function tests:readSelf() local textFileContent = file_system:loadFileToString(FILE_NAME) asserts.EQ(textFileContent, readFile(FILE_NAME)) end return test_runner.run(tests)
----------------------------------------------------------------------------- -- Name: minimal.wx.lua -- Purpose: 'Minimal' wxLua sample -- Author: J Winwood -- Modified by: -- Created: 16/11/2001 -- RCS-ID: $Id: veryminimal.wx.lua,v 1.7 2008/01/22 04:45:39 jrl1 Exp $ -- Copyright: (c) 2001 J Winwood. All rights reserved. -- Licence: wxWidgets licence ----------------------------------------------------------------------------- -- Load the wxLua module, does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit package.cpath = package.cpath..";./?.dll;./?.so;../lib/?.so;../lib/vc_dll/?.dll;../lib/bcc_dll/?.dll;../lib/mingw_dll/?.dll;" require("wx") frame = nil function main() -- create the frame window frame = wx.wxFrame( wx.NULL, wx.wxID_ANY, "wxLua Very Minimal Demo", wx.wxDefaultPosition, wx.wxSize(450, 450), wx.wxDEFAULT_FRAME_STYLE ) -- show the frame window frame:Show(true) end main() -- Call wx.wxGetApp():MainLoop() last to start the wxWidgets event loop, -- otherwise the wxLua program will exit immediately. -- Does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit since the -- MainLoop is already running or will be started by the C++ program. wx.wxGetApp():MainLoop()
-- nvim-cmp highlights local lush = require("lush") local base = require("lush_jsx.base") local M = {} M = lush(function() return { -- nvim-cmp CmpItemKind {base.LushJSXYellow}, CmpItemAbbrMatch {base.LushJSXFg1}, CmpItemAbbr {base.LushJSXFg4}, CmpItemMenu {base.LushJSXAqua} } end) return M
num = 42 s = "walternate" t = "double-quotes are also fine" u = " Double brackets\n start and end\n multi-line strings." t = nil while num < 50 do num = num + 1 end if num > 40 then print("over 40") elseif s ~= "walternate" then io.write("not over 40\n") else thisIsGlobal = 5 local line = io.read() print("Winter is coming, " .. line) end foo = anUnknownVariable aBoolValue = false if not aBoolValue then print("twas false") end ans = aBoolValue and "yes" or "no" karlSum = 0 for i = 1, 100 do karlSum = karlSum + i end fredSum = 0 for j = 100, 1, -1 do fredSum = fredSum + j end repeat print("the way of the future") num = num - 1 until num == 0 function fib(n) if n < 2 then return n end return fib(n - 2) + fib(n - 1) end function adder(x) return function(y) return x + y end end a1 = adder(9) a2 = adder(36) print(a1(16)) print(a2(64)) x, y, z = 1, 2, 3, 4 function bar(a, b, c) print(a, b, c) return 4, 8, 15, 16, 23, 42 end x, y = bar("zaphod") function f(x) return x * x end f = function(x) return x * x end local function g(x) return math.sin(x) end local g = function(x) return math.sin(x) end local g g = function(x) return math.sin(x) end print "hello" print {} t = { key1 = "value1", key2 = false } print(t.key1) t.newKey = {} t.key2 = nil u = { ["@!#"] = "qbert", [{}] = 1729, [6.28] = "tau" } print(u[6.28]) a = u["@!#"] b = u[{}] function h(x) print(x.key1) end h { key1 = "Sonmi~451" } for key, val in pairs(u) do print(key, val) end print(_G["_G"] == _G) v = { "value1", "value2", 1.21, "gigawatts" } for i = 1, #v do print(v[i]) end f1 = { a = 1, b = 2 } f2 = { a = 2, b = 3 } metafraction = {} function metafraction.__add(f1, f2) local sum = {} sum.b = f1.b * f2.b sum.a = f1.a * f2.b + f2.a * f1.b return sum end setmetatable(f1, metafraction) setmetatable(f2, metafraction) s = f1 + f2 defaultFavs = { animal = "gru", food = "donuts" } myFavs = { food = "pizza" } setmetatable(myFavs, { __index = defaultFavs }) eatenBy = myFavs.animal Dog = {} function Dog:new() local newObj = { sound = "woof" } self.__index = self return setmetatable(newObj, self) end function Dog:makeSound() print("I say " .. self.sound) end mrDog = Dog:new() mrDog:makeSound() LoudDog = Dog:new() function LoudDog:makeSound() local s = self.sound .. " " print(s .. s .. s) end seymour = LoudDog:new() seymour:makeSound() function LoudDog:new() local newObj = {} self.__index = self return setmetatable(newObj, self) end
object_mobile_dressed_rebel_communication_male_01 = object_mobile_shared_dressed_rebel_communication_male_01:new { } ObjectTemplates:addTemplate(object_mobile_dressed_rebel_communication_male_01, "object/mobile/dressed_rebel_communication_male_01.iff")
dofile(ModPath .. "infcore.lua") -- If we successfully pick up an ammo pickup and we have the upgrade, charge the bulletstorm meter local ammopickup_pickup_orig = AmmoClip._pickup function AmmoClip:_pickup(unit) local result = ammopickup_pickup_orig(self, unit) if result and unit == managers.player:player_unit() and managers.player:has_category_upgrade("player", "inf_charge_bulletstorm") then local bulletstorm_second_gain = managers.player:upgrade_value("player", "inf_bulletstorm_second_gain", 0) IreNFist.current_bulletstorm_charge = IreNFist.current_bulletstorm_charge + bulletstorm_second_gain -- Clamp to max if IreNFist.current_bulletstorm_charge > tweak_data.upgrades.bulletstorm_max_seconds then IreNFist.current_bulletstorm_charge = tweak_data.upgrades.bulletstorm_max_seconds end end return result end
cflags{ '-I $dir', '-isystem $builddir/pkg/freetype/include', '-isystem $builddir/pkg/fribidi/include', } nasmflags{ '-D ARCH_X86_64=1', '-D HAVE_ALIGNED_STACK=1', '-D HAVE_CPUNOP=0', '-D private_prefix=ass', '-i $srcdir/libass/', '-f elf64', '-P $outdir/PIC.asm', } pkg.hdrs = copy('$outdir/include/ass', '$srcdir/libass', {'ass.h', 'ass_types.h'}) pkg.deps = { 'pkg/freetype/headers', 'pkg/fribidi/headers', '$outdir/PIC.asm', } build('sed', '$outdir/PIC.asm', '$builddir/probe/PIC', {expr='s,#define,%define,'}) lib('libass.a', [[ libass/( ass.c ass_utils.c ass_string.c ass_strtod.c ass_library.c ass_cache.c ass_font.c ass_fontselect.c ass_render.c ass_render_api.c ass_parse.c ass_shaper.c ass_outline.c ass_drawing.c ass_rasterizer.c ass_rasterizer_c.c ass_bitmap.c ass_blur.c x86/( rasterizer.asm blend_bitmaps.asm blur.asm cpuid.asm be_blur.asm ) ) $builddir/pkg/freetype/libfreetype.a.d $builddir/pkg/fribidi/libfribidi.a ]]) fetch 'git'
local DB = require("dashboard.model.db") return function(config) local node_model = {} local mysql_config = config.store_mysql local db = DB:new(mysql_config) local table_name = 'persist_log' function node_model:get_stat(limit, group_by_day) local result, err, sql if group_by_day then sql = "SELECT stat_time, SUM(request_2xx) request_2xx,SUM(request_3xx) request_3xx,SUM(request_4xx) request_4xx,SUM(request_5xx) request_5xx,SUM(total_request_count) total_request_count,SUM(total_success_request_count) total_success_request_count,SUM(traffic_read) traffic_read,SUM(traffic_write) traffic_write,SUM(total_request_time) total_request_time " .. "FROM (SELECT DATE(stat_time) stat_time,SUM(request_2xx) request_2xx,SUM(request_3xx) request_3xx,SUM(request_4xx) request_4xx,SUM(request_5xx) request_5xx,SUM(total_request_count) total_request_count,SUM(total_success_request_count) total_success_request_count,SUM(traffic_read) traffic_read,SUM(traffic_write) traffic_write,SUM(total_request_time) total_request_time FROM " .. table_name .. " " .. "GROUP BY stat_time ) T GROUP BY stat_time ORDER BY stat_time DESC LIMIT ? " else sql = "" .. " SELECT stat_time as stat_time_old, " .. " DATE_FORMAT(stat_time, '%Y-%m-%d %H:%i') as stat_time, " .. " SUM(request_2xx) as request_2xx," .. " sum(request_3xx) as request_3xx," .. " sum(request_4xx) as request_4xx," .. " sum(request_5xx) as request_5xx," .. " sum(total_request_count) as total_request_count," .. " sum(total_success_request_count) as total_success_request_count," .. " sum(traffic_read) as traffic_read," .. " sum(traffic_write) as traffic_write," .. " sum(total_request_time) as total_request_time" .. " FROM " .. table_name .. " GROUP BY stat_time" .. " ORDER BY stat_time DESC LIMIT ?" end result, err = db:query(sql, { limit }) if not result or err or type(result) ~= "table" or #result < 1 then return nil, err else return result, err end end function node_model:get_stat_by_ip(ip, limit, group_by_day) local result, err, sql if group_by_day then sql = "SELECT op_time,stat_time,ip,SUM(request_2xx) request_2xx,SUM(request_3xx) request_3xx,SUM(request_4xx) request_4xx,SUM(request_5xx) request_5xx,SUM(total_request_count) total_request_count,SUM(total_success_request_count) total_success_request_count,SUM(traffic_read) traffic_read,SUM(traffic_write) traffic_write,SUM(total_request_time) total_request_time " .. "FROM (SELECT DATE(stat_time) stat_time,ip,SUM(request_2xx) request_2xx,SUM(request_3xx) request_3xx,SUM(request_4xx) request_4xx,SUM(request_5xx) request_5xx,SUM(total_request_count) total_request_count,SUM(total_success_request_count) total_success_request_count,SUM(traffic_read) traffic_read,SUM(traffic_write) traffic_write,SUM(total_request_time) total_request_time FROM " .. table_name .. " " .. "GROUP BY stat_time HAVING ip = ?) T GROUP BY stat_time ORDER BY stat_time DESC LIMIT ? " else sql = "SELECT * from " .. table_name .. " WHERE ip = ? ORDER BY stat_time DESC LIMIT ?" end result, err = db:query(sql, { ip, limit }) if not result or err or type(result) ~= "table" or #result < 1 then return nil, err else return result, err end end return node_model end
--- === plugins.zoom.shortcuts === --- --- Trigger Zoom Shortcuts local require = require --local log = require "hs.logger".new "actions" local application = require "hs.application" local image = require "hs.image" local config = require "cp.config" local i18n = require "cp.i18n" local tools = require "cp.tools" local imageFromPath = image.imageFromPath local keyStroke = tools.keyStroke local launchOrFocusByBundleID = application.launchOrFocusByBundleID local playErrorSound = tools.playErrorSound local mod = {} local plugin = { id = "zoom.shortcuts", group = "zoom", dependencies = { ["core.action.manager"] = "actionmanager", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Shortcuts: -- -- TODO: This needs to be i18n'ified. -------------------------------------------------------------------------------- local shortcuts = { { title = "Close the current window", modifiers = {"cmd"}, character = "w" }, { title = "Switch to portrait or landscape View, depending on current view", modifiers = {"cmd"}, character = "l" }, { title = "Switch from one tab to the next", modifiers = {"control"}, character = "t" }, { title = "Join meeting", modifiers = {"command"}, character = "j" }, { title = "Start meeting", modifiers = {"cmd","control"}, character = "v" }, { title = "Schedule meeting", modifiers = {"cmd"}, character = "j" }, { title = "Screen share using direct share", modifiers = {"cmd","control"}, character = "s" }, { title = "Mute/unmute audio ", modifiers = {"cmd","shift"}, character = "a" }, { title = "Mute audio for everyone except the host (only available to the host)", modifiers = {"cmd","control"}, character = "m" }, { title = "Unmute audio for everyone except host (only available to the host)", modifiers = {"cmd","control"}, character = "u" }, { title = "Start/stop video", modifiers = {"command", "shift"}, character = "v" }, { title = "Switch camera", modifiers = {"cmd","shift"}, character = "n" }, { title = "Start/stop screen share", modifiers = {"cmd","shift"}, character = "s" }, { title = "Pause or resume screen share", modifiers = {"cmd","shift"}, character = "t" }, { title = "Start local recording", modifiers = {"cmd","shift"}, character = "r" }, { title = "Start cloud recording", modifiers = {"command", "shift"}, character = "c" }, { title = "Pause or resume recording", modifiers = {"cmd","shift"}, character = "p" }, { title = "Switch to active speaker view or gallery view, depending on current view", modifiers = {"command", "shift"}, character = "w" }, { title = "View previous 25 participants in gallery view", modifiers = {"control"}, character = "p" }, { title = "View next 25 participants in gallery view", modifiers = {"control"}, character = "n" }, { title = "Display/hide participants panel", modifiers = {"command"}, character = "u" }, { title = "Show/hide in-meeting chat panel", modifiers = {"cmd", "shift"}, character = "h" }, { title = "Open invite window", modifiers = {"command"}, character = "i" }, { title = "Raise hand/lower hand", modifiers = {"option"}, character = "y" }, { title = "Gain remote control", modifiers = {"control","shift"}, character = "r" }, { title = "Stop remote control", modifiers = {"control","shift"}, character = "g" }, { title = "Enter or exit full screen", modifiers = {"command", "shift"}, character = "f" }, { title = "Switch to minimal window", modifiers = {"command", "shift"}, character = "m" }, { title = "Show/hide meeting controls", modifiers = {"control", "option", "command"}, character = "h" }, { title = "Toggle the Always Show meeting controls option in General settings", modifiers = {"control"}, character = [[\]] }, { title = "Prompt to End or Leave Meeting", modifiers = {"command"}, character = "w" }, { title = "Jump to chat with someone", modifiers = {"command"}, character = "k" }, { title = "Screenshot", modifiers = {"command"}, character = "t" }, { title = "Call highlighted phone number", modifiers = {"control","shift"}, character = "c" }, { title = "Accept inbound call", modifiers = {"control", "shift"}, character = "a" }, { title = "Decline inbound call", modifiers = {"control", "shift"}, character = "d" }, { title = "End current call", modifiers = {"control", "shift"}, character = "e" }, { title = "Mute/unmute mic", modifiers = {"control", "shift"}, character = "m" }, { title = "Hold/unhold call", modifiers = {"command", "shift"}, character = "h" }, } -------------------------------------------------------------------------------- -- Setup Handler: -------------------------------------------------------------------------------- local icon = imageFromPath(config.basePath .. "/plugins/skype/console/images/shortcut.png") local actionmanager = deps.actionmanager mod._handler = actionmanager.addHandler("zoom_shortcuts", "zoom") :onChoices(function(choices) for _, v in pairs(shortcuts) do choices :add(v.title) :subText("Triggers a shortcut key within Zoom") :params({ modifiers = v.modifiers, character = v.character, id = v.title }) :image(icon) :id("zoom_shortcuts_" .. "pressControl") end end) :onExecute(function(action) if launchOrFocusByBundleID("us.zoom.xos") then keyStroke(action.modifiers, action.character) else playErrorSound() end end) :onActionId(function(params) return "zoom_shortcuts" .. params.id end) return mod end return plugin
ITEM.name = "Scrap Revolver" ITEM.description = "An unusually crafted revolver using .357 rounds. Good enough for personal defense." ITEM.model = "models/weapons/yurie_rustalpha/wm-revolver.mdl" ITEM.class = "tfa_rustalpha_revolver" ITEM.weaponCategory = "secondary" ITEM.width = 2 ITEM.height = 1 ITEM.chance = 17
local animPos, lastx, lasty, jumpTypes, jumpTimes, moveDirs, jumpStarted local moveTime = 0 local backJumped, jTimer, awTime, globalWait, stageEvents, seNum, curEvent local needToDecrease local AnimList, AnimListNum local FunctionList, FunctionListNum local skipFuncList local skipping local baseInputMask = 0xFFFFFFFF local extraInputMask = baseInputMask --------------------------------Animation--------------------------------- --------------------------(In-game cinematics)---------------------------- function AddSkipFunction(anim, func, args) skipFuncList[anim] = {sfunc = func, sargs = args} end function RemoveSkipFunction(anim) skipFuncList[anim] = nil end function SetAnimSkip(bool) skipping = bool end function AnimInProgress() return AnimListNum ~= 0 end function SkipAnimation(anim) if skipFuncList[anim] == nil then return else skipFuncList[anim].sfunc(unpack(skipFuncList[anim].sargs)) end end function AddFunction(element) table.insert(FunctionList, element) FunctionListNum = FunctionListNum + 1 end function RemoveFunction() table.remove(FunctionList, 1) FunctionListNum = FunctionListNum - 1 end function ExecuteAfterAnimations() if FunctionListNum == 0 then return end FunctionList[1].func(unpack(FunctionList[1].args)) RemoveFunction() end local function updateInputMask() SetInputMask(band(baseInputMask, extraInputMask)) end local function startCinemaLock() SetCinematicMode(true) baseInputMask = bnot(gmAnimate+gmAttack+gmDown+gmHJump+gmLeft+gmLJump+gmRight+gmSlot+gmSwitch+gmTimer+gmUp+gmWeapon) updateInputMask() end local function stopCinemaLock() baseInputMask = 0xFFFFFFFF updateInputMask() SetCinematicMode(false) end function AnimSetInputMask(newExtraInputMask) extraInputMask = newExtraInputMask updateInputMask() end function AnimInit(startAnimating) lastx = 0 lasty = 0 jumpTypes = {long = gmLJump, high = gmHJump, back = gmHJump} jumpTimes = {long = 500, high = 500, back = 300, backback = 500} moveDirs = {Right = gmRight, Left = gmLeft} jumpStarted = false backJumped = false jTimer = 0 awTime = 0 globalWait = 0 stageEvents = {} seNum = 0 curEvent = 0 needToDecrease = 0 AnimList = {} AnimListNum = 0 FunctionList = {} FunctionListNum = 0 skipping = false skipFuncList = {} animPos = 1 if startAnimating then startCinemaLock() end end function AnimSwitchHog(gear) SetGearMessage(gear, band(GetGearMessage(gear), bnot(gmAllStoppable))) SwitchHog(gear) FollowGear(gear) return true end function AnimGiveState(gear, state) SetState(gear, state) return true end function AnimRemoveState(gear, state) SetState(gear, band(GetState(gear), bnot(state))) return true end function AnimGearWait(gear, time) AnimWait(gear, time) return true end function AnimUnWait() if globalWait > 0 then globalWait = globalWait - 1 end end function AnimWait(gear, time) -- gear is for compatibility with Animate globalWait = globalWait + time return true end function AnimWaitLeft() return globalWait end function AnimSay(gear, text, manner, time) HogSay(gear, text, manner, 2) if time ~= nil then AnimWait(gear, time) end return true end function AnimSound(gear, sound, time) PlaySound(sound, gear) AnimWait(gear, time) return true end function AnimTurn(gear, dir) if dir == "Right" then HogTurnLeft(gear, false) else HogTurnLeft(gear, true) end return true end function AnimFollowGear(gear) FollowGear(gear) return true end function AnimMove(gear, dir, posx, posy, maxMoveTime) local dirr = moveDirs[dir] SetGearMessage(gear, dirr) moveTime = moveTime + 1 if (maxMoveTime and moveTime > maxMoveTime) then SetGearMessage(gear, 0) SetGearPosition(gear, posx, posy) lastx = GetX(gear) lasty = GetY(gear) moveTime = 0 return true elseif GetX(gear) == posx or GetY(gear) == posy then SetGearMessage(gear, 0) lastx = GetX(gear) lasty = GetY(gear) moveTime = 0 return true end return false end function AnimJump(gear, jumpType) if jumpStarted == false then lastx = GetX(gear) lasty = GetY(gear) backJumped = false jumpStarted = true SetGearMessage(gear, jumpTypes[jumpType]) AnimGearWait(gear, jumpTimes[jumpType]) elseif jumpType == "back" and backJumped == false then backJumped = true SetGearMessage(gear, jumpTypes[jumpType]) AnimGearWait(gear, jumpTimes["backback"]) else local curx = GetX(gear) local cury = GetY(gear) if curx == lastx and cury == lasty then jumpStarted = false backJumped = false AnimGearWait(gear, 100) return true else lastx = curx lasty = cury AnimGearWait(gear, 100) end end return false end function AnimSetGearPosition(gear, destX, destY, fall) SetGearPosition(gear, destX, destY) if fall ~= false then SetGearVelocity(gear, 0, 10) end return true end function AnimDisappear(gear, destX, destY) AddVisualGear(GetX(gear)-5, GetY(gear)-5, vgtSmoke, 0, false) AddVisualGear(GetX(gear)+5, GetY(gear)+5, vgtSmoke, 0, false) AddVisualGear(GetX(gear)-5, GetY(gear)+5, vgtSmoke, 0, false) AddVisualGear(GetX(gear)+5, GetY(gear)-5, vgtSmoke, 0, false) PlaySound(sndExplosion) AnimSetGearPosition(gear, destX, destY) return true end function AnimOutOfNowhere(gear, destX, destY) if (not destX) or (not destY) then destX = GetX(gear) destY = GetY(gear) end AnimSetGearPosition(gear, destX, destY) AddVisualGear(destX, destY, vgtBigExplosion, 0, false) PlaySound(sndExplosion) AnimGearWait(gear, 50) return true end function AnimTeleportGear(gear, destX, destY) AddVisualGear(GetX(gear)-5, GetY(gear)-5, vgtSmoke, 0, false) AddVisualGear(GetX(gear)+5, GetY(gear)+5, vgtSmoke, 0, false) AddVisualGear(GetX(gear)-5, GetY(gear)+5, vgtSmoke, 0, false) AddVisualGear(GetX(gear)+5, GetY(gear)-5, vgtSmoke, 0, false) AnimSetGearPosition(gear, destX, destY) AddVisualGear(GetX(gear), GetY(gear), vgtBigExplosion, 0, false) PlaySound(sndExplosion) FollowGear(gear) AnimGearWait(gear, 50) return true end function AnimVisualGear(gear, x, y, vgType, state, critical) AddVisualGear(x, y, vgType, state, critical) return true end function AnimCaption(gear, text, time) AddCaption(text) if time == nil then return true end AnimWait(gear, time) return true end function AnimCustomFunction(gear, func, args) if args == nil then args = {} end local retval = func(unpack(args)) if retval == false then return false else return true end end function AnimInsertStepNext(step) table.insert(AnimList[1], animPos + 1, step) return true end function AnimShowMission(gear, caption, subcaption, text, icon, time) ShowMission(caption, subcaption, text, icon, time) return true end function RemoveAnim() table.remove(AnimList, 1) AnimListNum = AnimListNum - 1 end function AddAnim(animation) table.insert(AnimList, animation) AnimListNum = AnimListNum + 1 if AnimListNum == 1 then skipping = false end end function ShowAnimation() if AnimListNum == 0 then skipping = false return true else SetTurnTimeLeft(MAX_TURN_TIME) if Animate(AnimList[1]) == true then RemoveAnim() end end return false end function Animate(steps) if skipping == true then animPos = 1 stopCinemaLock() SkipAnimation(steps) return true end if globalWait ~= 0 then return false end if steps[animPos] == nil then animPos = 1 stopCinemaLock() return true end if steps[animPos].args[1] ~= CurrentHedgehog and steps[animPos].func ~= AnimWait and (steps[animPos].swh == nil or steps[animPos].swh == true) then AnimSwitchHog(steps[animPos].args[1]) end startCinemaLock() local retVal = steps[animPos].func(unpack(steps[animPos].args)) if (retVal ~= false) then animPos = animPos + 1 end return false end ------------------------------Event Handling------------------------------ function AddEvent(condFunc, condArgs, doFunc, doArgs, evType) seNum = seNum + 1 stageEvents[seNum] = {} stageEvents[seNum].cFunc = condFunc stageEvents[seNum].cArgs = condArgs stageEvents[seNum].dFunc = doFunc stageEvents[seNum].dArgs = doArgs stageEvents[seNum].evType = evType end function AddNewEvent(condFunc, condArgs, doFunc, doArgs, evType) local i for i = 1, seNum do if stageEvents[i].cFunc == condFunc and stageEvents[i].cArgs == condArgs and stageEvents[i].dFunc == doFunc and stageEvents[i].dArgs == doArgs and stageEvents[seNum].evType == evType then return end end AddEvent(condFunc, condArgs, doFunc, doArgs, evType) end function RemoveEvent(evNum) if stageEvents[evNum] ~= nil then seNum = seNum - 1 table.remove(stageEvents, evNum) if evNum < curEvent then return true end end if evNum < curEvent then needToDecrease = needToDecrease + 1 end end function RemoveEventFunc(cFunc, cArgs) local i = 1 while i <= seNum do if stageEvents[i].cFunc == cFunc and (cArgs == nil or cArgs == stageEvents[i].cArgs) then RemoveEvent(i) i = i - 1 end i = i + 1 end end function CheckEvents() local i = 1 while i <= seNum do curEvent = i if stageEvents[i].cFunc(unpack(stageEvents[i].cArgs)) then stageEvents[i].dFunc(unpack(stageEvents[i].dArgs)) if needToDecrease > 0 then i = i - needToDecrease needToDecrease = 0 end if stageEvents[i].evType ~= 1 then RemoveEvent(i) i = i - 1 end end i = i + 1 end curEvent = 0 end -------------------------------------Misc--------------------------------- function StoppedGear(gear) -- GetHealth returns nil if gear does not exist if not GetHealth(gear) then -- We consider the gear to be “stopped” if it has been destroyed return true end local dx,dy = GetGearVelocity(gear) return math.abs(dx) <= 1 and math.abs(dy) <= 1 end
----------------------------------- -- Area: Windurst Waters -- NPC: Hakeem -- Type: Cooking Image Support -- !pos -123.120 -2.999 65.472 238 ----------------------------------- require("scripts/globals/status") require("scripts/globals/crafting") local ID = require("scripts/zones/Windurst_Waters/IDs") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) local guildMember = isGuildMember(player, 4) local SkillCap = getCraftSkillCap(player, tpz.skill.COOKING) local SkillLevel = player:getSkillLevel(tpz.skill.COOKING) if (guildMember == 1) then if (player:hasStatusEffect(tpz.effect.COOKING_IMAGERY) == false) then player:startEvent(10017, SkillCap, SkillLevel, 2, 495, player:getGil(), 0, 4095, 0) -- p1 = skill level else player:startEvent(10017, SkillCap, SkillLevel, 2, 495, player:getGil(), 7094, 4095, 0) end else player:startEvent(10017) -- Standard Dialogue end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (csid == 10017 and option == 1) then player:messageSpecial(ID.text.COOKING_SUPPORT, 0, 8, 2) player:addStatusEffect(tpz.effect.COOKING_IMAGERY, 1, 0, 120) end end
local screenSize = Vector2(guiGetScreenSize()) local windowSize = Vector2(240, 120) local currentCallback local ui = {} function admin.ui.hideConfirmWindow() ui.window.visible = false currentCallback(false) currentCallback = nil end function admin.ui.showConfirmWindow(title, text, callback) if ui.window.visible then return false end ui.window.text = title ui.textLabel.text = text ui.window.visible = true ui.window:bringToFront() currentCallback = callback end addEventHandler("onClientResourceStart", resourceRoot, function () ui.window = GuiWindow( (screenSize.x - windowSize.x) / 2, (screenSize.y - windowSize.y) / 2, windowSize.x, windowSize.y, "", false) ui.window.sizable = false ui.textLabel = GuiLabel(0.05, 0.2, 0.9, 0.15, "", true, ui.window) ui.cancelButton = GuiButton(0, 0.7, 0.45, 0.3, "No", true, ui.window) ui.acceptButton = GuiButton(0.5, 0.7, 0.45, 0.3, "Yes", true, ui.window) ui.window.visible = false addEventHandler("onClientGUIClick", resourceRoot, function() if not ui.window.visible then return false end if source == ui.acceptButton then if type(currentCallback) == "function" then currentCallback(true) end admin.ui.hideConfirmWindow() elseif source == ui.cancelButton then admin.ui.hideConfirmWindow() end end) end)
include "app.ui.base.init" _ENV=namespace "ui" using_namespace "luaClass" using_namespace "container" using_namespace "game" class("SkillDetailUI"){ super(cc.Node); super(LUIObject); SINGAL.skillUsed("skill","cardUI"); public{ FUNCTION.SkillDetailUI(function(self,skill,contentSize) self=self:__super() self:LUIObject() self._skill=skill self._contentSize=contentSize self:setContentSize(contentSize) local detail=createBlock(contentSize) :setPosition(0,0) :setAnchorPoint(0,0) :addTo(self) local textNode=createLabel(skill:toString(),18) :setWidth(contentSize.width) :setTag(998) local head=cc.Sprite:create(skill.picPath) :setAnchorPoint(1,1) :setPosition(contentSize.width,0) :setContentSize(contentSize.width/3,contentSize.height/3) :setTag(100) local scrollView= ScrollView() :setContentSize(contentSize) :setPosition(0,0) :setInnerNode(textNode) :addNode(head) :addTo(detail) end); FUNCTION.showMenu(function(self) local textArray=array() local callArray=array() textArray:push_back(self._skill.equipped and "可用" or "禁用") textArray:push_back("返回") local skill=self._skill callArray:push_back(function(_,_,card) self:skillUsed(skill,card) end) --返回 callArray:push_back(function() self:remove() end) return self:setMenu(textArray,callArray) end); FUNCTION.setMenu(function(self,textArray,callArray) local contentSize=self._contentSize for index,text,callBack in textArray:zip(callArray) do local card= CardUI(cc.size(contentSize.width/4,contentSize.height/8)) :setAnchorPoint(0,1) :addTo(self) :setPosition(contentSize.width,contentSize.height-((index-1)*contentSize.height/6)) :setText(text,20) card.onTouch=true connect(card,"touched",card,callBack) end return self end) }; protected{ MEMBER._contentSize(); MEMBER._skill(); } }
-- -- created with TexturePacker (http://www.codeandweb.com/texturepacker) -- -- $TexturePacker:SmartUpdate:a71a13373f387aa5f10d9c8c01bef7df:5ad5675d5cd591fb77929de69c088943:cf8ab4992190eb44f97f06311ef326d7$ -- -- local sheetInfo = require("mysheet") -- local myImageSheet = graphics.newImageSheet( "mysheet.png", sheetInfo:getSheet() ) -- local sprite = display.newSprite( myImageSheet , {frames={sheetInfo:getFrameIndex("sprite")}} ) -- local SheetInfo = {} SheetInfo.sheet = { frames = { { -- 1 x=321, y=449, width=88, height=118, sourceX = 129, sourceY = 469, sourceWidth = 960, sourceHeight = 672 }, { -- 2 x=525, y=435, width=80, height=66, sourceX = 116, sourceY = 377, sourceWidth = 960, sourceHeight = 672 }, { -- 3 x=209, y=449, width=110, height=130, sourceX = 123, sourceY = 352, sourceWidth = 960, sourceHeight = 672 }, { -- 4 x=1, y=289, width=244, height=158, sourceX = 600, sourceY = 339, sourceWidth = 960, sourceHeight = 672 }, { -- 5 x=549, y=1, width=90, height=252, sourceX = 617, sourceY = 97, sourceWidth = 960, sourceHeight = 672 }, { -- 6 x=1, y=1, width=176, height=286, sourceX = 685, sourceY = 77, sourceWidth = 960, sourceHeight = 672 }, { -- 7 x=439, y=1, width=108, height=234, sourceX = 528, sourceY = 121, sourceWidth = 960, sourceHeight = 672 }, { -- 8 x=497, y=367, width=90, height=66, sourceX = 653, sourceY = 484, sourceWidth = 960, sourceHeight = 672 }, { -- 9 x=391, y=367, width=104, height=78, sourceX = 734, sourceY = 478, sourceWidth = 960, sourceHeight = 672 }, { -- 10 x=301, y=179, width=136, height=90, sourceX = 173, sourceY = 262, sourceWidth = 960, sourceHeight = 672 }, { -- 11 x=501, y=505, width=40, height=36, sourceX = 686, sourceY = 34, sourceWidth = 960, sourceHeight = 672 }, { -- 12 x=547, y=639, width=20, height=32, sourceX = 602, sourceY = 40, sourceWidth = 960, sourceHeight = 672 }, { -- 13 x=401, y=569, width=54, height=16, sourceX = 613, sourceY = 80, sourceWidth = 960, sourceHeight = 672 }, { -- 14 x=321, y=569, width=78, height=18, sourceX = 148, sourceY = 577, sourceWidth = 960, sourceHeight = 672 }, { -- 15 x=437, y=639, width=30, height=32, sourceX = 108, sourceY = 374, sourceWidth = 960, sourceHeight = 672 }, { -- 16 x=411, y=505, width=88, height=56, sourceX = 207, sourceY = 319, sourceWidth = 960, sourceHeight = 672 }, { -- 17 x=179, y=179, width=120, height=106, sourceX = 603, sourceY = 26, sourceWidth = 960, sourceHeight = 672 }, { -- 18 x=577, y=523, width=68, height=58, sourceX = 671, sourceY = 203, sourceWidth = 960, sourceHeight = 672 }, { -- 19 x=569, y=583, width=74, height=76, sourceX = 474, sourceY = 196, sourceWidth = 960, sourceHeight = 672 }, { -- 20 x=641, y=1, width=98, height=194, sourceX = 859, sourceY = 478, sourceWidth = 960, sourceHeight = 672 }, { -- 21 x=247, y=287, width=142, height=160, sourceX = 816, sourceY = 433, sourceWidth = 960, sourceHeight = 672 }, { -- 22 x=179, y=1, width=160, height=176, sourceX = 736, sourceY = 496, sourceWidth = 960, sourceHeight = 672 }, { -- 23 x=1, y=589, width=184, height=72, sourceX = 627, sourceY = 600, sourceWidth = 960, sourceHeight = 672 }, { -- 24 x=301, y=271, width=76, height=14, sourceX = 711, sourceY = 658, sourceWidth = 960, sourceHeight = 672 }, { -- 25 x=457, y=563, width=34, height=18, sourceX = 686, sourceY = 654, sourceWidth = 960, sourceHeight = 672 }, { -- 26 x=391, y=639, width=44, height=24, sourceX = 806, sourceY = 648, sourceWidth = 960, sourceHeight = 672 }, { -- 27 x=353, y=589, width=208, height=48, sourceX = 390, sourceY = 527, sourceWidth = 960, sourceHeight = 672 }, { -- 28 x=493, y=563, width=26, height=18, sourceX = 341, sourceY = 560, sourceWidth = 960, sourceHeight = 672 }, { -- 29 x=217, y=659, width=32, height=10, sourceX = 516, sourceY = 579, sourceWidth = 960, sourceHeight = 672 }, { -- 30 x=187, y=659, width=28, height=12, sourceX = 570, sourceY = 558, sourceWidth = 960, sourceHeight = 672 }, { -- 31 x=391, y=287, width=106, height=78, sourceX = 37, sourceY = 556, sourceWidth = 960, sourceHeight = 672 }, { -- 32 x=509, y=639, width=36, height=22, sourceX = 72, sourceY = 581, sourceWidth = 960, sourceHeight = 672 }, { -- 33 x=469, y=639, width=38, height=24, sourceX = 184, sourceY = 643, sourceWidth = 960, sourceHeight = 672 }, { -- 34 x=411, y=447, width=112, height=56, sourceX = 145, sourceY = 616, sourceWidth = 960, sourceHeight = 672 }, { -- 35 x=501, y=543, width=26, height=18, sourceX = 285, sourceY = 586, sourceWidth = 960, sourceHeight = 672 }, { -- 36 x=645, y=583, width=74, height=60, sourceX = 259, sourceY = 565, sourceWidth = 960, sourceHeight = 672 }, { -- 37 x=1, y=449, width=206, height=138, sourceX = 0, sourceY = 534, sourceWidth = 960, sourceHeight = 672 }, { -- 38 x=187, y=589, width=164, height=68, sourceX = 233, sourceY = 604, sourceWidth = 960, sourceHeight = 672 }, { -- 39 x=379, y=271, width=28, height=14, sourceX = 389, sourceY = 658, sourceWidth = 960, sourceHeight = 672 }, { -- 40 x=543, y=523, width=22, height=16, sourceX = 409, sourceY = 640, sourceWidth = 960, sourceHeight = 672 }, { -- 41 x=529, y=543, width=24, height=16, sourceX = 423, sourceY = 620, sourceWidth = 960, sourceHeight = 672 }, { -- 42 x=561, y=559, width=14, height=22, sourceX = 405, sourceY = 617, sourceWidth = 960, sourceHeight = 672 }, { -- 43 x=543, y=503, width=20, height=18, sourceX = 221, sourceY = 603, sourceWidth = 960, sourceHeight = 672 }, { -- 44 x=251, y=659, width=10, height=12, sourceX = 220, sourceY = 597, sourceWidth = 960, sourceHeight = 672 }, { -- 45 x=555, y=541, width=12, height=16, sourceX = 210, sourceY = 603, sourceWidth = 960, sourceHeight = 672 }, { -- 46 x=541, y=561, width=18, height=20, sourceX = 87, sourceY = 528, sourceWidth = 960, sourceHeight = 672 }, { -- 47 x=521, y=563, width=18, height=22, sourceX = 66, sourceY = 512, sourceWidth = 960, sourceHeight = 672 }, { -- 48 x=565, y=503, width=14, height=18, sourceX = 65, sourceY = 536, sourceWidth = 960, sourceHeight = 672 }, { -- 49 x=263, y=659, width=12, height=10, sourceX = 82, sourceY = 527, sourceWidth = 960, sourceHeight = 672 }, { -- 50 x=353, y=639, width=36, height=30, sourceX = 818, sourceY = 550, sourceWidth = 960, sourceHeight = 672 }, { -- 51 x=607, y=255, width=88, height=236, sourceX = 872, sourceY = 436, sourceWidth = 960, sourceHeight = 672 }, }, sheetContentWidth = 960, sheetContentHeight = 672 } SheetInfo.frameIndex = { ["1"] = 1, ["2"] = 2, ["3"] = 3, ["4"] = 4, ["5"] = 5, ["6"] = 6, ["7"] = 7, ["8"] = 8, ["9"] = 9, ["10"] = 10, ["11"] = 11, ["12"] = 12, ["13"] = 13, ["14"] = 14, ["15"] = 15, ["16"] = 16, ["17"] = 17, ["18"] = 18, ["19"] = 19, ["20"] = 20, ["21"] = 21, ["22"] = 22, ["23"] = 23, ["24"] = 24, ["25"] = 25, ["26"] = 26, ["27"] = 27, ["28"] = 28, ["29"] = 29, ["30"] = 30, ["31"] = 31, ["32"] = 32, ["33"] = 33, ["34"] = 34, ["35"] = 35, ["36"] = 36, ["37"] = 37, ["38"] = 38, ["39"] = 39, ["40"] = 40, ["41"] = 41, ["42"] = 42, ["43"] = 43, ["44"] = 44, ["45"] = 45, ["46"] = 46, ["47"] = 47, ["48"] = 48, ["49"] = 49, ["50"] = 50, ["51"] = 51, } function SheetInfo:getSheet() return self.sheet; end function SheetInfo:getFrameIndex(name) return self.frameIndex[name]; end return SheetInfo
Config = {} Config.Locale = 'fr' Config.green = 56108 Config.grey = 8421504 Config.red = 16711680 Config.orange = 16744192 Config.blue = 2061822 Config.purple = 11750815 Config.webhook = "https://discordapp.com/api/webhooks/739310086232735924/VpNqKWmwqZSajNVVGdcw7GN0BxsHpTUSpExJHMngd_N9Ycn3rrCWh9QYyTUh14Gs6hIh" settings = { LogKills = true, -- Log when a player kill an other player. LogEnterPoliceVehicle = true, -- Log when an player enter in a police vehicle. LogEnterBlackListedVehicle = true, -- Log when a player enter in a blacklisted vehicle. LogPedJacking = true, -- Log when a player is jacking a car LogChatServer = true, -- Log when a player is talking in the chat , /command works too. LogLoginServer = true, -- Log when a player is connecting/disconnecting to the server. LogItemTransfer = true, -- Log when a player is giving an item. LogWeaponTransfer = true, -- Log when a player is giving a weapon. LogMoneyTransfer = true, -- Log when a player is giving money LogMoneyBankTransfert = true, -- Log when a player is giving money from bankaccount } blacklistedModels = { "APC", "BARRACKS", "BARRACKS2", "RHINO", "CRUSADER", "CARGOBOB", "SAVAGE", "TITAN", "LAZER", "HYDRA", "BUZZARD", "OPPRESSOR", "OPPRESSOR2", }
-- Author : olipcs -- Create Date : 8/12/2009 -- Version : 0.1 -- Credits: Many thanks goes to Jafula for the awsome JAMBA addon -- Nearly all code where copy & pasted from Jafulas JAMBA 0.5 addon, -- and only small additions where coded by me. -- So again, many thanks Jafula, for making the Jamba 0.5 API so simple to use! -- Create the addon using AceAddon-3.0 and embed some libraries. local AJM = LibStub( "AceAddon-3.0" ):NewAddon( "JambaFTL", "JambaModule-1.0", "AceConsole-3.0", "AceEvent-3.0" ) -- Get the Jamba Utilities Library. local JambaUtilities = LibStub:GetLibrary( "JambaUtilities-1.0" ) local JambaHelperSettings = LibStub:GetLibrary( "JambaHelperSettings-1.0" ) -- Constants and Locale for this module. AJM.moduleName = "Jamba-FTL" AJM.settingsDatabaseName = "JambaFTLProfileDB" AJM.chatCommand = "jamba-ftl" local L = LibStub( "AceLocale-3.0" ):GetLocale( AJM.moduleName ) AJM.parentDisplayName = L["Advanced"] AJM.moduleDisplayName = L["FTL Helper"] local assistButton local followButton local targetButton -- Settings - the values to store and their defaults for the settings database. -- dontUseLeftRight : If this is true only shift/alt/ctrl will be used instead of lshift/rshift... -- onlyUseUsedModifiers : If this is true, only modifiers, which are used by the active Toons are used in the macro -- onlyUseOnlineToons : If true only Toons which are online (and active) when the ftl-string is created are included -- assistString: The macrotext of the JambaFTLAssist Button AJM.settings = { profile = { dontUseLeftRight = false, onlyUseUsedModifiers = true, onlyUseOnlineToons = false, assistString = "", targetString = "", followString = "", CharListWithModifiers = {}, }, } -- Configuration. function AJM:GetConfiguration() local configuration = { name = AJM.moduleDisplayName, handler = AJM, type = 'group', childGroups = "tab", get = "JambaConfigurationGetSetting", set = "JambaConfigurationSetSetting", args = { update = { type = "input", name = L["Update FTL-Button"], desc = L["Updates the FTL-Button on all Team members"], usage = "/jamba-ftl update", get = false, set = "CreateUpdateFTLButton", }, push = { type = "input", name = L["Push Settings"], desc = L["Push the FTL settings to all characters in the team."], usage = "/jamba-ftl push", get = false, set = "JambaSendSettings", }, }, } return configuration end ------------------------------------------------------------------------------------------------------------- -- Command this module sends. ------------------------------------------------------------------------------------------------------------- AJM.COMMAND_UPDATE_FTL_BUTTON = "JambaFTLupdate" ------------------------------------------------------------------------------------------------------------- -- FTL. ------------------------------------------------------------------------------------------------------------- -- Creates a new Entry if a Char isn't in CharListWithModifiers local function createNewFTLListEntry( characterName ) if AJM.db.CharListWithModifiers[characterName] == nil then AJM.db.CharListWithModifiers[characterName] = {useToon = false, lshift=false, lalt=false, lctrl=false, rshift=false, ralt=false, rctrl=false} end end -- Updates The AssistButton with an FTL String (called when the AJM.COMMAND_UPDATE_FTL_BUTTON is received) local function UpdateFTLAssistButton( astring ) assistButton:SetAttribute("macrotext", astring) AJM:Print("Updating JambaFTLAssist-Button with:" .. astring) AJM.db.assistString = astring end -- Updates The FollowButton with an FTL String (called when the AJM.COMMAND_UPDATE_FTL_BUTTON is received) local function UpdateFTLFollowButton( fstring ) followButton:SetAttribute("macrotext", fstring) AJM:Print("Updating JambaFTLFollow-Button with:" .. fstring) AJM.db.followString = fstring end -- Updates The AssistButton with an FTL String (called when the AJM.COMMAND_UPDATE_FTL_BUTTON is received) local function UpdateFTLTargetButton( tstring ) targetButton:SetAttribute("macrotext", tstring) AJM:Print("Updating JambaFTLTarget-Button with:" .. tstring) AJM.db.targetString = tstring end local function UpdateFTLButton( ftlstring ) local a = "/assist " .. ftlstring local f = "/follow " .. ftlstring local t = "/target " .. ftlstring UpdateFTLAssistButton(a) UpdateFTLFollowButton(f) UpdateFTLTargetButton(t) end --creates a String for the teamlist which represents the used modifiers local function getModifierStringForChar( characterName ) if AJM.db.CharListWithModifiers[characterName] == nil then createNewFTLListEntry(characterName) end local modstring = ""; if AJM.db.CharListWithModifiers[characterName].lshift then modstring = modstring .. "lshift " end if AJM.db.CharListWithModifiers[characterName].lalt then modstring = modstring .. "lalt " end if AJM.db.CharListWithModifiers[characterName].lctrl then modstring = modstring .. "lctrl " end if AJM.db.CharListWithModifiers[characterName].rshift then modstring = modstring .. "rshift " end if AJM.db.CharListWithModifiers[characterName].ralt then modstring = modstring .. "ralt " end if AJM.db.CharListWithModifiers[characterName].rctrl then modstring = modstring .. "rctrl " end return modstring end -- Main function to create the FTL-Assist-String from the settings local function createFTLString() -- create a list of the Toons which should be used local activeToons = {} for index, characterName in JambaApi.TeamListOrdered() do -- check if modifoers for a character exist if AJM.db.CharListWithModifiers[characterName] then -- check if useToon is true if AJM.db.CharListWithModifiers[characterName].useToon then -- check if onlyUseOnlineToons is activated and if so, if the toon is online if (not AJM.db.onlyUseOnlineToons) or (JambaApi.GetCharacterOnlineStatus( characterName )) then table.insert( activeToons, characterName ) end end end end -- First find out, which modifiers to use: local useLShift = false; local useRShift = false; local useLAlt = false; local useRAlt = false; local useLCtrl = false; local useRCtrl = false; if AJM.db.onlyUseUsedModifiers then for index, characterName in ipairs( activeToons ) do if AJM.db.CharListWithModifiers[characterName].lshift then useLShift=true end if AJM.db.CharListWithModifiers[characterName].rshift then useRShift=true end if AJM.db.CharListWithModifiers[characterName].lalt then useLAlt=true end if AJM.db.CharListWithModifiers[characterName].ralt then useRAlt=true end if AJM.db.CharListWithModifiers[characterName].lctrl then useLCtrl=true end if AJM.db.CharListWithModifiers[characterName].rctrl then useRCtrl=true end end else useLShift = true; useRShift = true; useLAlt = true; useRAlt = true; useLCtrl = true; useRCtrl = true; end -- create the string local ftlstring = "" for index, characterName in ipairs( activeToons ) do ftlstring = ftlstring .. "[" --first if not dontUseLeftRight is set (so its differeniated between l/r) if (not AJM.db.dontUseLeftRight) then if useLShift then if (not AJM.db.CharListWithModifiers[characterName].lshift) then ftlstring = ftlstring .. "no" end ftlstring = ftlstring .. "mod:lshift," end if useRShift then if (not AJM.db.CharListWithModifiers[characterName].rshift) then ftlstring = ftlstring .. "no" end ftlstring = ftlstring .. "mod:rshift," end if useLAlt then if (not AJM.db.CharListWithModifiers[characterName].lalt) then ftlstring = ftlstring .. "no" end ftlstring = ftlstring .. "mod:lalt," end if useRAlt then if (not AJM.db.CharListWithModifiers[characterName].ralt) then ftlstring = ftlstring .. "no" end ftlstring = ftlstring .. "mod:ralt," end if useLCtrl then if (not AJM.db.CharListWithModifiers[characterName].lctrl) then ftlstring = ftlstring .. "no" end ftlstring = ftlstring .. "mod:lctrl," end if useRShift then if (not AJM.db.CharListWithModifiers[characterName].rctrl) then ftlstring = ftlstring .. "no" end ftlstring = ftlstring .. "mod:rctrl," end -- dontUseLeftRight is set else if (useLShift or useRShift) then if (not ((AJM.db.CharListWithModifiers[characterName].lshift) or (AJM.db.CharListWithModifiers[characterName].rshift))) then ftlstring = ftlstring .. "no" end ftlstring = ftlstring .. "mod:shift," end if (useLAlt or useRAlt) then if (not ((AJM.db.CharListWithModifiers[characterName].lalt) or (AJM.db.CharListWithModifiers[characterName].ralt))) then ftlstring = ftlstring .. "no" end ftlstring = ftlstring .. "mod:alt," end if (useLCtrl or useRCtrl) then if (not ((AJM.db.CharListWithModifiers[characterName].lctrl) or (AJM.db.CharListWithModifiers[characterName].rctrl))) then ftlstring = ftlstring .. "no" end ftlstring = ftlstring .. "mod:ctrl," end end ftlstring = ftlstring .. "]" .. characterName .. ";" end return ftlstring end ------------------------------------------ -- GUI/Settings (Creation, refreshing, callbacks) ------------------------------------------ -- Settings received. function AJM:JambaOnSettingsReceived( characterName, settings ) if characterName ~= AJM.characterName then -- Update the settings. AJM.db.CharListWithModifiers = JambaUtilities:CopyTable( settings.CharListWithModifiers ) AJM.db.dontUseLeftRight = settings.dontUseLeftRight AJM.db.onlyUseUsedModifiers = settings.onlyUseUsedModifiers AJM.db.onlyUseOnlineToons = settings.onlyUseOnlineToons AJM.db.assistString = settings.assistString AJM.db.targetString = settings.targetString -- Refresh the settings. AJM:SettingsRefresh() -- Tell the player. AJM:Print( L["Settings received from A."]( characterName ) ) end end function AJM:BeforeJambaProfileChanged() end function AJM:OnJambaProfileChanged() AJM:SettingsRefresh() end function AJM:SettingsRefresh() -- Refreshes all GUI-Elements AJM.settingsControl.checkBoxDontUseLeftRight:SetValue( AJM.db.dontUseLeftRight ) AJM.settingsControl.checkBoxonlyUseUsedModifiers:SetValue( AJM.db.onlyUseUsedModifiers ) AJM.settingsControl.checkBoxonlyUseOnlineToons:SetValue( AJM.db.onlyUseOnlineToons ) local characterName = JambaApi.GetCharacterNameAtOrderPosition( AJM.settingsControl.teamListHighlightRow ) if AJM.db.CharListWithModifiers[characterName] == nil then createNewFTLListEntry( characterName ) end AJM.settingsControl.checkBoxUseToon:SetValue( AJM.db.CharListWithModifiers[characterName].useToon ) AJM.settingsControl.checkBoxLShift:SetValue( AJM.db.CharListWithModifiers[characterName].lshift ) AJM.settingsControl.checkBoxRShift:SetValue( AJM.db.CharListWithModifiers[characterName].rshift ) AJM.settingsControl.checkBoxLAlt:SetValue( AJM.db.CharListWithModifiers[characterName].lalt ) AJM.settingsControl.checkBoxRAlt:SetValue( AJM.db.CharListWithModifiers[characterName].ralt ) AJM.settingsControl.checkBoxLCtrl:SetValue( AJM.db.CharListWithModifiers[characterName].lctrl ) AJM.settingsControl.checkBoxRCtrl:SetValue( AJM.db.CharListWithModifiers[characterName].rctrl ) AJM:SettingsTeamListScrollRefresh() end function SettingsCreateFTLControl( top ) -- Get positions and dimensions. local buttonHeight = JambaHelperSettings:GetButtonHeight() local checkBoxHeight = JambaHelperSettings:GetCheckBoxHeight() local labelHeight = JambaHelperSettings:GetLabelHeight() local left = JambaHelperSettings:LeftOfSettings() local headingHeight = JambaHelperSettings:HeadingHeight() local headingWidth = JambaHelperSettings:HeadingWidth( false ) local column1Left = left local movingTop = top -- Create a heading for information. JambaHelperSettings:CreateHeading( AJM.settingsControl, L["Modifiers to use for selected toon"], movingTop, false ) movingTop = movingTop - headingHeight AJM.settingsControl.checkBoxUseToon = JambaHelperSettings:CreateCheckBox( AJM.settingsControl, headingWidth, column1Left, movingTop, L["Use selected Toon in FTL"], AJM.SettingsToggleUseToon ) movingTop = movingTop - headingHeight AJM.settingsControl.checkBoxLShift = JambaHelperSettings:CreateCheckBox( AJM.settingsControl, headingWidth/2 - column1Left, column1Left, movingTop, L["Use left shift"], AJM.SettingsToggleLShift ) AJM.settingsControl.checkBoxRShift = JambaHelperSettings:CreateCheckBox( AJM.settingsControl, headingWidth/2, headingWidth/2, movingTop, L["Use right shift"], AJM.SettingsToggleRShift ) movingTop = movingTop - checkBoxHeight AJM.settingsControl.checkBoxLAlt = JambaHelperSettings:CreateCheckBox( AJM.settingsControl, headingWidth/2 - column1Left, column1Left, movingTop, L["Use left alt"], AJM.SettingsToggleLAlt ) AJM.settingsControl.checkBoxRAlt = JambaHelperSettings:CreateCheckBox( AJM.settingsControl, headingWidth/2, headingWidth/2, movingTop, L["Use right alt"], AJM.SettingsToggleRAlt ) movingTop = movingTop - checkBoxHeight AJM.settingsControl.checkBoxLCtrl = JambaHelperSettings:CreateCheckBox( AJM.settingsControl, headingWidth/2 - column1Left, column1Left, movingTop, L["Use left ctrl"], AJM.SettingsToggleLCtrl ) AJM.settingsControl.checkBoxRCtrl = JambaHelperSettings:CreateCheckBox( AJM.settingsControl, headingWidth, headingWidth/2, movingTop, L["Use right ctrl"], AJM.SettingsToggleRCtrl ) movingTop = movingTop - checkBoxHeight JambaHelperSettings:CreateHeading( AJM.settingsControl, L["Options"], movingTop, false ) movingTop = movingTop - headingHeight -- Check box: left/right_mod. AJM.settingsControl.checkBoxonlyUseUsedModifiers = JambaHelperSettings:CreateCheckBox( AJM.settingsControl, headingWidth, column1Left, movingTop, L["If a modifier isn't used in a team, don't include it."], AJM.SettingsToggleonlyUseUsedModifiers ) movingTop = movingTop - checkBoxHeight -- Check box: left/right_mod. AJM.settingsControl.checkBoxDontUseLeftRight = JambaHelperSettings:CreateCheckBox( AJM.settingsControl, headingWidth, column1Left, movingTop, L["Don't differenciate between left/right modifier states"], AJM.SettingsToggleDontUseLeftRight ) movingTop = movingTop - checkBoxHeight -- Check box: left/right_mod. AJM.settingsControl.checkBoxonlyUseOnlineToons = JambaHelperSettings:CreateCheckBox( AJM.settingsControl, headingWidth, column1Left, movingTop, L["Only use Toons which are online"], AJM.SettingsToggleonlyUseOnlineToons ) movingTop = movingTop - checkBoxHeight AJM.settingsControl.teamListButtonUpdateFTL = JambaHelperSettings:CreateButton( AJM.settingsControl, headingWidth, left, movingTop, L["Create / Update FTL Buttons"], AJM.CreateUpdateFTLButton ) movingTop = movingTop - buttonHeight -- Label: Quest has more than one reward. AJM.settingsControl.labelUpdateFTL= JambaHelperSettings:CreateLabel( AJM.settingsControl, headingWidth, column1Left, movingTop, L["Hint:Use the buttons by: /click JambaFTLAssist or /click JambaFTLTarget"] ) --TODO: Add in message area. return movingTop end function SettingsCreateTeamList() -- Position and size constants. local teamListButtonControlWidth = 85 local inviteDisbandButtonWidth = 85 local setMasterButtonWidth = 120 local buttonHeight = JambaHelperSettings:GetButtonHeight() local top = JambaHelperSettings:TopOfSettings() local left = JambaHelperSettings:LeftOfSettings() local headingHeight = JambaHelperSettings:HeadingHeight() local headingWidth = JambaHelperSettings:HeadingWidth( false ) local horizontalSpacing = JambaHelperSettings:GetHorizontalSpacing() local verticalSpacing = JambaHelperSettings:GetVerticalSpacing() local teamListWidth = headingWidth local rightOfList = left + teamListWidth + horizontalSpacing local topOfList = top - headingHeight -- Team list internal variables (do not change). AJM.settingsControl.teamListHighlightRow = 1 AJM.settingsControl.teamListOffset = 1 -- Create a heading. JambaHelperSettings:CreateHeading( AJM.settingsControl, L["Team List"], top, false ) -- Create a team list frame. local list = {} list.listFrameName = "JambaFTLSettingsTeamListFrame" list.parentFrame = AJM.settingsControl.widgetSettings.content list.listTop = topOfList list.listLeft = left list.listWidth = teamListWidth list.rowHeight = 20 list.rowsToDisplay = 5 list.columnsToDisplay = 2 list.columnInformation = {} list.columnInformation[1] = {} list.columnInformation[1].width = 40 list.columnInformation[1].alignment = "LEFT" list.columnInformation[2] = {} list.columnInformation[2].width = 60 list.columnInformation[2].alignment = "LEFT" list.scrollRefreshCallback = AJM.SettingsTeamListScrollRefresh list.rowClickCallback = AJM.SettingsTeamListRowClick AJM.settingsControl.teamList = list JambaHelperSettings:CreateScrollList( AJM.settingsControl.teamList ) -- Position and size constants (once list height is known). local bottomOfList = topOfList - list.listHeight - verticalSpacing local bottomOfSection = bottomOfList - verticalSpacing return bottomOfSection end local function SettingsCreate() AJM.settingsControl = {} -- Create the settings panels. JambaHelperSettings:CreateSettings( AJM.settingsControl, AJM.moduleDisplayName, AJM.parentDisplayName, AJM.SettingsPushSettingsClick ) -- Create the team list controls. local bottomOfTeamList = SettingsCreateTeamList() -- Create the FTL controls. local bottomOfQuestOptions = SettingsCreateFTLControl( bottomOfTeamList ) AJM.settingsControl.widgetSettings.content:SetHeight( -bottomOfQuestOptions ) -- Help local helpTable = {} JambaHelperSettings:CreateHelp( AJM.settingsControl, helpTable, AJM:GetConfiguration() ) end function AJM:SettingsTeamListScrollRefresh() FauxScrollFrame_Update( AJM.settingsControl.teamList.listScrollFrame, JambaApi.GetTeamListMaximumOrder(), AJM.settingsControl.teamList.rowsToDisplay, AJM.settingsControl.teamList.rowHeight ) AJM.settingsControl.teamListOffset = FauxScrollFrame_GetOffset( AJM.settingsControl.teamList.listScrollFrame ) for iterateDisplayRows = 1, AJM.settingsControl.teamList.rowsToDisplay do -- Reset. AJM.settingsControl.teamList.rows[iterateDisplayRows].columns[1].textString:SetText( "" ) AJM.settingsControl.teamList.rows[iterateDisplayRows].columns[2].textString:SetText( "" ) AJM.settingsControl.teamList.rows[iterateDisplayRows].columns[1].textString:SetTextColor( 1.0, 1.0, 1.0, 1.0 ) AJM.settingsControl.teamList.rows[iterateDisplayRows].columns[2].textString:SetTextColor( 1.0, 1.0, 1.0, 1.0 ) AJM.settingsControl.teamList.rows[iterateDisplayRows].highlight:SetTexture( 0.0, 0.0, 0.0, 0.0 ) -- Get data. local dataRowNumber = iterateDisplayRows + AJM.settingsControl.teamListOffset if dataRowNumber <= JambaApi.GetTeamListMaximumOrder() then -- Put character name and type into columns. local characterName = JambaApi.GetCharacterNameAtOrderPosition( dataRowNumber ) local displayCharacterName = characterName local characterType = getModifierStringForChar(characterName) AJM.settingsControl.teamList.rows[iterateDisplayRows].columns[1].textString:SetText( displayCharacterName ) AJM.settingsControl.teamList.rows[iterateDisplayRows].columns[2].textString:SetText( characterType ) -- Highlight the selected row. if dataRowNumber == AJM.settingsControl.teamListHighlightRow then AJM.settingsControl.teamList.rows[iterateDisplayRows].highlight:SetTexture( 1.0, 1.0, 0.0, 0.5 ) end end end end function AJM:SettingsTeamListRowClick( rowNumber, columnNumber ) if AJM.settingsControl.teamListOffset + rowNumber <= JambaApi.GetTeamListMaximumOrder() then AJM.settingsControl.teamListHighlightRow = AJM.settingsControl.teamListOffset + rowNumber AJM:SettingsTeamListScrollRefresh() end AJM:SettingsRefresh() end function AJM:SettingsPushSettingsClick( event ) AJM:JambaSendSettings() end function AJM:SettingsToggleDontUseLeftRight( event, checked ) AJM.db.dontUseLeftRight = checked AJM:SettingsRefresh() end function AJM:SettingsToggleonlyUseOnlineToons( event, checked ) AJM.db.onlyUseOnlineToons = checked AJM:SettingsRefresh() end function AJM:SettingsToggleonlyUseUsedModifiers( event, checked ) AJM.db.onlyUseUsedModifiers = checked AJM:SettingsRefresh() end function AJM:SettingsToggleUseToon( event, checked ) local characterName = JambaApi.GetCharacterNameAtOrderPosition( AJM.settingsControl.teamListHighlightRow ) AJM.db.CharListWithModifiers[characterName].useToon = checked AJM:SettingsRefresh() end function AJM:SettingsToggleLShift( event, checked ) local characterName = JambaApi.GetCharacterNameAtOrderPosition( AJM.settingsControl.teamListHighlightRow ) AJM.db.CharListWithModifiers[characterName].lshift = checked AJM:SettingsRefresh() end function AJM:SettingsToggleLAlt( event, checked ) local characterName = JambaApi.GetCharacterNameAtOrderPosition( AJM.settingsControl.teamListHighlightRow ) AJM.db.CharListWithModifiers[characterName].lalt = checked AJM:SettingsRefresh() end function AJM:SettingsToggleLCtrl( event, checked ) local characterName = JambaApi.GetCharacterNameAtOrderPosition( AJM.settingsControl.teamListHighlightRow ) AJM.db.CharListWithModifiers[characterName].lctrl = checked AJM:SettingsRefresh() end function AJM:SettingsToggleRShift( event, checked ) local characterName = JambaApi.GetCharacterNameAtOrderPosition( AJM.settingsControl.teamListHighlightRow ) AJM.db.CharListWithModifiers[characterName].rshift = checked AJM:SettingsRefresh() end function AJM:SettingsToggleRAlt( event, checked ) local characterName = JambaApi.GetCharacterNameAtOrderPosition( AJM.settingsControl.teamListHighlightRow ) AJM.db.CharListWithModifiers[characterName].ralt = checked AJM:SettingsRefresh() end function AJM:SettingsToggleRCtrl( event, checked ) local characterName = JambaApi.GetCharacterNameAtOrderPosition( AJM.settingsControl.teamListHighlightRow ) AJM.db.CharListWithModifiers[characterName].rctrl = checked AJM:SettingsRefresh() end function AJM:CreateUpdateFTLButton(event) local ftlstring = createFTLString() AJM:Print("FTL-String is:" .. ftlstring) AJM:JambaSendCommandToTeam( AJM.COMMAND_UPDATE_FTL_BUTTON, ftlstring ) -- UpdateFTLButton( ftlstring ) (is done by SendCommandToTeam) end ------------------------------------------------------------------------------------------------------------- -- Jamba-FTL functionality. ------------------------------------------------------------------------------------------------------------- -- A Jamba command has been received. function AJM:JambaOnCommandReceived( characterName, commandName, ... ) if commandName == AJM.COMMAND_UPDATE_FTL_BUTTON then AJM:Print("Update recieved") UpdateFTLButton( ... ) end end function AJM:OnCharacterAdded( message, characterName ) AJM:SettingsRefresh() end function AJM:OnCharacterRemoved( message, characterName ) AJM:SettingsRefresh() end ------------------------------------------------------------------------------------------------------------- -- Addon initialization, enabling and disabling. ------------------------------------------------------------------------------------------------------------- -- Initialise the module. function AJM:OnInitialize() -- Create the settings control. SettingsCreate() -- Initialise the JambaModule part of this module. AJM:JambaModuleInitialize( AJM.settingsControl.widgetSettings.frame ) -- Populate the settings. AJM:SettingsRefresh() -- Creates the Assistbutton assistButton = CreateFrame("Button", "JambaFTLAssist", nil, "SecureActionButtonTemplate") assistButton:SetAttribute("type", "macro") if AJM.db.assistString then UpdateFTLAssistButton(AJM.db.assistString) end -- Creates the Followbutton followButton = CreateFrame("Button", "JambaFTLFollow", nil, "SecureActionButtonTemplate") followButton:SetAttribute("type", "macro") if AJM.db.followString then UpdateFTLFollowButton(AJM.db.followString) end -- Creates the Targetbutton targetButton = CreateFrame("Button", "JambaFTLTarget", nil, "SecureActionButtonTemplate") targetButton:SetAttribute("type", "macro") if AJM.db.targetString then UpdateFTLTargetButton(AJM.db.targetString) end end -- Called when the addon is enabled. function AJM:OnEnable() AJM:RegisterMessage( JambaApi.MESSAGE_TEAM_CHARACTER_ADDED, "OnCharacterAdded" ) AJM:RegisterMessage( JambaApi.MESSAGE_TEAM_CHARACTER_REMOVED, "OnCharacterRemoved" ) AJM:SettingsTeamListScrollRefresh() end -- Called when the addon is disabled. function AJM:OnDisable() end
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by shuieryin. --- DateTime: 12/01/2018 9:29 PM --- function visualizeBoundaryLinear(X, y, model, plot) --VISUALIZEBOUNDARYLINEAR plots a linear decision boundary learned by the --SVM -- VISUALIZEBOUNDARYLINEAR(X, y, model) plots a linear decision boundary -- learned by the SVM and overlays the data on it local w = model.w local b = model.b local data = X[{ {}, 1 }] local xp = torch.linspace(data:min(), data:max(), 100) local yp = -(w[1][1] * xp + b) / w[2][1] plot:line(xp:totable(), yp:totable(), 'blue', 'Decision boundary'):redraw() itorchHtml(plot, 'ex6data1.html') end
-- Random numbers along a Normal curve -- @author Validark -- @original https://github.com/Quenty/NevermoreEngine/blob/8f9cbd9b870b3f061457a5c713d84ed097a05ccd/src/probability/src/Shared/Probability.lua --[[ MIT License Copyright (c) 2014-2021 Quenty Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] local tau = 2 * math.pi local cos = math.cos local log = math.log local random = math.random local function Normal(Average, StdDeviation) --- Normal curve [-1, 1] * StdDeviation + Average return (Average or 0) + (-2 * log(random())) ^ 0.5 * cos(tau * random()) * 0.5 * (StdDeviation or 1) end return Normal
function RegenHp(unit) local hp_max = BlzGetUnitMaxHP(unit) local hp = (BlzGetUnitRealField(unit, UNIT_RF_HP)) local hp_regen = (BlzGetUnitRealField(unit, UNIT_RF_HIT_POINTS_REGENERATION_RATE)) local hp_heal = (((hp_max + .0) - hp) / 20.0) + hp_regen local hp_result = math.ceil( hp + hp_heal ) SetUnitLifeBJ(unit, hp_result) -- TEST --SetUnitFacing(unit, math.floor(hp)) end
local __ActionButton_OnUpdate; local function __BigFoot_ActionButton_UpdateUsable(self) if not BigFoot_DistanceAlert then return end local icon = self.icon; if ( IsActionInRange( ActionButton_GetPagedID(self)) == false ) then icon:SetVertexColor(0.5, 0.1, 0.1); else local isUsable, notEnoughMana = IsUsableAction(ActionButton_GetPagedID(self)); if isUsable then icon:SetVertexColor(1.0, 1.0, 1.0); elseif notEnoughMana then icon:SetVertexColor(0.5, 0.5, 1.0); else icon:SetVertexColor(0.4, 0.4, 0.4); end end end function DistanceAlert_Toggle(flag) if (flag == 1) then BigFoot_DistanceAlert = true; if (not __ActionButton_OnUpdate) then hooksecurefunc("ActionButton_UpdateUsable",__BigFoot_ActionButton_UpdateUsable) hooksecurefunc("ActionButton_OnUpdate", ActionButton_UpdateUsable); __ActionButton_OnUpdate = true end else BigFoot_DistanceAlert = nil; end end
--[[ -- Asteroid Class -- ]] Asteroid = Class{} --[[ Asteroid takes an x and y for starting position as well as a radius to determine size. Initializes dx and dy with random values in set ranges ]] function Asteroid:init(x, y, radius, stage) self.x = x self.y = y self.radius = radius self.stage = stage self.dy = math.random(2) == 1 and math.random(-90, -80) or math.random(80, 90) self.dx = math.random(2) == 1 and math.random(-90, -80) or math.random(80, 90) end function Asteroid:update(dt) if self.y < 0 and self.dy < 0 then self.y = VIRTUAL_HEIGHT - self.radius end if self.y >= VIRTUAL_HEIGHT - self.radius / 2 then self.y = 0 + self.radius / 2 end if self.x < 0 and self.dx < 0 then self.x = VIRTUAL_WIDTH - self.radius end if self.x >= VIRTUAL_WIDTH - self.radius / 2 then self.x = 0 + self.radius / 2 end self.x = self.x + self.dx * dt self.y = self.y + self.dy * dt end function Asteroid:setDX(dx) self.dx = dx end function Asteroid:setDY(dy) self.dy = dy end function Asteroid:render() love.graphics.circle('fill', self.x, self.y, self.radius) end
object_tangible_meatlump_hideout_shared_meatlump_hotdog_grill_01 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/meatlump/hideout/shared_meatlump_hotdog_grill_01.iff" } ObjectTemplates:addClientTemplate(object_tangible_meatlump_hideout_shared_meatlump_hotdog_grill_01, "object/tangible/meatlump/hideout/shared_meatlump_hotdog_grill_01.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_meatlump_hideout_shared_meatlump_hotdog_grill_02 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/meatlump/hideout/shared_meatlump_hotdog_grill_02.iff" } ObjectTemplates:addClientTemplate(object_tangible_meatlump_hideout_shared_meatlump_hotdog_grill_02, "object/tangible/meatlump/hideout/shared_meatlump_hotdog_grill_02.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_meatlump_hideout_shared_meatlump_lump_unfinished = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/meatlump/hideout/shared_meatlump_lump_unfinished.iff" } ObjectTemplates:addClientTemplate(object_tangible_meatlump_hideout_shared_meatlump_lump_unfinished, "object/tangible/meatlump/hideout/shared_meatlump_lump_unfinished.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_meatlump_hideout_shared_mtp_hideout_instance_entryb_controller = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/meatlump/hideout/shared_mtp_hideout_instance_entryb_controller.iff" } ObjectTemplates:addClientTemplate(object_tangible_meatlump_hideout_shared_mtp_hideout_instance_entryb_controller, "object/tangible/meatlump/hideout/shared_mtp_hideout_instance_entryb_controller.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_meatlump_hideout_shared_mtp_hideout_instance_supplies = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/meatlump/hideout/shared_mtp_hideout_instance_supplies.iff" } ObjectTemplates:addClientTemplate(object_tangible_meatlump_hideout_shared_mtp_hideout_instance_supplies, "object/tangible/meatlump/hideout/shared_mtp_hideout_instance_supplies.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_meatlump_hideout_shared_mtp_hideout_ladder_enter = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/meatlump/hideout/shared_mtp_hideout_ladder_enter.iff" } ObjectTemplates:addClientTemplate(object_tangible_meatlump_hideout_shared_mtp_hideout_ladder_enter, "object/tangible/meatlump/hideout/shared_mtp_hideout_ladder_enter.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_meatlump_hideout_shared_mtp_hideout_ladder_exit = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/meatlump/hideout/shared_mtp_hideout_ladder_exit.iff" } ObjectTemplates:addClientTemplate(object_tangible_meatlump_hideout_shared_mtp_hideout_ladder_exit, "object/tangible/meatlump/hideout/shared_mtp_hideout_ladder_exit.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_meatlump_hideout_shared_mtp_hideout_rock_chair = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/meatlump/hideout/shared_mtp_hideout_rock_chair.iff" } ObjectTemplates:addClientTemplate(object_tangible_meatlump_hideout_shared_mtp_hideout_rock_chair, "object/tangible/meatlump/hideout/shared_mtp_hideout_rock_chair.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_meatlump_hideout_shared_mtp_king_story = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/meatlump/hideout/shared_mtp_king_story.iff" } ObjectTemplates:addClientTemplate(object_tangible_meatlump_hideout_shared_mtp_king_story, "object/tangible/meatlump/hideout/shared_mtp_king_story.iff") ------------------------------------------------------------------------------------------------------------------------------------
--[[ File-Author: Pyrr File-Hash: 721f84fb9a18e42b9211590d4fcd63ef519c8efb File-Date: 2020-04-30T22:04:46Z ]] local BUILD = tonumber("20200430220446") or 0 if not ptl then ChatFrame1:AddMessage("|cffff0000OS-Fix error: ptl not found: PyLib required (https://rom.curseforge.com/projects/aa_pylib)")return end if not pylib then ChatFrame1:AddMessage("|cffff0000OS-Fix error: pylib not found: PyLib required (https://rom.curseforge.com/projects/aa_pylib)")return end local py_lib, py_timer, py_string, py_table, py_num, py_hash, py_color, py_hook, py_callback, py_item, py_helper = pylib.GetLibraries() OS_BASETIME = OS_BASETIME or 0 local me = { name = "pyos", build = BUILD, version = "1.1.2", startTime = math.floor(GetTime()), osFunctionNames = { "print", "clock", "time", "difftime", "date", "exit", "execute", "getenv", "remove", "rename", "setlocale", "tmpname" }, secondsInMonth = { 2678400, 2419200, 2678400, 2592000, 2678400, 2592000, 2678400, 2678400, 2592000, 2678400, 2592000, 2678400, 2678400, 2505600, 2678400, 2592000, 2678400, 2592000, 2678400, 2678400, 2592000, 2678400, 2592000, 2678400, }, secondsRepresentation = { second = 1, min = 60, hour = 3600, day = 86400, year = 31536000, lyear = 31622400, }, config = { usechat = true, } } _G[me.name] = me me.patterns = { ["%a"] = function (str,key,t) return string.gsub(str, "%"..key, me.GetDay(tonumber(t.wday), true)) end, ["%A"] = function (str,key,t) return string.gsub(str, "%"..key, me.GetDay(tonumber(t.wday), false)) end, ["%b"] = function (str,key,t) return string.gsub(str, "%"..key, me.GetMonth(tonumber(t.month), true)) end, ["%B"] = function (str,key,t) return string.gsub(str, "%"..key, me.GetMonth(tonumber(t.month), false)) end, ["%c"] = function (str,key,t) return string.gsub(str, "%"..key, string.format("%04d-%02d-%02d %02d:%02d:%02d", t.year, t.month, t.day, t.hour, t.min, t.sec)) end, ["%d"] = function (str,key,t) return string.gsub(str, "%"..key, string.format("%02d", t.day)) end, ["%H"] = function (str,key,t) return string.gsub(str, "%"..key, string.format("%02d", t.hour)) end, ["%I"] = function (str,key,t) return string.gsub(str, "%"..key, string.format("%02d", ((t.hour == 0) and (t.hour+12) or ((t.hour>12) and (t.hour-12) or (t.hour))))) end, ["%M"] = function (str,key,t) return string.gsub(str, "%"..key, string.format("%02d", t.min)) end, ["%m"] = function (str,key,t) return string.gsub(str, "%"..key, string.format("%02d", t.month)) end, ["%p"] = function (str,key,t) return string.gsub(str, "%"..key, (((t.hour / 12) >= 1) and "pm" or "am")) end, ["%S"] = function (str,key,t) return string.gsub(str, "%"..key, string.format("%02d", t.sec)) end, ["%w"] = function (str,key,t) return string.gsub(str, "%"..key, me.GetDay(tonumber(t.wday), false)) end, ["%x"] = function (str,key,t) return string.gsub(str, "%"..key, string.format("%04d-%02d-%02d", t.year, t.month, t.day)) end, ["%X"] = function (str,key,t) return string.gsub(str, "%"..key, string.format("%02d:%02d:%02d", t.hour, t.min, t.sec)) end, ["%Y"] = function (str,key,t) return string.gsub(str, "%"..key, string.format("%04d", t.year)) end, ["%y"] = function (str,key,t) return string.gsub(str, "%"..key, string.sub(string.format("%04d", t.year), 3)) end, } function me.RegisterWithAddonManager() if AddonManager and AddonManager.RegisterAddonTable then local addon={ name = "osFix", -- todo name description = "", author = "Pyrrhus", category="Development", slashCommands="/os", version = me.version, icon = "interface\\icons\\boss_skill\\skill_boss_skill_380", } AddonManager.RegisterAddonTable(addon) return true else printf("|cffff9a00%s loaded!", "osFix") -- todo name end end --[[ [ Morphclockworkaround by TellTod]] local MORPHCLOCK_FULL_REPLACEMENT= true local function ReplaceMorphClock() if MorphClock then if MorphClock.vars and MorphClock.vars.registeredfuncs then for _,v in ipairs(MorphClock.vars.registeredfuncs) do local funcpt=_G[v] if not funcpt and type(v)=="string" then local tab,mfunc = string.match(v,"(.+)%.(.+)") if type(_G[tab])=="table" then funcpt=_G[tab][mfunc] end end if type(funcpt)=="function" then funcpt(time) end end end if MORPHCLOCK_FULL_REPLACEMENT then MorphClock = { VERSION="99999", date = function(self,...) return os.date(...) end, time = function(self,...) return os.time(...) end, difftime = function(self,...) return os.difftime(...) end, -- helpers - for those using it as library IsLeapYear = function (self,year) return me.IsLeapYear(year) end, GetDaythisYear = function (self,day,month,year) return me.GetDaythisYear(day,month,year) end, GetDaysSinceBegin = function (self,year) return me.GetDaysSinceBegin(year) end, GetWeekday = function (self,day,month,year) return me.GetWeekday(day,month,year) end, IsSummerTime = function (self,day,month,year,hour) return me.IsSummerTime(day,month,year,hour) end, UTCToLocale = function(self,time) if time then return time else return 0 end end, -- clock ready RegisterClockReady = function(self,fct) _G[fct](nil) end, IsValid = function(self) if OS_BASETIME~=0 then return true else return false end end, -- unused UnregisterClockReady = function(self,fct) end, OnTimerUpdate = function() end, OnTimerLoad = function() end, OnTimerEvent = function() end, About = function(self) end, Restart = function(self) end, Handler = function() end, PromptItemshopID = function(self) end, GetFirstDailyOfferGUID = function(self) end, -- and finally the ZZInfoBar special vars={}, } else -- just function fixing MorphClock.date = function(self,...) return os.date(...) end MorphClock.time = function(self,...) return os.time(...) end MorphClock.difftime = function(self,...) return os.difftime(...) end MorphClock.RegisterClockReady = function(self,fct) _G[fct](nil) end MorphClock.IsValid = function(self) if OS_BASETIME~=0 then return true else return false end end end -- stop morphclock updates if MorphClockTimerFrame then MorphClockTimerFrame:Hide() end end end --[[ ] ]] --------------------------------------- -- Determines if given time is within the summertime or not. -- Works with the rules for summertime in germany. -- last sunday in march and last sunday in october --@param day the day of the date 1-31 --@param month the month of the date 1-12 --@param year the year of the date 1970- --@param hour the hour of the time 0-23 --@return true if the given time is within the summertime else false<br><hr> function me.IsSummerTime(day,month,year,hour) local result=false; if (tonumber(month) and tonumber(day) and tonumber(year)) then month=tonumber(month); year=tonumber(year); day=tonumber(day); if month>3 and month<10 then result=true; elseif month==3 then local wday=me.GetWeekday(31,3,year); local keyday=31-wday+1; if day>keyday then result=true; elseif day==keyday and hour>=2 then result=true; end; elseif month==10 then local wday=me.GetWeekday(31,10,year); local keyday=31-wday+1; if day<keyday then --there will be an error of one hour in the night of the timeshift result=true; elseif day==keyday and hour<=2 then result=true; end; end end return result; end ------------------------------------------------------------------------------- -- Returns Weekday for a given date --@param day 1-31 --@param month 1-12 --@param year 1970- --@return weekday from Sunday 1 to Saturday 7 <br><hr> function me.GetWeekday(day,month,year) local result=-1; local days=me.GetDaythisYear(day,month,year); days=days+ me.GetDaysSinceBegin(year); --01.01.1970 was a Thursday result=math.mod(days-1,7); if result<=2 then result=result+5; else result=result-2; end; return result; end ------------------------------------------------------------------------------ -- returns the days fom 1.1.1970 till 1.1 of the given year --@param year 1970- --@return days from 1.1.1970 till 1.1.year<br><hr> function me.GetDaysSinceBegin(year) local result=0; if tonumber(year) and tonumber(year)>=1970 then year=tonumber(year); if year>1970 then for i=1970,year-1 do result=result+365; if me.IsLeapYear(i) then result=result+1; end; end end end return result; end --------------------------------------------------------------------- -- returns the yearday for a given date --@param day 1-31 --@param month 1-12 --@param year 1970- --@return day of the year for the given date or 0 for errors or unknown dates.e.g. 2.Januar.2010 would be the 2 day of the year<br><hr> function me.GetDaythisYear(day,month,year) local result=0; if tonumber(day) and tonumber(month) and tonumber(year) then month=tonumber(month); day=tonumber(day); if month>1 then for i=1,month-1 do result=result+me.secondsInMonth[i]/86400 if i==2 and me.IsLeapYear(year) then result=result+1; end; end end result=result+day; end return result; end me.GetMonth = function(num, short) local MonthsFull = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", } local month = MonthsFull[num] or "err" if short then month=string.sub(month,1,3) end return month end me.GetDay = function(num, short) local WeekDaysFull = { "WEEKINSTANCE_SUN", "WEEKINSTANCE_MON", "WEEKINSTANCE_TUE", "WEEKINSTANCE_WED", "WEEKINSTANCE_THUR", "WEEKINSTANCE_FRI", "WEEKINSTANCE_SAT", } local day = TEXT(WeekDaysFull[num] or "err") if short then day=string.sub(day,1,GetLanguage()=="DE" and 2 or 3) end return day end me._Init = function(var) if not var then return end --after load of children py_lib.RegisterEventHandler("CHAT_MSG_GUILD", "OS_FIX", me.OnEvent) py_lib.RegisterEventHandler("CHAT_MSG_SAY", "OS_FIX", me.OnEvent) py_lib.RegisterEventHandler("CHAT_MSG_ZONE", "OS_FIX", me.OnEvent) py_lib.RegisterEventHandler("CHAT_MSG_WHISPER", "OS_FIX", me.OnEvent) py_lib.RegisterEventHandler("CHAT_MSG_PARTY", "OS_FIX", me.OnEvent) py_lib.RegisterEventHandler("CHAT_MSG_YELL", "OS_FIX", me.OnEvent) py_lib.RegisterEventHandler("CHAT_MSG_CHANNEL", "OS_FIX", me.OnEvent) py_lib.RegisterEventHandler("VARIABLES_LOADED", "OS_FIX", me.LoadVars) py_lib.RegisterEventHandler("REGISTER_HOOKS", "OS_FIX", me.SetHook) end me.OnEvent=function(event, arg1, ...) if me.config.usechat then if OS_BASETIME==0 then me.parseTime(arg1) end end end me.LoadVars = function() os = nil os = {} for _,v in ipairs(me.osFunctionNames) do os[v] = me[v] end -- override osfix if osfix then SlashCmdList["osfix"] = nil osfix.var.baseTime = 0 osfix.OnEvent = function() end end ReplaceMorphClock() me.RegisterWithAddonManager() -- Save Vars PY_OSFIX_SETTINGS = PY_OSFIX_SETTINGS or {} for a,b in pairs(PY_OSFIX_SETTINGS) do me.config[a] = b end PY_OSFIX_SETTINGS = me.config SaveVariables("PY_OSFIX_SETTINGS") end me.SetHook = function() py_hook.AddHook("SendChatMessage", "OS_FIX", me.SendChatMessage) end me.SendChatMessage = function(next_fn, arg1,arg2,...) if me.config.usechat then if arg2~="GM" and type(arg1)=="string" and OS_BASETIME > 0 then if string.len(arg1)<200 then arg1=arg1.." |Hos:"..math.floor(OS_BASETIME+GetTime()).."|h|h" end end end next_fn(arg1, arg2, ...) end function me.parseTime(txt) if string.find(txt, "(%d%d)/(%d%d)/(%d%d) (%d%d):(%d%d)") then local _,_,m, d, y, h, M = string.find(txt, "(%d%d)/(%d%d)/(%d%d) (%d%d):(%d%d)"); OS_BASETIME=me.time({year=tonumber("20"..y),month=tonumber(m),day=tonumber(d),hour=tonumber(h),min=tonumber(M),sec=0})-GetTime(); elseif string.match(txt,"|Hos:%d+|h|h") then local base=string.match(txt,"|Hos:(%d+)|h|h") OS_BASETIME=base-GetTime(); end if OS_BASETIME<=1324512000 then OS_BASETIME=0 end end function me.IsLeapYear(year) return ((year % 4 == 0) and (year % 100 ~= 0) or (year % 400 == 0 and year % 1000 ~= 0)) end function me.clock() return math.floor(GetTime() - me.startTime) end function me.time(param) local t = {}; if (type(param) == "table") then t = param; t.isLeap = me.IsLeapYear(t.year or 0); else -- Avoid loop date -> time -> date :D return OS_BASETIME + GetTime(); end; -- Calculate from days, hours, minutes and seconds tm = tonumber(t.sec or 0) + (tonumber(t.min or 0) * me.secondsRepresentation.min) + (tonumber(t.hour or 12) * me.secondsRepresentation.hour) + (((tonumber(t.day or 1) - 1) * me.secondsRepresentation.day)); -- Add Month m = tonumber(t.month or 1) while m > 1 do tm = tm + me.secondsInMonth[t.isLeap and m + 11 or m - 1] m = m - 1; end; -- Add year y = tonumber(t.year or 1970); while y > 1970 do tm = tm + me.secondsRepresentation[me.IsLeapYear(y - 1) and "lyear" or "year"]; y = y - 1; end return tm; end function me.difftime(x, y) return ((type(x) == "table") and me.time(x) or x) - ((type(y) == "table") and me.time(y) or y) end function me.date(fmt, param) local t = {}; local tm = OS_BASETIME + GetTime(); if param then -- Set time from param tm = (type(param) == "table") and me.time(param) or param; -- If time is from parameter than get UTC time if fmt and fmt:find("!") == 1 then fmt = string.sub(fmt, 2) end; else -- Get Game time if requested if fmt and fmt:find("!") == 1 then -- Few people tried to fix that, this is not an error, in RoM '!' means Game Time not UTC time tm = ((86400 * GetCurrentGameTime()) / 240) + 16200; while (tm > 86400) do tm = tm - 86400; end; fmt = string.sub(fmt, 2) end; end -- Set UNIX Base date t = { year = 1970, month = 1, day = 1, hour = 0, min = 0, sec = 0, isLeap = false, isdst = true, } -- Calculate week day t.wday = 1 + (( 4 + math.ceil(tm / me.secondsRepresentation.day)) % 7); -- Calculate year y = me.secondsRepresentation[me.IsLeapYear(t.year) and "lyear" or "year"]; while tm >= y do tm = tm - y; t.year = t.year + 1; y = me.secondsRepresentation[me.IsLeapYear(t.year) and "lyear" or "year"]; end t.isLeap = y == me.secondsRepresentation.lyear; -- Calculate day of the year t.yday = math.floor(tm / 86400) + 1; -- Calculate month while tm >= me.secondsInMonth[t.isLeap and t.month + 12 or t.month] do tm = tm - me.secondsInMonth[t.isLeap and t.month + 12 or t.month]; t.month = t.month + 1; end -- Calculate day, hour, minute and seconds t.day = math.floor(tm / me.secondsRepresentation.day)+1; tm = tm % me.secondsRepresentation.day; t.hour = math.floor(tm / me.secondsRepresentation.hour); tm = tm % me.secondsRepresentation.hour; t.min = math.floor(tm / me.secondsRepresentation.min); tm = tm % me.secondsRepresentation.min; t.sec = math.floor(tm); if fmt and fmt == "*t" or fmt == "!*t" then return t; elseif fmt == nil then fmt = "%c" end; -- Apply patterns for key,fn in pairs(me.patterns) do if fmt and fmt:find("%"..key) then fmt = fn(fmt, key, t) end end -- Fix % char if fmt and fmt:find("%%") then fmt = string.gsub(fmt, "%%", "%") end; -- return formatted string (splall trick for nill value) return (fmt == nil) and "nil" or tostring(fmt) end function me.exit() end function me.execute() end function me.getenv() end function me.remove() end function me.rename() end function me.setlocale() end function me.tmpname() end SLASH_pyos1 ="/os" SlashCmdList["pyos"] = function(editBox, msg) if msg=="reset" then OS_BASETIME=0; elseif string.find(msg,"settime") then if string.find(msg, "(%d%d)/(%d%d)/(%d%d) (%d%d):(%d%d)") then local _,_,m, d, y, h, M = string.find(msg, "(%d%d)/(%d%d)/(%d%d) (%d%d):(%d%d)"); OS_BASETIME=me.time({year=tonumber("20"..y),month=tonumber(m),day=tonumber(d),hour=tonumber(h),min=tonumber(M),sec=0})-GetTime(); end elseif msg=="chat" then me.config.usechat = not me.config.usechat printf("osFix: Use Chat %s", me.config.usechat and "enabled" or "disabled") else print("osFix help:\n /os settime mm/dd/yy hh:mm\n/os reset\n/os chat [enables/disables sync with chat]"); end end; ptl.CreateTable(me, me.name, nil, _G) --Create Parent
--====================================================================-- -- dmc_widget/widget_style/textfield_style.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2015 David McCuskey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] --====================================================================-- --== DMC Corona UI : TextField Widget Style --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== DMC UI Setup --====================================================================-- local dmc_ui_data = _G.__dmc_ui local dmc_ui_func = dmc_ui_data.func local ui_find = dmc_ui_func.find local ui_file = dmc_ui_func.file --====================================================================-- --== DMC UI : newTextFieldStyle --====================================================================-- --====================================================================-- --== Imports local Objects = require 'dmc_objects' local Utils = require 'dmc_utils' local uiConst = require( ui_find( 'ui_constants' ) ) local BaseStyle = require( ui_find( 'core.style' ) ) local StyleHelp = require( ui_find( 'core.style_helper' ) ) --====================================================================-- --== Setup, Constants local assert = assert local sfmt = string.format local tinsert = table.insert local type = type --== To be set in initialize() local Style = nil --====================================================================-- --== TextField Style Class --====================================================================-- --- TextField Style Class. -- a style object for a TextField View. -- -- **Inherits from:** <br> -- * @{Core.Style} -- -- @classmod Style.TextField -- @usage -- dUI = require 'dmc_ui' -- widget = dUI.newTextFieldStyle() local TextFieldStyle = newClass( BaseStyle, {name="TextField Style"} ) --- Class Constants. -- @section --== Class Constants TextFieldStyle.TYPE = uiConst.TEXTFIELD TextFieldStyle.__base_style__ = nil TextFieldStyle._CHILDREN = { background=true, hint=true, display=true } TextFieldStyle._VALID_PROPERTIES = { debugOn=true, width=true, height=true, anchorX=true, anchorY=true, align=true, backgroundStyle=true, inputType=true, isHitActive=true, isHitTestable=true, isSecure=true, marginX=true, marginY=true, returnKey=true, } TextFieldStyle._EXCLUDE_PROPERTY_CHECK = { background=true, hint=true, display=true } TextFieldStyle._STYLE_DEFAULTS = { debugOn=false, width=300, height=40, anchorX=0.5, anchorY=0.5, align='center', backgroundStyle='none', inputType='default', isHitActive=true, isSecure=false, marginX=10, marginY=5, returnKey='done', background={ --[[ Copied from TextField * width * height * anchorX/Y --]] type='9-slice', view={ sheetInfo=ui_find('theme.default.textfield.textfield-sheet'), sheetImage=ui_file('theme/default/textfield/textfield-sheet.png'), } }, hint={ --[[ Copied from TextField * width * height * align * anchorX/Y * marginX/Y --]] fillColor={0,0,0,0}, font=native.systemFont, fontSize=18, fontSizeMinimum=0, marginX=15, textColor={0.3,0.3,0.3,1}, }, display={ --[[ Copied from TextField * width * height * align * anchorX/Y * marginX/Y --]] fillColor={0,0,0,0}, font=native.systemFont, fontSize=18, fontSizeMinimum=0, marginX=15, textColor={0.1,0.1,0.1,1}, }, } TextFieldStyle._TEST_DEFAULTS = { name='textfield-test-style', debugOn=false, width=501, height=502, anchorX=503, anchorY=504, align='textf-center', backgroundStyle='textf-none', inputType='textf-default', isHitActive=true, isSecure=false, marginX=510, marginY=511, returnKey='done', background={ --[[ Copied from TextField * width * height * anchorX/Y --]] type='rectangle', view={ fillColor={501,502,503,504}, strokeWidth=505, strokeColor={511,512,513,514}, } }, hint={ --[[ Copied from TextField * width * height * align * anchorX/Y * marginX/Y --]] fillColor={521,522,523,524}, font=native.systemFont, fontSize=524, fontSizeMinimum=520, textColor={523,524,525,526}, }, display={ --[[ Copied from TextField * width * height * align * anchorX/Y * marginX/Y --]] fillColor={531,532,533,534}, font=native.systemFontBold, fontSize=534, fontSizeMinimum=523, textColor={533,534,535,536}, }, } TextFieldStyle.MODE = uiConst.RUN_MODE TextFieldStyle._DEFAULTS = TextFieldStyle._STYLE_DEFAULTS --== Event Constants TextFieldStyle.EVENT = 'textfield-style-event' --======================================================-- -- Start: Setup DMC Objects function TextFieldStyle:__init__( params ) -- print( "TextFieldStyle:__init__", params ) params = params or {} self:superCall( '__init__', params ) --==-- --== Style Properties ==-- -- self._data -- self._inherit -- self._widget -- self._parent -- self._onProperty -- self._name -- self._debugOn -- self._width -- self._height -- self._anchorX -- self._anchorY self._align = nil self._bgStyle = nil self._inputType = nil self._isHitActive = nil self._isSecure = nil self._marginX = nil self._marginY = nil self._returnKey = nil --== Object Refs ==-- -- these are other style objects self._background = nil -- Background Style self._display = nil -- Text Style self._hint = nil -- Text Style end -- END: Setup DMC Objects --======================================================-- --====================================================================-- --== Static Methods function TextFieldStyle.initialize( manager, params ) -- print( "TextFieldStyle.initialize", manager ) params = params or {} if params.mode==nil then params.mode=uiConst.RUN_MODE end --==-- Style = manager if params.mode==uiConst.TEST_MODE then TextFieldStyle.MODE = params.mode TextFieldStyle._DEFAULTS = TextFieldStyle._TEST_DEFAULTS end local defaults = TextFieldStyle._DEFAULTS TextFieldStyle._setDefaults( TextFieldStyle, {defaults=defaults} ) end function TextFieldStyle.createStyleStructure( src ) -- print( "TextFieldStyle.createStyleStructure", src ) src = src or {} --==-- return { background=Style.Background.createStyleStructure( src.background ), hint=Style.Text.createStyleStructure( src.hint ), display=Style.Text.createStyleStructure( src.display ), } end function TextFieldStyle.addMissingDestProperties( dest, src ) -- print( "TextFieldStyle.addMissingDestProperties", dest, src ) assert( dest ) --==-- local srcs = { TextFieldStyle._DEFAULTS } if src then tinsert( srcs, 1, src ) end dest = BaseStyle.addMissingDestProperties( dest, src ) for i=1,#srcs do local src = srcs[i] if dest.align==nil then dest.align=src.align end if dest.backgroundStyle==nil then dest.backgroundStyle=src.backgroundStyle end if dest.inputType==nil then dest.inputType=src.inputType end if dest.isHitActive==nil then dest.isHitActive=src.isHitActive end if dest.isSecure==nil then dest.isSecure=src.isSecure end if dest.marginX==nil then dest.marginX=src.marginX end if dest.marginY==nil then dest.marginY=src.marginY end if dest.returnKey==nil then dest.returnKey=src.returnKey end end dest = TextFieldStyle._addMissingChildProperties( dest, src ) return dest end -- _addMissingChildProperties() -- copy properties to sub-styles -- function TextFieldStyle._addMissingChildProperties( dest, src ) -- print("TextFieldStyle._addMissingChildProperties", dest, srcs ) assert( dest ) src = dest --==-- local eStr = "ERROR: Style (BackgroundStyle) missing property '%s'" local StyleClass, child child = dest.background -- assert( child, sfmt( eStr, 'background' ) ) StyleClass = Style.Background dest.background = StyleClass.addMissingDestProperties( child, src ) child = dest.hint -- assert( child, sfmt( eStr, 'hint' ) ) StyleClass = Style.Text dest.hint = StyleClass.addMissingDestProperties( child, src ) child = dest.display -- assert( child, sfmt( eStr, 'display' ) ) StyleClass = Style.Text dest.display = StyleClass.addMissingDestProperties( child, src ) return dest end function TextFieldStyle.copyExistingSrcProperties( dest, src, params) -- print( "TextFieldStyle.copyMissingProperties", dest, src ) assert( dest ) if not src then return end params = params or {} if params.force==nil then params.force=false end --==-- local force=params.force dest = BaseStyle.copyExistingSrcProperties( dest, src, params ) if (src.align~=nil and dest.align==nil) or force then dest.align=src.align end if (src.backgroundStyle~=nil and dest.backgroundStyle==nil) or force then dest.backgroundStyle=src.backgroundStyle end if (src.inputType~=nil and dest.inputType==nil) or force then dest.inputType=src.inputType end if (src.isHitActive~=nil and dest.isHitActive==nil) or force then dest.isHitActive=src.isHitActive end if (src.isSecure~=nil and dest.isSecure==nil) or force then dest.isSecure=src.isSecure end if (src.marginX~=nil and dest.marginX==nil) or force then dest.marginX=src.marginX end if (src.marginY~=nil and dest.marginY==nil) or force then dest.marginY=src.marginY end if (src.returnKey~=nil and dest.returnKey==nil) or force then dest.returnKey=src.returnKey end return dest end function TextFieldStyle._verifyStyleProperties( src, exclude ) -- print("TextFieldStyle._verifyStyleProperties", src, exclude ) assert( src, "TextFieldStyle:verifyStyleProperties requires source" ) --==-- local emsg = "Style (TextFieldStyle) requires property '%s'" local is_valid = BaseStyle._verifyStyleProperties( src, exclude ) if not src.align then print(sfmt(emsg,'align')) ; is_valid=false end if not src.backgroundStyle then print(sfmt(emsg,'backgroundStyle')) ; is_valid=false end if not src.inputType then print(sfmt(emsg,'inputType')) ; is_valid=false end if src.isHitActive==nil then print(sfmt(emsg,'isHitActive')) ; is_valid=false end if src.isSecure==nil then print(sfmt(emsg,'isSecure')) ; is_valid=false end if not src.marginX then print(sfmt(emsg,'marginX')) ; is_valid=false end if not src.marginY then print(sfmt(emsg,'marginY')) ; is_valid=false end if not src.returnKey then print(sfmt(emsg,'returnKey')) ; is_valid=false end local child, StyleClass child = src.background if not child then print( "TextFieldStyle child test skipped for 'background'" ) is_valid=false else StyleClass = Style.Background if not StyleClass._verifyStyleProperties( child, exclude ) then is_valid=false end end child = src.hint if not child then print( "TextFieldStyle child test skipped for 'hint'" ) is_valid=false else StyleClass = Style.Text if not StyleClass._verifyStyleProperties( child, exclude ) then is_valid=false end end child = src.display if not child then print( "TextFieldStyle child test skipped for 'display'" ) is_valid=false else StyleClass = Style.Text if not StyleClass._verifyStyleProperties( child, exclude ) then is_valid=false end end return is_valid end --====================================================================-- --== Public Methods --======================================================-- -- Access to sub-styles --== Background function TextFieldStyle.__getters:background() -- print( 'TextFieldStyle.__getters:background', self._background ) return self._background end function TextFieldStyle.__setters:background( data ) -- print( 'TextFieldStyle.__setters:background', data ) assert( data==nil or type( data )=='table' ) --==-- local StyleClass = Style.Background local inherit = self._inherit and self._inherit._background or self._inherit self._background = StyleClass:createStyleFrom{ name=TextFieldStyle.BACKGROUND_NAME, inherit=inherit, parent=self, data=data } end --== Display function TextFieldStyle.__getters:display() return self._display end function TextFieldStyle.__setters:display( data ) -- print( 'TextFieldStyle.__setters:display', data ) assert( data==nil or type( data )=='table' ) --==-- local StyleClass = Style.Text local inherit = self._inherit and self._inherit._display or self._inherit self._display = StyleClass:createStyleFrom{ name=TextFieldStyle.DISPLAY_NAME, inherit=inherit, parent=self, data=data } end --== Hint function TextFieldStyle.__getters:hint() -- print( "TextFieldStyle.__getters:hint", data ) return self._hint end function TextFieldStyle.__setters:hint( data ) -- print( "TextFieldStyle.__setters:hint", data ) assert( data==nil or type( data )=='table' ) --==-- local StyleClass = Style.Text local inherit = self._inherit and self._inherit._hint or self._inherit self._hint = StyleClass:createStyleFrom{ name=TextFieldStyle.HINT_NAME, inherit=inherit, parent=self, data=data } end --======================================================-- -- Hint Style Properties --== .hintFont --- [**style**] set/get Style value for Widget's Hint font. -- -- @within Style-Helpers -- @function .hintFont -- @usage style.hintFont = 'helvetica-bold' -- @usage print( style.hintFont ) function TextFieldStyle.__getters:hintFont() -- print( "TextFieldStyle.__getters:hintFont" ) return self._hint.font end function TextFieldStyle.__setters:hintFont( value ) -- print( "TextFieldStyle.__setters:hintFont", value ) self._hint.font = value end --== .hintFontSize --- [**style**] set/get Style value for Widget's Hint font size. -- -- @within Style-Helpers -- @function .hintFontSize -- @usage style.hintFontSize = 12 -- @usage print( style.hintFontSize ) function TextFieldStyle.__getters:hintFontSize() -- print( "TextFieldStyle.__getters:hintFontSize" ) return self._hint.fontSize end function TextFieldStyle.__setters:hintFontSize( value ) -- print( "TextFieldStyle.__setters:hintFontSize", value ) self._hint.fontSize = value end --== .hintTextColor --- [**style**] set/get Style value for Widget's Hint text color. -- -- @within Style-Helpers -- @function .hintTextColor -- @usage style.hintTextColor = {1,0.5,1,0.25} -- @usage print( style.hintTextColor ) function TextFieldStyle.__getters:hintTextColor() -- print( "TextFieldStyle.__getters:hintTextColor" ) return self._hint.textColor end function TextFieldStyle.__setters:hintTextColor( value ) -- print( "TextFieldStyle.__setters:hintTextColor", value ) self._hint.textColor = value end --======================================================-- -- Display Style Properties --== .displayFont --- [**style**] set/get Style value for Widget's Display font. -- -- @within Style-Helpers -- @function .displayFont -- @usage style.displayFont = 'helvetica-bold' -- @usage print( style.displayFont ) function TextFieldStyle.__getters:displayFont() -- print( "TextFieldStyle.__getters:displayFont" ) return self._display.font end function TextFieldStyle.__setters:displayFont( value ) -- print( "TextFieldStyle.__setters:displayFont", value ) self._display.font = value end --== .displayFontSize --- [**style**] set/get Style value for Widget's Display font size. -- -- @within Style-Helpers -- @function .displayFontSize -- @usage style.displayFontSize = 12 -- @usage print( style.displayFontSize ) function TextFieldStyle.__getters:displayFontSize() -- print( "TextFieldStyle.__getters:displayFontSize" ) return self._display.fontSize end function TextFieldStyle.__setters:displayFontSize( value ) -- print( "TextFieldStyle.__setters:displayFontSize", value ) self._display.fontSize = value end --== .displayTextColor --- [**style**] set/get Style value for Widget's Display text color. -- -- @within Style-Helpers -- @function .displayTextColor -- @usage style.displayTextColor = {1,0.5,1,0.25} -- @usage print( style.displayTextColor ) function TextFieldStyle.__getters:displayTextColor() -- print( "TextFieldStyle.__getters:displayTextColor" ) return self._display.textColor end function TextFieldStyle.__setters:displayTextColor( value ) -- print( "TextFieldStyle.__setters:displayTextColor", value ) self._display.textColor = value end --======================================================-- -- Access to style properties --== .align --- [**style**] set/get Style value for Widget text alignment. -- values are 'left', 'center', 'right' -- -- @within Properties -- @function .align -- @usage style.align = 'center' -- @usage print( style.align ) TextFieldStyle.__getters.align = StyleHelp.__getters.align TextFieldStyle.__setters.align = StyleHelp.__setters.align --== .backgroundStyle -- [**style**] set/get Style value for Widget background style. -- values are 'none', ... -- -- @within Properties -- @function .backgroundStyle -- @usage style.backgroundStyle = 'none' -- @usage print( style.backgroundStyle ) function TextFieldStyle.__getters:backgroundStyle() -- print( "TextFieldStyle.__getters:backgroundStyle" ) local value = self._bgStyle if value==nil and self._inherit then value = self._inherit.backgroundStyle end return value end function TextFieldStyle.__setters:backgroundStyle( value ) -- print( "TextFieldStyle.__setters:backgroundStyle", value ) assert( type(value)=='string' or (value==nil and (self._inherit or self._isClearing)) ) --==-- if value == self._bgStyle then return end self._bgStyle = value self:_dispatchChangeEvent( 'backgroundStyle', value ) end --== .inputType function TextFieldStyle.__getters:inputType() -- print( "TextFieldStyle.__getters:inputType" ) local value = self._inputType if value==nil and self._inherit then value = self._inherit.inputType end return value end function TextFieldStyle.__setters:inputType( value ) -- print( "TextFieldStyle.__setters:inputType", value ) assert( type(value)=='string' or (value==nil and (self._inherit or self._isClearing)) ) --==-- if value == self._inputType then return end self._inputType = value self:_dispatchChangeEvent( 'inputType', value ) end --== .isHitActive function TextFieldStyle.__getters:isHitActive() -- print( "TextFieldStyle.__getters:isHitActive" ) local value = self._isHitActive if value==nil and self._inherit then value = self._inherit.isHitActive end return value end function TextFieldStyle.__setters:isHitActive( value ) -- print( "TextFieldStyle.__setters:isHitActive", value ) assert( type(value)=='boolean' or (value==nil and (self._inherit or self._isClearing)) ) --==-- if value == self._isHitActive then return end self._isHitActive = value self:_dispatchChangeEvent( 'isHitActive', value ) end --== .isSecure function TextFieldStyle.__getters:isSecure() -- print( "TextFieldStyle.__getters:isSecure" ) local value = self._isSecure if value==nil and self._inherit then value = self._inherit.isSecure end return value end function TextFieldStyle.__setters:isSecure( value ) -- print( "TextFieldStyle.__setters:isSecure", value ) assert( type(value)=='boolean' or (value==nil and (self._inherit or self._isClearing)) ) --==-- if value==self._isSecure then return end self._isSecure = value self:_dispatchChangeEvent( 'isSecure', value ) end --== .marginX --- [**style**] set/get Style value for Widget X-axis margin. -- -- @within Properties -- @function .marginX -- @usage style.marginX = 10 -- @usage print( style.marginX ) TextFieldStyle.__getters.marginX = StyleHelp.__getters.marginX TextFieldStyle.__setters.marginX = StyleHelp.__setters.marginX --== .marginY --- [**style**] set/get Style value for Widget Y-axis margin. -- -- @within Properties -- @function .marginY -- @usage style.marginY = 10 -- @usage print( style.marginY ) TextFieldStyle.__getters.marginY = StyleHelp.__getters.marginY TextFieldStyle.__setters.marginY = StyleHelp.__setters.marginY --== .returnKey function TextFieldStyle.__getters:returnKey() -- print( "TextFieldStyle.__getters:returnKey" ) local value = self._returnKey if value==nil and self._inherit then value = self._inherit.returnKey end return value end function TextFieldStyle.__setters:returnKey( value ) -- print( "TextFieldStyle.__setters:returnKey", value ) assert( (value==nil and (self._inherit or self._isClearing)) or type(value)=='string' ) --==-- if value == self._inputType then return end self._returnKey = value end --======================================================-- -- Misc --====================================================================-- --== Private Methods function TextFieldStyle:_doChildrenInherit( value ) -- print( "TextFieldStyle:_doChildrenInherit", value ) if not self._isInitialized then return end self._background.inherit = value and value.background or value self._hint.inherit = value and value.hint or value self._display.inherit = value and value.display or value end function TextFieldStyle:_clearChildrenProperties( style, params ) -- print( "TextFieldStyle:_clearChildrenProperties", style, self ) assert( style==nil or type(style)=='table' ) if style and type(style.isa)=='function' then assert( style:isa(TextFieldStyle) ) end --==-- local substyle substyle = style and style.background self._background:_clearProperties( substyle, params ) substyle = style and style.hint self._hint:_clearProperties( substyle, params ) substyle = style and style.display self._display:_clearProperties( substyle, params ) end function TextFieldStyle:_destroyChildren() self._background:removeSelf() self._background=nil self._display:removeSelf() self._display=nil self._hint:removeSelf() self._hint=nil end -- TODO: more work when inheriting, etc (Background Style) function TextFieldStyle:_prepareData( data, dataSrc, params ) -- print("TextFieldStyle:_prepareData", data, self ) params = params or {} --==-- -- local inherit = params.inherit local StyleClass local src, dest, tmp if not data then data = TextFieldStyle.createStyleStructure( dataSrc ) end src, dest = data, nil --== make sure we have structure for children StyleClass = Style.Background if not src.background then tmp = dataSrc and dataSrc.background src.background = StyleClass.createStyleStructure( tmp ) end StyleClass = Style.Text if not src.display then tmp = dataSrc and dataSrc.display src.display = StyleClass.createStyleStructure( tmp ) end if not src.hint then tmp = dataSrc and dataSrc.hint src.hint = StyleClass.createStyleStructure( tmp ) end --== process children dest = src.background src.background = StyleClass.copyExistingSrcProperties( dest, src ) dest = src.display src.display = StyleClass.copyExistingSrcProperties( dest, src ) dest = src.hint src.hint = StyleClass.copyExistingSrcProperties( dest, src ) return data end --====================================================================-- --== Event Handlers -- none return TextFieldStyle
--[[Intention of this script is to turn Christmas lights on and off based on sunrise and sunset. Script will run every third minute and only from November to February. Setting debug variable true, script prints debug information to Domoticz's log Own variable christmasLightsOnTime (type: Time) is used to store time in 24h format (HH:MM) when Christmas lights need to turned on. Own variable christmasLightsOffTime (type: Time) is used to store time in 24h format (HH:MM) when Christmas lights need to turned off. Own variable christmasLightsLastRunTime (type: Int) is used to store time when script ran last time (in system seconds)]] -------------------------------- ------ Variables to edit ------ -------------------------------- frontGardenSwitch = "Etupihan valokytkin" --Name of the front garden switch backGardenSwitch = "Takapihan valokytkin" --Name of the back garden switch outdoorSwitch = "Ulkokytkin" --Name of the outdoor switch switchOnTime = "christmasLightsOnTime" --Variable HH:MM format which determines when christmas lights need to be turned On switchOffTime = "christmasLightsOffTime" --Variable HH:MM format which determines when christmas lights need to be turned Off lastRunTimeVariable = "christmasLightsLastRunTime" --Time in system seconds when script ran last time runInterval = 150 --runInterval variable determines how often this script will run. Default 150s which means the script will run every third minute defaultOnTime = "07:00" --Time when Christmas lights are turned On by default before sunrise defaultOffTime = "00:00" --Time when Christmas lights are turned Off by default after sunset switchOnWindow = 5 --switchOnWindow variable determines time "window" in minutes in which switch is turned on. Default value is 5min. debug = false -------------------------------- -- End of variables to edit -- -------------------------------- --Variables needed in the first place are initialized lastRunTime = uservariables[lastRunTimeVariable] --Time in system seconds when script ran last time time = os.time() --System time in seconds is stored to time variable currentMonth = tonumber(os.date("%m")) --Number of current month (01-12) commandArray = {} if (time > lastRunTime + runInterval and (currentMonth < 3 or currentMonth > 10 or (otherdevices[frontGardenSwitch] == "On" and otherdevices[backGardenSwitch] == "On"))) then print("Christmas lights switch script running...") --Function currentTimeInMinutes returns current time in minutes function currentTimeInMinutes() local hour = tonumber(os.date("%H")) --Current hour (0 - 23) local minute = tonumber(os.date("%M")) --Current minute (0 - 59) return (hour * 60 + minute) end --Function convertTimeToMinutes converts time from HH:MM format to minutes. Converted time in minutes is returned. function convertTimeToMinutes(timeSeconds) local hour = tonumber(string.sub(timeSeconds, 1, 2)) local minutes = tonumber(string.sub(timeSeconds, 4, 5)) return (hour * 60 + minutes) end --Function convertMinutesToTime converts time from minutes to HH:MM format. Converted time in HH:MM format is returned. function convertMinutesToTime(timeMinutes) local hour = math.floor(timeMinutes / 60) local minutes = math.floor(timeMinutes % 60) if (hour < 10) then hour = "0"..hour end if (minutes < 10) then minutes = "0"..minutes end return (hour..":"..minutes) end --More variables are initialized sunRise = timeofday['SunriseInMinutes'] --Time of sunrise in minutes sunSet = timeofday['SunsetInMinutes'] --Time of sunrise in minutes currentTime = currentTimeInMinutes() --Current time in minutes is stored to this variable switchOnTimeInMinutes = convertTimeToMinutes(uservariables[switchOnTime]) --Christmas lights On time in minutes switchOffTimeInMinutes = convertTimeToMinutes(uservariables[switchOffTime]) --Christmas lights Off time in minutes commandArray["Variable:"..lastRunTimeVariable] = tostring(time) --Last run time of the script is updated to CarHeaterSwitchLastRunTime variable if (debug) then print("Current time: "..os.date("%H")..":"..os.date("%M")) print("Time when Christmas light need to be turned on: "..uservariables[switchOnTime]) print("Time when Christmas light need to be turned off: "..uservariables[switchOffTime]) print("Time of sunrise: "..convertMinutesToTime(sunRise)) print("Time of sunset: "..convertMinutesToTime(sunSet)) print("State of "..frontGardenSwitch.." is: "..otherdevices[frontGardenSwitch]) print("State of "..backGardenSwitch.." is: "..otherdevices[backGardenSwitch]) print("State of "..outdoorSwitch.." is: "..otherdevices[outdoorSwitch]) end if (otherdevices[frontGardenSwitch] == "Off" or otherdevices[backGardenSwitch] == "Off") then --Switches are Off if ((currentTime > switchOnTimeInMinutes) and (currentTime < switchOnTimeInMinutes + switchOnWindow)) then --The switches are turned on if current time is within switch On time and start time "window". New Christmas light On time is set. commandArray[frontGardenSwitch] = "On" --Turn front garden switch On commandArray[backGardenSwitch] = "On" --Turn back garden switch On commandArray[outdoorSwitch] = "On" --Turn outdoor switch On if (currentTime <= 720) then --If switches are turned On before noon (720mins = 12:00), sunrise is set as an off time. Otherwise off time is based on defaultOffTime variable commandArray["Variable:"..switchOffTime] = convertMinutesToTime(sunRise) --Time when switches need to be turned Off is updated to switchOffTime variable else commandArray["Variable:"..switchOffTime] = defaultOffTime --Time when switches need to be turned Off is updated to switchOffTime variable end print(frontGardenSwitch.." and "..backGardenSwitch.." and "..outdoorSwitch.." have been switched On") end else --Switches are On if ((currentTime > switchOffTimeInMinutes) and (currentTime < switchOffTimeInMinutes + switchOnWindow)) then --The switches are turned off if current time is within switch Off time and start time "window". New Christmas light On time is set. commandArray[frontGardenSwitch] = "Off" --Turn front garden switch Off commandArray[backGardenSwitch] = "Off" --Turn back garden switch Off commandArray[outdoorSwitch] = "Off" --Turn outdoor switch Off if (timeofday['Daytime'] == false) then --If switches are turned Off after sunset, defaultOnTime variable is set as an On time. Otherwise On time is based on sunset. commandArray["Variable:"..switchOnTime] = defaultOnTime --Time when switches need to be turned On is updated to switchOnTime variable else commandArray["Variable:"..switchOnTime] = convertMinutesToTime(sunSet) --Time when switches need to be turned On is updated to switchOnTime variable end print(frontGardenSwitch.." and "..backGardenSwitch.." and "..outdoorSwitch.." have been switched Off") end end end return commandArray
return { { effect_list = { { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRateExtra", number = 0.01 } } } }, { effect_list = { { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRateExtra", number = 0.02 } } } }, { effect_list = { { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRateExtra", number = 0.03 } } } }, { effect_list = { { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRateExtra", number = 0.04 } } } }, { effect_list = { { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRateExtra", number = 0.05 } } } }, { effect_list = { { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRateExtra", number = 0.06 } } } }, { effect_list = { { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRateExtra", number = 0.07 } } } }, { effect_list = { { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRateExtra", number = 0.08 } } } }, { effect_list = { { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRateExtra", number = 0.09 } } } }, { effect_list = { { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRateExtra", number = 0.1 } } } }, time = 1, name = "", init_effect = "", color = "yellow", picture = "", desc = "", stack = 1, id = 14792, icon = 14792, last_effect = "", blink = { 0, 0.7, 1, 0.3, 0.3 }, effect_list = { { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRateExtra", number = 0.01 } } } }
// ============================================================================================ // /* * Wildfire Servers - Portal RP - Base Addon * File description: Event Power Box serverside script file * Copyright (C) 2022 KiwifruitDev * Licensed under the MIT License. */ // ============================================================================================ // // BASE FILE HEADER DO NOT MODIFY!! // local ent = FindMetaTable("Entity") // local ply = FindMetaTable("Player") // local vec = FindMetaTable("Vector") // // ================================ // AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:SetModel("models/props_vehicles/generatortrailer01.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) local phys = self:GetPhysicsObject() if phys:IsValid() then phys:Wake() end end function ENT:Use(ply) if not IsValid(ply) then return end if not ply:IsPlayer() then return end if GetGlobalBool("BlackoutEvent", false) == true then endpoweroutage() end end
local luaunit = require("luaunit") local xmlua = require("xmlua") TestCDATASection = {} function TestCDATASection.test_path() local document = xmlua.XML.parse([=[ <root><![CDATA[This is <CDATA>]]></root> ]=]) local cdata_section = document:search("/root/text()") luaunit.assertEquals(cdata_section[1]:path(), "/root/text()") end function TestCDATASection.test_content() local document = xmlua.XML.parse([=[ <root><![CDATA[This is <CDATA>]]></root> ]=]) local cdata_section = document:search("/root/text()") luaunit.assertEquals(cdata_section[1]:content(), "This is <CDATA>") end function TestCDATASection.test_set_content() local document = xmlua.XML.parse([=[ <root><![CDATA[This is <CDATA>]]></root> ]=]) local cdata_section = document:search("/root/text()") cdata_section[1]:set_content("Setting new <CDATA> content!") luaunit.assertEquals(cdata_section[1]:content(), "Setting new <CDATA> content!") end function TestCDATASection.test_text() local document = xmlua.XML.parse([=[ <root><![CDATA[This is <CDATA>]]></root> ]=]) local cdata_section = document:search("/root/text()") luaunit.assertEquals(cdata_section[1]:text(), "") end
-- factorial -- return factorial of 'n', return 'nil' otherwise function fact(n) if type(n) ~= "number" or n < 0 or n%1 ~= 0 then -- It's not a number, or positive or integer, wrong input! return nil end if n == 0 then return 1 else return n*fact(n-1) end end
local Plugin = script.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent local Libs = Plugin.Libs local Roact = require(Libs.Roact) local Constants = require(Plugin.Core.Util.Constants) local ContextGetter = require(Plugin.Core.Util.ContextGetter) local ContextHelper = require(Plugin.Core.Util.ContextHelper) local SmartSetState = require(Plugin.Core.Util.SmartSetState) local Types = require(Plugin.Core.Util.Types) local Utility = require(Plugin.Core.Util.Utility) local withTheme = ContextHelper.withTheme local getMainManager = ContextGetter.getMainManager local getModal = ContextGetter.getModal local Components = Plugin.Core.Components local Foundation = Components.Foundation local PresetPreview = require(Components.PresetPreview) -- local BorderedFrame = require(Foundation.BorderedFrame) local RoundedBorderedFrame = require(Foundation.RoundedBorderedFrame) local RoundedBorderedVerticalList = require(Foundation.RoundedBorderedVerticalList) local StatefulButtonDetector = require(Foundation.StatefulButtonDetector) local PreciseFrame = require(Foundation.PreciseFrame) local RunService = game:GetService("RunService") local PresetEntry = Roact.PureComponent:extend("PresetEntry") function PresetEntry:init() local mainManager = getMainManager(self) self:setState( { buttonState = "Default", dotState = "Default", stale = false, hovering = false } ) self.boxRef = Roact.createRef() self.skyRef = Roact.createRef() local modal = getModal(self) self.hoveringInternal = false self.onHoverDetectorMouseEnter = function() self.hoveringInternal = true self:UpdateHovering() end self.onHoverDetectorMouseLeave = function() self.hoveringInternal = false self:UpdateHovering() end self.onStateChanged = function(buttonState) RunService.Heartbeat:Wait() self:setState { buttonState = buttonState } end self.onDotStateChanged = function(dotState) self:setState { dotState = dotState } end self.onCancelButtonClicked = function() mainManager:ClearPresetIdBeingDelete() end self.onClickDetector = function() local presetId = self.props.presetId local activePreset = mainManager:GetActivePreset() if activePreset ~= presetId then mainManager:SetActivePreset(presetId) end end self.onDotsClicked = function() local presetId = self.props.presetId mainManager:OpenPresetEntryContextMenu(presetId) end local camera = Instance.new("Camera") camera.CFrame = CFrame.new(Vector3.new(0, -1.75, 6), Vector3.new(0, -1.75, -1)) camera.FieldOfView = 40 self.camera = camera local skybox = Constants.SKYBOX_BALL:Clone() Utility.ScaleObject(skybox, 100) self.skybox = skybox self.skybox:SetPrimaryPartCFrame(CFrame.new(self.camera.CFrame.p)) self:UpdateStateFromMainManager() end function PresetEntry:UpdateStateFromMainManager() local mainManager = getMainManager(self) local presetId = self.props.presetId local hasPreset = mainManager:HasPreset(presetId) if not hasPreset then SmartSetState( self, { stale = true } ) return end local presetType = mainManager:GetPresetType(presetId) local active = mainManager:GetActivePreset() == presetId local presetName = mainManager:GetPresetName(presetId) SmartSetState( self, { presetType = presetType, active = active, presetName = presetName, stale = false } ) end function PresetEntry:render() if self.state.stale then return end local props = self.props return withTheme( function(theme) local entryTheme = theme.presetEntry local entryHeight = 120 local entryPadding = 4 local state = self.state local presetName = state.presetName local active = state.active local buttonState = state.buttonState local boxState if active then boxState = "Selected" else local map = { Default = "Default", Hovered = "Hovered", PressedInside = "PressedInside", PressedOutside = "PressedOutside" } boxState = map[buttonState] end local bgColors = entryTheme.backgroundColor local bgColor = bgColors[boxState] return Roact.createElement( RoundedBorderedVerticalList, { width = UDim.new(1, 0), LayoutOrder = props.LayoutOrder, BackgroundColor3 = theme.mainBackgroundColor, BorderColor3 = theme.borderColor }, { Wrap = Roact.createElement( "Frame", { Size = UDim2.new(1, 0, 0, entryHeight), BackgroundTransparency = 1, LayoutOrder = 1 }, { Border = Roact.createElement( RoundedBorderedFrame, { Size = UDim2.new(1, 0, 1, 0), BackgroundColor3 = bgColor, BorderColor3 = theme.borderColor, LayoutOrder = props.LayoutOrder, slice = "Center" } ), HoverDetector = Roact.createElement( PreciseFrame, { [Roact.Event.MouseEnter] = self.onHoverDetectorMouseEnter, [Roact.Event.MouseLeave] = self.onHoverDetectorMouseLeave, Size = UDim2.new(1, 0, 1, 0), BackgroundTransparency = 1 } ), ClickDetector = Roact.createElement( StatefulButtonDetector, { Size = UDim2.new(1, 0, 1, 0), BackgroundTransparency = 1, onClick = self.onClickDetector, onStateChanged = self.onStateChanged } ), ImageFrame = Roact.createElement( "Frame", { Size = UDim2.new(1, -entryPadding * 2, 1, -entryPadding * 3 - Constants.FONT_SIZE_MEDIUM), Position = UDim2.new(0, entryPadding, 0, entryPadding), BackgroundTransparency = 1 }, { PresetPreview = Roact.createElement( PresetPreview, { Size = UDim2.new(1, 0, 1, 0), presetId = props.presetId, presetParams = props.presetParams } ), DotDetector = self.state.hovering and Roact.createElement( StatefulButtonDetector, { Size = UDim2.new(0, 32, 0, 32), Position = UDim2.new(1, -8, 1, -0), BackgroundTransparency = 1, AnchorPoint = Vector2.new(1, 1), onStateChanged = self.onDotStateChanged, onClick = self.onDotsClicked, ZIndex = 2 }, { Shadow = Roact.createElement( "ImageLabel", { BackgroundTransparency = 1, Size = UDim2.new(1, 0, 1, 0), Position = UDim2.new(0, 2, 0, 2), Image = "rbxtemp://0", ImageColor3 = Color3.new(0, 0, 0), ImageTransparency = 0.25 } ), Dots = Roact.createElement( "ImageLabel", { BackgroundTransparency = 1, Size = UDim2.new(1, 0, 1, 0), Position = UDim2.new(0, 0, 0, 0), Image = "rbxtemp://0", ImageColor3 = state.dotState == "Default" and entryTheme.dotColor.Default or entryTheme.dotColor.Hovered, ZIndex = 2 } ) } ) } ), ContentFrame = Roact.createElement( "Frame", { BackgroundTransparency = 1, Size = UDim2.new(1, 0, 1, 0), Position = UDim2.new(0, 0, 0, 0), ZIndex = 2 }, { TextLabel = Roact.createElement( "TextLabel", { BackgroundTransparency = 1, Font = Constants.FONT_BOLD, TextColor3 = entryTheme.textColorEnabled, Size = UDim2.new(1, -entryPadding * 2, 0, Constants.FONT_SIZE_MEDIUM + entryPadding * 2), Position = UDim2.new(0, entryPadding, 1, -Constants.FONT_SIZE_MEDIUM - entryPadding * 2), TextSize = Constants.FONT_SIZE_MEDIUM, TextXAlignment = Enum.TextXAlignment.Center, TextYAlignment = Enum.TextYAlignment.Center, TextTruncate = Enum.TextTruncate.None, ZIndex = 9, Text = presetName } ) } ) } ) } ) end ) end function PresetEntry:CreatePreviewObject() debug.profilebegin("PresetEntry:CreatePreviewObject") local mainManager = getMainManager(self) local presetId = self.props.presetId local previewObjectModel = mainManager:DrawPreset( presetId, { curveType = Types.Curve.CATENARY, length = 15, points = {Vector3.new(-6.5, 0, 0), Vector3.new(6.5, 0, 0)}, seed = 0 } ) local previewObject = Instance.new("Model") previewObjectModel.Parent = previewObject debug.profileend() return previewObject end function PresetEntry:UpdateHovering() local modal = getModal(self) local hoveringInternal = self.hoveringInternal if modal.isAnyButtonPressed() then return end if modal.isShowingModal(0) then SmartSetState(self, {hovering=false}) else SmartSetState(self, {hovering=hoveringInternal}) end end function PresetEntry:didMount() local mainManager = getMainManager(self) self.mainManagerDisconnect = mainManager:subscribe( function() self:UpdateStateFromMainManager() end ) self.modalDisconnect = getModal(self).modalStatus:subscribe( function() self:UpdateHovering() end ) self.skybox.Parent = self.skyRef.current local previewObject = self:CreatePreviewObject() self.previewObject = previewObject self.previewObject.Parent = self.boxRef.current end function PresetEntry:willUnmount() self.skybox.Parent = nil self.previewObject:Destroy() self.previewObject = nil self.mainManagerDisconnect() self.modalDisconnect() end return PresetEntry
local M = {} M.log = print local function log(...) M.log(...) end local function get_metadata_filename() return sys.get_save_file(sys.get_config("project.title"), "liveupdate_meta") end local function load_metadata() return sys.load(get_metadata_filename()) end local function checksum(buffer) return hash_to_hex(hash(buffer)) end local function status_to_string(status) if status == resource.LIVEUPDATE_OK then return "LIVEUPDATE_OK" elseif status == resource.LIVEUPDATE_INVALID_RESOURCE then return "LIVEUPDATE_INVALID_RESOURCE" elseif status == resource.LIVEUPDATE_ENGINE_VERSION_MISMATCH then return "LIVEUPDATE_ENGINE_VERSION_MISMATCH" elseif status == resource.LIVEUPDATE_FORMAT_ERROR then return "LIVEUPDATE_FORMAT_ERROR" elseif status == resource.LIVEUPDATE_BUNDLED_RESOURCE_MISMATCH then return "LIVEUPDATE_BUNDLED_RESOURCE_MISMATCH" elseif status == resource.LIVEUPDATE_SCHEME_MISMATCH then return "LIVEUPDATE_SCHEME_MISMATCH" elseif status == resource.LIVEUPDATE_SIGNATURE_MISMATCH then return "LIVEUPDATE_SIGNATURE_MISMATCH" else return("UNKNOWN") end end local function download(url, cb) log("Downloading", url) http.request(url, "GET", function(self, id, response) if response.status ~= 200 then cb(nil, response) return end cb(response.response, response) end) end local config = {} function M.init(server_url) config.server_url = server_url end function M.download_manifest(cb) local url = config.server_url .. "/liveupdate.game.dmanifest" log("Downloading manifest from", url) download(url, cb) end function M.store_manifest(manifest, cb) log("Storing manifest") local manifest_hex = checksum(manifest) log("Manifest hex", manifest_hex) local metadata = sys.load(get_metadata_filename()) if metadata.manifest_hex == manifest_hex then log("LIVEUPDATE_OK - manifest already saved") cb(true) return end resource.store_manifest(manifest, function(self, status) log(status_to_string(status)) if status == resource.LIVEUPDATE_OK then log("Stored manifest - rebooting!") metadata.manifest_hex = manifest_hex sys.save(get_metadata_filename(), metadata) sys.reboot() else cb(false) end end) end function M.update_manifest(cb) M.download_manifest(function(manifest, response) if not manifest then cb(false) return end M.store_manifest(manifest, cb) end) end local function load_and_store_missing_resource(resource_hash, cb) local url = config.server_url .. "/" .. resource_hash log("Downloading missing resource", url) download(url, function(resource_data, response) if resource_data then local manifest_reference = resource.get_current_manifest() resource.store_resource(manifest_reference, resource_data, resource_hash, function(self, hexdigest, status) log("Storing resource", url, status) cb(status) end) else cb(false) end end) end function M.load_missing_resources(proxy_url, cb) log("Load missing resources", proxy_url) local missing = collectionproxy.missing_resources(proxy_url) local progress = { total = #missing, loaded = 0, failed = 0, done = #missing == 0 } pprint(missing) local load_missing = nil load_missing = function() cb(progress) if not progress.done then local resource_hash = table.remove(missing) load_and_store_missing_resource(resource_hash, function(ok) if ok then progress.loaded = progress.loaded + 1 else progress.failed = progress.failed + 1 end progress.done = (progress.loaded + progress.failed) == progress.total load_missing() end) end end load_missing() end return M
--- Utilities for libtess2 plugin. -- -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- [ MIT license: http://www.opensource.org/licenses/mit-license.php ] -- -- Standard library imports -- local floor = math.floor local huge = math.huge local max = math.max local min = math.min local sqrt = math.sqrt local select = select local unpack = unpack -- Plugins -- local libtess2 = require("plugin.libtess2") -- Corona globals -- local display = display local system = system local timer = timer -- Cached module references -- local _AddTriVert_ local _CancelTimers_ local _CloseTri_ local _GetTess_ -- Exports -- local M = {} -- -- -- local Tri = {} -- recycle the triangle function M.AddTriVert (x, y, offset) Tri[offset + 1], Tri[offset + 2] = x, y end local Timers = {} function M.CancelTimers () for i = #Timers, 1, -1 do timer.cancel(Timers[i]) Timers[i] = nil end end function M.CloseTri (group) Tri[7] = Tri[1] Tri[8] = Tri[2] display.newLine(group, unpack(Tri)) end local Ray = {} -- recycle the ray local function DrawRay (group, sx, sy, ex, ey) local dx, dy = ex - sx, ey - sy local len = sqrt(dx^2 + dy^2) local head_len = min(3, .5 * len) local tail_len = len - head_len dx, dy = dx / len, dy / len local nx, ny = -dy, dx local tx, ty = sx + dx * tail_len, sy + dy * tail_len Ray[ 1], Ray[ 2] = sx, sy Ray[ 3], Ray[ 4] = tx, ty Ray[ 5], Ray[ 6] = tx + nx * head_len, ty + ny * head_len Ray[ 7], Ray[ 8] = ex, ey Ray[ 9], Ray[10] = tx - nx * head_len, ty - ny * head_len Ray[11], Ray[12] = tx, ty local ray = display.newLine(group, unpack(Ray)) ray:setStrokeColor(1, 0, 0) end local NumberStillDrawing local RayTime = 120 local function NoOp () end local function GetContours (x, y, shape, on_begin, on_end, on_add_vertex) on_begin, on_end, on_add_vertex = on_begin or NoOp, on_end or NoOp, on_add_vertex or NoOp local si, has_prev = 1 repeat local entry = shape[si] if not entry or entry == "sep" then si, has_prev = si + 1 -- only relevant when switching contour on_end() else if not has_prev then on_begin() has_prev = true end on_add_vertex(entry + x, shape[si + 1] + y) si = si + 2 end until not entry -- cancel case end local function DrawShape (sgroup, n, shape, ...) if n > 0 then local group = display.newGroup() sgroup:insert(group) local since, pri, psx, psy, ptx, pty = system.getTimer() local on_done, on_all_done = sgroup.on_done, sgroup.on_all_done local on_begin_contour = sgroup.on_begin_contour local on_end_contour = sgroup.on_end_contour local on_add_vertex = sgroup.on_add_vertex Timers[#Timers + 1] = timer.performWithDelay(35, function(event) local elapsed, n = event.time - since, group.numChildren local timeouts = floor(elapsed / RayTime) local last, t = timeouts + 1, elapsed / RayTime - timeouts local ri, si, first, sx, sy, return_to = 1, 1 local x, y = shape.x or 0, shape.y or 0 repeat local entry = shape[si] if not entry then -- finished? timer.cancel(event.source) if pri then -- see notes below group:remove(pri) DrawRay(group, psx, psy, ptx, pty) end local tess = _GetTess_() if on_begin_contour or on_end_contour or on_add_vertex then GetContours(x, y, shape, on_begin_contour, on_end_contour, on_add_vertex) end if on_done then on_done(sgroup, tess) end NumberStillDrawing = NumberStillDrawing - 1 if NumberStillDrawing == 0 and on_all_done then on_all_done(sgroup) end elseif entry == "sep" then -- switching contours? si, sx = si + 1 elseif sx then -- have a previous point? local tx, ty = entry + x, shape[si + 1] + y if ri > n or ri == last then -- ray not yet drawn and / or in progress? local px, py = tx, ty if ri == last then -- interpolate if in progress px, py = sx + t * (tx - sx), sy + t * (ty - sy) end if ri == n then -- need to replace current entry? group:remove(n) else n = n + 1 end if pri == ri - 1 then -- finish previous interpolation, if necessary... group:remove(pri) DrawRay(group, psx, psy, ptx, pty) end pri, psx, psy, ptx, pty = ri, sx, sy, tx, ty -- ...since it will probably miss the last stretch DrawRay(group, sx, sy, px, py) end ri = ri + 1 if ri > last then -- past currently drawing ray? break else local next_entry = shape[si + 2] if return_to then -- just did a loop si, return_to = return_to elseif not next_entry or next_entry == "sep" then -- ending shape? si, return_to = first, si + 2 else -- normal ray si = si + 2 end sx, sy = tx, ty end else -- start of contour first, si, sx, sy = si, si + 2, entry + x, shape[si + 1] + y end until not entry -- cancel case, see above end, 0) DrawShape(sgroup, n - 1, ...) end end function M.DrawAll (sgroup, ...) NumberStillDrawing = select("#", ...) for i = sgroup.numChildren, 1, -1 do sgroup:remove(i) end _CancelTimers_() DrawShape(sgroup, NumberStillDrawing, ...) end local Tess = libtess2.NewTess() function M.GetTess () return Tess end function M.Polygon () local verts, xmax, ymax, xmin, ymin = {}, -huge, -huge, huge, huge return function(x, y, offset) verts[offset + 1], verts[offset + 2] = x, y xmax, ymax = max(x, xmax), max(y, ymax) xmin, ymin = min(x, xmin), min(y, ymin) end, function(group) display.newPolygon(group, (xmax + xmin) / 2, (ymax + ymin) / 2, verts) verts, xmax, ymax, xmin, ymin = {}, -huge, -huge, huge, huge end end function M.PolyTris (group, tess, rule) if tess:Tesselate(rule, "POLYGONS") then local elems = tess:GetElements() local verts = tess:GetVertices() local add_vert, close = group.add_vert or _AddTriVert_, group.close or _CloseTri_ for i = 1, tess:GetElementCount() do local base, offset = (i - 1) * 3, 0 -- for an interesting error (good to know for debugging), hoist offset out of the loop for j = 1, 3 do local index = elems[base + j] add_vert(verts[index * 2 + 1], verts[index * 2 + 2], offset) offset = offset + 2 end close(group) end end end _AddTriVert_ = M.AddTriVert _CancelTimers_ = M.CancelTimers _CloseTri_ = M.CloseTri _GetTess_ = M.GetTess return M
return {'fohn','fohnen','fohnde','fohns'}
object_mobile_target_dummy_stormtrooper = object_mobile_shared_target_dummy_stormtrooper:new { } ObjectTemplates:addTemplate(object_mobile_target_dummy_stormtrooper, "object/mobile/target_dummy_stormtrooper.iff")
require 'torch' require 'optim' require 'rosenbrock' require 'l2' x = torch.Tensor(2):fill(0) fx = {} state = {} config = {} for i = 1,10001 do x,f=optim.adamax(rosenbrock,x,config,state) if (i-1)%1000 == 0 then table.insert(fx,f[1]) end end print() print('Rosenbrock test') print() print('x=');print(x) print('fx=') for i=1,#fx do print((i-1)*1000+1,fx[i]); end
local Object = require "classic" local date = require "date" local base64 = require "base64" local EscherFactory = require "kong.plugins.escher.escher_factory" local EscherWrapper = Object:extend() local function parse_headers(ngx_headers) local headers = {} for key, value in pairs(ngx_headers) do table.insert(headers, {key, value}) end return headers end local function key_retriever(key_db) return function(key) return key_db:find_secret_by_key(key) end end function EscherWrapper:new(key_db) self.key_db = key_db end function EscherWrapper:authenticate(request, mandatory_headers_to_sign) local escher = EscherFactory.create() local request_headers = request.headers local date_as_string = request_headers["x-ems-date"] local success = pcall(date, date_as_string) if date_as_string and not success then return nil, "Could not parse X-Ems-Date header" end local headers_as_array = parse_headers(request_headers) local transformed_request = { method = request.method, url = request.url, headers = headers_as_array, body = request.body } local api_key, err, debug_info = escher:authenticate(transformed_request, key_retriever(self.key_db), mandatory_headers_to_sign) if not api_key then if request_headers["x-ems-debug"] and debug_info then err = err .. " (Base64 encoded debug message: '" .. base64.encode(debug_info) .. "')" end return nil, err else return self.key_db:find_by_key(api_key) end end return EscherWrapper
------------------------------ -- python specific settings -- ------------------------------ local keymap = vim.api.nvim_set_keymap -- UI -- {{{ vim.bo.tabstop=4 vim.bo.softtabstop=4 vim.bo.shiftwidth=4 vim.bo.textwidth=79 vim.bo.expandtab = true vim.bo.autoindent = true vim.bo.fileformat = "unix" vim.g.formatters_python = {'yapf'} -- }}} -- Keymaps -- {{{ -- autocmd FileType python nnoremap <LocalLeader>= :0,$!yapf<CR> keymap('n', '<F5>', ':AsyncRun -raw python %<CR>', { noremap=true, silent = true }) keymap('n', '<leader>cf', ':Autoformat<CR>', { noremap=true }) -- }}}
Stick = class('Stick') function Stick:initialize(x1, y1, x2, y2, texture) self.x = x1 self.y = y1 self.rotation = math.atan2(y2 - y1, x2 - x1) self.length = math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) if texture then self.texture = texture else self.texture = love.graphics.newCanvas(1, 1) love.graphics.setCanvas(self.texture) love.graphics.clear(1, 1, 1) love.graphics.setCanvas() end end function Stick:animateTo(x1, y1, x2, y2, duration, ease) local newRotation = math.atan2(y2 - y1, x2 - x1) local newLength = math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) self._moveTween = tween.new(duration or 1, self, {x = x1, y = y1, rotation = newRotation, length = newLength}, ease or 'inOutCubic') end function Stick:update(dt) if self._moveTween then if self._moveTween:update(dt) then self._moveTween = nil end end end function Stick:endAnimation() self._moveTween:set(self._moveTween.duration) self._moveTween = nil end function Stick:render() love.graphics.draw(self.texture, self.x, self.y, self.rotation, self.length / self.texture:getWidth(), 1) end function Stick:isAnimating() return self._moveTween ~= nil end function Stick:destination() return self.x + math.cos(self.rotation) * self.length, self.y + math.sin(self.rotation) * self.length end function Stick:unpack() return self.x, self.y, self:destination() end function Stick:copy() return Stick:new(self.x, self.y, self:destination()) end return Stick
-- Test Sword Item item = {} item.graphic = "items/sword:main" item.groundGraphic = "items/sword:ground" item.stats = {minDamage = "+ 3", maxDamage = "+ 7"} item.itemType = "sword" item.name = "Sword" item.prefix = "Wooden" item.postfix = "of Test"
TerrainChunk = Object:extend() function TerrainChunk:new(scale, image, pos) self.texture = image self.textureHeight = 0 self.textureWidth = 0 self.x = 0 self.y = 0 self.id = love.math.random() if not (pos == nil) then self.x = pos.x or pos[1] self.y = pos.y or pos[2] end if not (self.texture == nil) then self.texture:setWrap("repeat", "repeat") self.textureHeight = self.texture:getHeight() self.textureWidth = self.texture:getWidth() end self.scale = scale self.terrainPoints = {} self.mesh = nil self.workingLength = 0 self.meshVertices = {} end function TerrainChunk:valueAtPoint(i, j) if (self.terrainPoints[i] == nil) then return nil end return self.terrainPoints[i][j] end function TerrainChunk:getPoints() return self.terrainPoints end function TerrainChunk:newPoint(value, i, j) if (self.terrainPoints[i] == nil) then table.insert(self.terrainPoints, i, {}) end if (self.terrainPoints[i][j] == nil) then table.insert(self.terrainPoints[i], j, value) else self.terrainPoints[i][j] = value end end function TerrainChunk:initialiseThread(points) self.meshVertices = {} self.generate = love.thread.newThread("Modules/counterGenerationThread.lua") self.generate:start(self.id, self.x, self.y, self.textureHeight, self.textureWidth, self.scale, self.terrainPoints) end function TerrainChunk:update() while love.thread.getChannel("vertices"..self.id):getCount() > 0 do local vertixTable = love.thread.getChannel("vertices"..self.id):pop() if not (vertixTable == nil) then table.insert(self.meshVertices, vertixTable) end end if not (self.generate:isRunning()) then self.workingLength = #self.meshVertices self.mesh = love.graphics.newMesh(self.workingLength+36000, "triangles") self.mesh:setTexture(self.texture) if (self.workingLength > 0) then self.mesh:setVertices(self.meshVertices, 1, self.workingLength) self.mesh:setDrawRange(1, self.workingLength) end local error = self.generate:getError() assert(not error, error) self.generate = nil return true end return false end function TerrainChunk:isoEdge(i, j, middleValue) local shiftX = 0.5*self.scale local function addVertices(vertices) for _, v in ipairs(vertices) do local vertixTable = { v[1], v[2], v[1]/self.textureWidth/2, v[2]/self.textureHeight/2, 1, 1, 1, 1 } self.workingLength = self.workingLength + 1 table.insert(self.meshVertices,vertixTable) if (self.workingLength > self.mesh:getVertexCount()) then self.mesh = love.graphics.newMesh(self.workingLength + 36000, "triangles") self.mesh:setTexture(self.texture) self.mesh:setDrawRange(1, self.workingLength) self.mesh:setVertices(self.meshVertices, 1, self.workingLength) print("newLength: "..self.workingLength) end self.mesh:setVertex(self.workingLength, vertixTable) end end local x, y = j*self.scale + self.x, i*self.scale + self.y local valueSquare = ValueSquare() local relativeVertices = { {self.terrainPoints[i-1][j-1], x - self.scale, y - self.scale}, -- upper left {self.terrainPoints[i-1][j ], x, y - self.scale}, -- upper middle {self.terrainPoints[i-1][j+1], x + self.scale, y - self.scale}, -- upper right {self.terrainPoints[i ][j+1], x + self.scale, y}, -- middle right {self.terrainPoints[i+1][j+1], x + self.scale, y + self.scale}, -- lower right {self.terrainPoints[i+1][j ], x, y + self.scale}, -- lower middle {self.terrainPoints[i+1][j-1], x - self.scale, y + self.scale}, -- lower left {self.terrainPoints[i ][j-1], x - self.scale, y}, -- middle left {self.terrainPoints[i ][j ], j*self.scale, i*self.scale}} -- current for k = 1, 4 do valueSquare:replaceVertex(1, relativeVertices[2^(k-1) + (1-k)*(2-k)*(4-k)*2.5]) valueSquare:replaceVertex(2, relativeVertices[k + 1 - (1-k)*(2-k)*(3-k)/6*4]) valueSquare:replaceVertex(3, relativeVertices[k + 2 + (2-k)*(3-k)*(4-k)]) valueSquare:replaceVertex(4, relativeVertices[(k+2)%4+5 - (1-k)*(3-k)*(4-k)*2]) addVertices(valueSquare:intraprolated(middleValue)) end if (self.workingLength > 1) then self.mesh:setDrawRange(1, self.workingLength) end end function TerrainChunk:getShift() return self.x, self.y end function TerrainChunk:drawMesh() if not (self.mesh == nil) then love.graphics.draw(self.mesh) end end function TerrainChunk:drawPoints() for i, row in ipairs(self.terrainPoints) do for j,v in ipairs(row) do if (v >= 0.5) then love.graphics.setColor(v+0.1, v+0.1, v+0.1) love.graphics.points(j*self.scale + self.x, i*self.scale + self.y) end end end end function TerrainChunk:resolveColision(x, y, r) local xMin, yMin = 1000, 1000 for i = 1, #self.meshVertices/3 do vertix1 = self.meshVertices[i*3-2] vertix2 = self.meshVertices[i*3-1] vertix3 = self.meshVertices[i*3] -- local xAvg = (vertix1[1] + vertix2[1] + vertix3[1])/3 -- local yAvg = (vertix1[2] + vertix2[2] + vertix3[2])/3 -- if circleVsCircle(x, y, r, xAvg, yAvg, self.scale*0.5) then -- if triangleVsCircle(vertix1[1], vertix1[2], vertix2[1], vertix2[2], vertix3[1], vertix3[2], x, y, r) then qx, qy = pointOnTriangle(x, y, vertix1[1], vertix1[2], vertix2[1], vertix2[2], vertix3[1], vertix3[2]) if((x-qx)^2 + (y-qy)^2 < (x-xMin)^2 + (y-yMin)^2) then xMin, yMin = qx, qy end -- end -- end end if (xMin == 1000 and yMin == 1000) then return false, false end return xMin, yMin -- return false end
--[[ ------------------------------------------ change "LuaStat" in your project if you need specific another directory ------------------------------------------ THIS PROGRAM is developed by Hubert Ronald https://sites.google.com/view/liasoft/home Feel free to distribute and modify code, but keep reference to its creator The MIT License (MIT) Copyright (C) 2017 Hubert Ronald Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------ ]] -- math functions local rand = math.random local ln = math.log -- natural logarithm local sqrt = math.sqrt local pi = math.pi local exp = math.exp -- e exponent local pow = math.pow -- non-math functions local ipairs = ipairs local table_sort = table.sort -- sum array function local function sumF(array) local s = 0 for _, v in ipairs(array) do s=s+v end return s end -- average array function local function avF(array) local s = sumF(array) return s/#array end -- (n-1) standard deviation local function stvF(array) local xp, sq = avF(array), 0 for _,v in ipairs(array) do sq = sq + (v - xp)^2 end return (sq/(#array-1))^0.5 end local function frecuencyF(array) local list, frec = {}, {g={},c={}} -- group, count for k,v in ipairs(array) do list[k] = v end table_sort(list) frec.g[1], frec.c[1] = list[1], 1 for i=2, #list do if frec.g[#frec.g]==list[i] then frec.c[#frec.c] = frec.c[#frec.c] + 1 else frec.c[#frec.c+1], frec.g[#frec.g+1] = 1, list[i] end end return frec end local function normalVA(mu, sig) -- normal standar: mu=0,sig=1 -- method schmeiser local mu, sig, r = mu or 0, sig or 1, rand() local z = (r^0.135 - (1-r)^0.135)/0.1975 return z*sig + mu end local function normal_inv_D(p, mu, sig) -- nomal standar mu=0,sig=1, p~[0,1]: (probability) -- method schmeiser local mu, sig, p = mu or 0, sig or 1, p or 0.5 -- 'p' parameter fixed local z = (p^0.135 - (1-p)^0.135)/0.1975 return z*sig + mu end local function bernoulliVA(p) if rand()<= p then return 1 else return 0 end end local function unifVA(min,max) return (max-min)*rand() + min end local function expoVA(beta) return (-1/beta)*ln(1.0-rand()) end local function weibullVA(alpha,beta) return alpha*(-ln(1.0-rand()))^(1/beta) end local function erlangVA(n, lambda) local VaErlang = 0 for i=1, n do VaErlang = VaErlang + expoVA(lambda) end return VaErlang end local function trianVA(a,b,c) local a,b,c = a or 1, b or 2, c or 3 if rand() <= (b-a)/(c-1) then return a + ((b-a)*(c-a)*r)^0.5 else return c - ((c-b)*(c-a)*(1-r))^0.5 end end local function binomialVA(n,p) local n, p , va = n or 1, p or 0.5, 0 -- convolution method for i=1,n do va=va+bernoulliVA(p) end return va end local function poissonVA(lamba) local t, va, lamba = 0, 0, lamba or 0.5 -- convolution method while true do t = t+expoVA(lamba) if t <= 1 then va = va + 1 else break end end return va end local function geometricVA(p) --[[ ------------------------------------------------------------ -- See details in: -- https://math.stackexchange.com/questions/485448/prove-the-way-to-generate-geometrically-distributed-random-numbers ------------------------------------------------------------ ]] local U = 1-rand() local va = ln(U)/ln(1-p) return va end local function chiSquareVA(n) local va = 0 for i=1, n do va = va + normalVA() end return va^0.5 end local function gamVA(alpha, lamba) --[[ ------------------------------------------------------------ -- generator using Marsaglia and Tsang method -- See details in the work of [Marsaglia and Tsang (2000)]. -- check this paper: -- http://www.ijcse.com/docs/INDJCSE14-05-06-048.pdf ------------------------------------------------------------ ]] local alpha, lamba = alpha or 0.5, lamba or 0.5 local va=0 if alpha >= 1 then local d=alpha-1/3 local c=1/(9*d)^.5 while (true) do local Z=normalVA() if Z>-1/c then local V=(1+c*Z)^3 local U=1-rand() if ln(U)<0.5*Z^2+d-d*V+d*ln(V) then va=d*V/lamba break end end end elseif alpha>0 and alpha<1 then va=gamVA(alpha+1,lamba) va=va*rand()^(1/alpha) else print("alpha must be > 0") end return va end local function lognoVA(m, s) --[[ ------------------------------------------------------------ -- Took -- See details in these links -- http://stackoverflow.com/questions/23699738/how-to-create-a-random-number-following-a-lognormal-distribution-in-excel -- http://blogs.sas.com/content/iml/2014/06/04/simulate-lognormal-data-with-specified-mean-and-variance.html ------------------------------------------------------------ ]] local m, s = m or 0, s or 1 -- Next step is to scale the mean and standard deviation local mean = ln( m^2 / sqrt( m^2 + s^2 )) local sd = sqrt( ln(( m^2 + s^2 ) / m^2 )) local x = normal_inv_D(rand, mean, sd) return exp(x) end return { sumF=sumF, avF=avF, stvF=stvF, frecuencyF=frecuencyF, nomalVA=nomalVA, normal_inv_D=normal_inv_D, bernoulliVA=bernoulliVA, unifVA=unifVA, expoVA=expoVA, weibullVA=weibullVA, erlangVA=erlangVA, trianVA=trianVA, binomialVA=binomialVA, geometricVA=geometricVA, poissonVA=poissonVA, chiSquareVA=chiSquareVA, gamVA=gamVA, lognoRandVA=lognoRandVA, }
return {'jhinkoe'}
local TimerList do local time = os.time TimerList = {} local meta = {__index = TimerList} --[[@ @name new @desc Creates a new instance of TimerList. @param obj?<table> The table to turn into a TimerList. @returns TimerList The new TimerList object. @struct { last = Timer -- the last timer (the one that must trigger before all the others). Might be nil. } ]] function TimerList.new(obj) return setmetatable(obj or {}, meta) end --[[@ @name add @desc Adds a timer to the list. @desc `timer.callback` will receive the timer as the unique argument, so you can add more values here @param timer<Timer> The timer to add. @paramstruct timer { callback<function> The callback function. when<int> When it will be executed. } @returns Timer The timer you've added ]] function TimerList:add(timer) timer.list = self if not self.last then self.last = timer elseif self.last.when < timer.when then -- sorts the timer in descendent order local current, last = self.last.previous, self.last while current and current.when < timer.when do current, last = current.previous, current end timer.previous, last.previous = current, timer else timer.previous = self.last self.last = timer end return timer end --[[@ @name run @desc Runs the timers that need to be run. ]] function TimerList:run() local now, current = time(), self.last while current and current.when <= now do current:callback() -- gives the timer itself to the callback current = current.previous end self.last = current end --[[@ @name remove @desc Removes a timer from the list. @param timer<Timer> The timer to remove. ]] function TimerList:remove(timer) if self.last == timer then self.last = timer.previous return end local current, last = self.last.previous, self.last while current and current ~= timer do current, last = current.previous, current end if current then last.previous = timer.previous end end end return { TimerList = TimerList }
local Frame = script.Parent local PhoneButton = Frame:WaitForChild("HomeScreenApps"):WaitForChild("Phone") local BackButton = Frame:WaitForChild("PhonePage"):WaitForChild("Back") local HomeScreenApps = Frame:WaitForChild("HomeScreenApps"):GetChildren() local Contact = Frame.PhonePage:WaitForChild("Contact") local PeopleFrame = Frame.PhonePage:WaitForChild("PeopleFrame") PhoneButton.MouseButton1Click:Connect(function() local PhonePage = Frame.PhonePage:GetChildren() for _,v in pairs (PhonePage)do v.Visible = true end Frame.PhonePage.Contact.Visible = false -- needs to stay false always for _,v in pairs (HomeScreenApps)do v.Visible = false end local players = game.Players:GetChildren() for _, v in pairs (players) do if (v.Backpack:FindFirstChild("iExotic 11 Pro Max") or v.Character:FindFirstChild("iExotic 11 Pro Max")) and PeopleFrame:FindFirstChild(v.Name) == nil and v.Name ~= game.Players.LocalPlayer.Name then local newContact = Contact:Clone() newContact.Parent = PeopleFrame newContact.Visible = true local content, isReady = game:GetService("Players"):GetUserThumbnailAsync(v.UserId, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size420x420) -- Set the ImageLabel's content to the user thumbnail local imageLabel = newContact.Avatar imageLabel.Image = content newContact.ID.Text = v.UserId newContact.Username.Text = v.Name newContact.Name = v.Name end end end) BackButton.MouseButton1Click:Connect(function() local PhonePage = Frame.PhonePage:GetChildren() for _,v in pairs (PhonePage)do v.Visible = false end for _,v in pairs (HomeScreenApps)do v.Visible = true end end)
local varm_util = require("modules/varm_util") -- Include individual node definitions and preprocessors. local node_types = require("modules/fsm_node_defs") local FSMNodes = {} -- Create the initial filesystem structure for the project, using -- information stored in the startup 'Boot' node. Store relevant -- information in a table for the preprocessor to keep track of. function FSMNodes.init_project_state(boot_node, node_graph, global_decs, proj_id) local p_state = {} local proj_int = tonumber(proj_id) if proj_int <= 0 then return p_state end -- Store global variable declarations. p_state.global_decs = global_decs -- Set the base directory, and make it if it doesn't exist. local proj_dir = 'project_storage/precomp_' .. proj_int .. '/' if varm_util.ensure_dir_empty(proj_dir) then p_state.base_dir = proj_dir -- Verify or create other required directories for the project skeleton. -- Also empty the directory contents, if any. if varm_util.ensure_dir_empty(proj_dir .. 'boot_s/') and varm_util.ensure_dir_empty(proj_dir .. 'ld/') and varm_util.ensure_dir_empty(proj_dir .. 'lib/') and varm_util.ensure_dir_empty(proj_dir .. 'vector_tables/') and varm_util.ensure_dir_empty(proj_dir .. 'src/') and varm_util.ensure_dir_empty(proj_dir .. 'src/std_periph/') and varm_util.ensure_dir_empty(proj_dir .. 'src/arm_include/') then p_state.dir_structure = 'valid' -- Generate the 'boot' assembly script. p_state.boot_script = FSMNodes.gen_boot_script(boot_node, p_state) -- Generate the linker script. p_state.ld_script = FSMNodes.gen_ld_script(boot_node, p_state) -- Copy the static GCC libs. p_state.with_toolchain_libs = FSMNodes.copy_static_libs(boot_node, p_state) -- Generate the vector table. p_state.vector_table = FSMNodes.gen_vector_table(boot_node, p_state) -- Generate the bare-bones source files. p_state.src_base = FSMNodes.gen_bare_source_files(boot_node, p_state) -- Generate a Makefile and LICENSE/README.md files. p_state.build_files_generated = FSMNodes.gen_build_files(boot_node, p_state) -- TODO: Delete, after making EXTI stuff only import when needed. if not varm_util.import_std_periph_lib('exti', p_state.base_dir) or not varm_util.import_std_periph_lib('syscfg', p_state.base_dir) then return nil end else return p_state end else return p_state end return p_state end function FSMNodes.get_boot_chip_type(boot_node) -- (Default value) local chip_type = 'STM32F030F4' if boot_node and boot_node.options and boot_node.options.chip_type then local boot_chip = boot_node.options.chip_type -- (Accepted options.) if boot_chip == 'STM32F030F4' or boot_chip == 'STM32F031F6' or boot_chip == 'STM32F030K6' then chip_type = boot_chip end end return chip_type end -- Generate a .S assembly script to boot the specified chip with the -- specified options (from the 'Boot' node.) It resets the 'bss' portions of -- RAM to 0s, copies the 'data' portions, sets the core clock frequency, -- that sort of annoying bookkeeping stuff. -- Return the relative path to the generated boot script. function FSMNodes.gen_boot_script(boot_node, cur_proj_state) local chip_type = FSMNodes.get_boot_chip_type(boot_node) -- Copy the appropriate boot script. local boot_script_fn = chip_type .. 'T6_boot.S' local boot_script_source_dir = 'static/node_code/boot/boot/' local boot_script_source_path = boot_script_source_dir .. boot_script_fn local boot_script_dest_dir = cur_proj_state.base_dir .. 'boot_s/' local boot_script_dest_path = boot_script_dest_dir .. boot_script_fn if varm_util.copy_text_file(boot_script_source_path, boot_script_dest_path) then return boot_script_dest_path end return nil end -- Copy a linker script for the given MCU chip into the 'ld/' directory. -- Linker scripts specify things like how much RAM and Flash storage -- the chip has available, so the compiler knows which addresses to use. function FSMNodes.gen_ld_script(boot_node, cur_proj_state) local chip_type = FSMNodes.get_boot_chip_type(boot_node) -- Copy the appropriate linker script. local ld_script_fn = chip_type .. 'T6.ld' local ld_script_source_dir = 'static/node_code/boot/ld/' local ld_script_source_path = ld_script_source_dir .. ld_script_fn local ld_script_dest_dir = cur_proj_state.base_dir .. 'ld/' local ld_script_dest_path = ld_script_dest_dir .. ld_script_fn if varm_util.copy_text_file(ld_script_source_path, ld_script_dest_path) then return ld_script_dest_path end return nil end -- Copy library files. TODO: These files are too big. They should come with -- the GCC toolchain, but I've had trouble with getting it to recognize -- the correct 'libc' libraries for local armv6m builds automatically. -- (These library files are a little over 10MB put together) function FSMNodes.copy_static_libs(boot_node, cur_proj_state) -- These are the same for all armv6m chips, although lines other than -- Cortex-M0 chips may be armv7m. But really, these libraries shouldn't -- need to be served as part of a generated project. local libc_fn = 'libc.a' local libgcc_fn = 'libgcc.a' local clib_source_dir = 'static/node_code/boot/lib/' local libc_source_path = clib_source_dir .. libc_fn local libgcc_source_path = clib_source_dir .. libgcc_fn local clib_dest_dir = cur_proj_state.base_dir .. 'lib/' local libc_dest_path = clib_dest_dir .. libc_fn local libgcc_dest_path = clib_dest_dir .. libgcc_fn if not varm_util.copy_bin_file(libc_source_path, libc_dest_path) then return nil end if not varm_util.copy_bin_file(libgcc_source_path, libgcc_dest_path) then return nil end -- This method just returns a flag for 'toolchain libraries okay/not okay' return true end -- Generate a vector table for the given chip. Eventually, this can be used -- to set hardware interrupts, but for now just copy a common one which -- routes all interrupts to a common default 'error/infinite loop' handler. function FSMNodes.gen_vector_table(boot_node, cur_proj_state) local chip_type = FSMNodes.get_boot_chip_type(boot_node) -- Copy the appropriate vector table file. local vt_script_fn = chip_type .. 'T6_vt.S' local vt_script_source_dir = 'static/node_code/boot/vector_tables/' local vt_script_source_path = vt_script_source_dir .. vt_script_fn local vt_script_dest_dir = cur_proj_state.base_dir .. 'vector_tables/' local vt_script_dest_path = vt_script_dest_dir .. vt_script_fn -- Copy files. if varm_util.copy_text_file(vt_script_source_path, vt_script_dest_path) then return vt_script_dest_path end return nil end -- Generate bare-bones source files; basically, some mostly-empty headers -- / utility files, and an empty main method which should get called after -- booting, if you compiled everything after the 'init_project_state' method. function FSMNodes.gen_bare_source_files(boot_node, cur_proj_state) local chip_type = FSMNodes.get_boot_chip_type(boot_node) -- Right now, it looks like we should copy: -- - src/core.S -- - src/util.S -- - src/main.c -- - src/main.h -- - src/global.h -- - src/util_c.h -- - src/util_c.c -- - src/interrupts_c.h -- - src/interrupts_c.c -- - src/stm32f0xx.h -- - src/stm32f0xx_conf.h -- - src/std_periph -- - (none) -- - src/arm_include/ -- - arm_common_tables.h -- - arm_const_structs.h -- - arm_math.h -- - core_cm0.h -- - core_cm0plus.h -- - core_cmFunc.h -- - core_cmInstr.h local files_to_copy = { 'src/core.S', 'src/util.S', 'src/global.h', 'src/main.h', 'src/main.c', 'src/stm32f0xx.h', 'src/util_c.h', 'src/util_c.c', 'src/interrupts_c.h', 'src/interrupts_c.c', 'src/stm32f0xx_conf.h', 'src/arm_include/arm_common_tables.h', 'src/arm_include/arm_const_structs.h', 'src/arm_include/arm_math.h', 'src/arm_include/core_cm0.h', 'src/arm_include/core_cm0plus.h', --TODO: delete? 'src/arm_include/core_cmFunc.h', 'src/arm_include/core_cmInstr.h', } local copy_success = true for k, val in pairs(files_to_copy) do if val then local src_p = 'static/node_code/boot/' .. val local dest_p = cur_proj_state.base_dir .. val if not varm_util.copy_text_file(src_p, dest_p) then copy_success = false end end end -- One of the files copied, 'src/global.h', should also have initial -- global/static variable declarations: local g_vars_text = '' local m_vars_text = '' for i, val in pairs(cur_proj_state.global_decs) do if val and val.var_name and val.var_type and val.var_val then local var_c_type = val.var_type local var_c_val = tostring(val.var_val) if var_c_type == 'bool' then var_c_type = 'unsigned char' if var_c_val == 'false' or var_c_val == '0' then var_c_val = '0'; elseif var_c_val == 'true' or var_c_val == '1' then var_c_val = '1'; else -- Default to 'false'. var_c_val = '0'; end elseif var_c_type == 'char' then var_c_val = "'" .. var_c_val .. "'" end g_vars_text = g_vars_text .. 'volatile ' .. var_c_type .. ' ' .. val.var_name .. ';\n' m_vars_text = m_vars_text .. ' ' .. val.var_name .. ' = ' .. var_c_val .. ';\n' end end if not varm_util.insert_into_file(cur_proj_state.base_dir .. 'src/global.h', "/ GLOBAL_VAR_DEFINES:", g_vars_text) then copy_success = false end if not varm_util.insert_into_file(cur_proj_state.base_dir .. 'src/main.c', "/ MAIN_VAR_DEFS:", m_vars_text) then copy_success = false end return copy_success end -- Generate build files. So, a GNU Makefile, a README.md which advises -- users not to take programming tips from the autogenerated GOTO-riddled -- code, and an MIT LICENSE file. function FSMNodes.gen_build_files(boot_node, cur_proj_state) local chip_type = FSMNodes.get_boot_chip_type(boot_node) -- Copy the common README.md/LICENSE files, along with a -- chip-specific Makefile for GNU Make. local makefile_source_fn = 'Make_' .. chip_type local makefile_source_dir = 'static/node_code/boot/makefiles/' local makefile_source_path = makefile_source_dir .. makefile_source_fn local license_source_path = 'static/node_code/boot/LICENSE' local readme_source_path = 'static/node_code/boot/README.md' local makefile_dest_path = cur_proj_state.base_dir .. 'Makefile' local license_dest_path = cur_proj_state.base_dir .. 'LICENSE' local readme_dest_path = cur_proj_state.base_dir .. 'README.md' -- Copy files. if not varm_util.copy_text_file(makefile_source_path, makefile_dest_path) then return nil end if not varm_util.copy_text_file(license_source_path, license_dest_path) then return nil end if not varm_util.copy_text_file(readme_source_path, readme_dest_path) then return nil end -- This method just returns a 'build files generated/not generated' flag. return true end -- Process a single node in the FSM graph. -- Return true if the processing succeeds, false if it doesn't. function FSMNodes.process_node(node, node_graph, proj_state) -- Loading a node takes two steps. -- - First, we verify that all of the necessary utility methods/includes -- exist, and copy them into the project files if they aren't. -- - Second, we add the code to the end of the 'main' method. Like this: -- <This node's unique label>: -- <node code> -- GOTO <Next node's label> -- But this method will really just call other ones based on the node type. if (not node) or (not node.node_type) then return nil end for k, val in pairs(node_types) do if node.node_type == k then if (val.ensure_support_methods(node, proj_state) and val.append_node(node, node_graph, proj_state)) then return true end break end end -- (Unrecognized node type or preprocessing failure.) return nil end return FSMNodes
ZPClass.Name = "HumanHeavyClassName" ZPClass.Description = "HumanHeavyClassDescription" ZPClass.MaxHealth = 150 ZPClass.Armor = 100 ZPClass.PModel = "models/player/combine_super_soldier.mdl" ZPClass.Speed = 210 ZPClass.RunSpeed = 100 ZPClass.CrouchSpeed = 0.3 ZPClass.Gravity = 1.2 ZPClass.Battery = 200 ZPClass.Breath = 150 ClassManager:AddZPClass("HeavyHuman", ZPClass, TEAM_HUMANS)
local helpers = require("spec_helper") describe("cliargs - options", function() local cli before_each(function() cli = require("cliargs.core")() end) describe('defining options', function() it('requires a key', function() assert.error_matches(function() cli:option() end, 'Key and description are mandatory arguments') end) it('requires a description', function() assert.error_matches(function() cli:option('--url=URL') end, 'Key and description are mandatory arguments') end) it('works', function() assert.has_no_errors(function() cli:option('--url=URL', '...') end) end) it('rejects a duplicate option', function() cli:option('--url=URL', '...') assert.error_matches(function() cli:option('--url=URL', '...') end, 'Duplicate') end) end) it('works with only a short key: -u VALUE', function() cli:option('-u VALUE', '...') assert.equal(helpers.parse(cli, '-u something').u, 'something') end) it('works with only an expanded key: --url=VALUE', function() cli:option('--url=VALUE', '...') assert.equal(helpers.parse(cli, '--url=something').url, 'something') end) it('works with only an expanded key using space as a delimiter: --url VALUE', function() cli:option('--url VALUE', '...') assert.equal(helpers.parse(cli, '--url something').url, 'something') end) it('works with both: -u, --url=VALUE', function() cli:option('-u, --url=VALUE', '...') assert.equal(helpers.parse(cli, '--url=something').url, 'something') assert.equal(helpers.parse(cli, '-u=something').url, 'something') end) it('works with both keys and no comma between them: -u --url VALUE', function() cli:option('-u --url=VALUE', '...') assert.equal(helpers.parse(cli, '--url something').url, 'something') assert.equal(helpers.parse(cli, '-u something').url, 'something') end) context('given no value indicator (an implicit flag, e.g. --quiet)', function() it('proxies to #flag', function() stub(cli, 'flag') cli:option('-q', '...') assert.stub(cli.flag).was.called(); end) end) describe('parsing', function() before_each(function() cli:option('-s, --source=SOURCE', '...') end) context('using a -short key and space as a delimiter', function() it('works', function() local args = helpers.parse(cli, '-s /foo/**/*.lua') assert.equal(args.source, '/foo/**/*.lua') end) end) context('using a -short key and = as a delimiter', function() it('works', function() local args = helpers.parse(cli, '-s=/foo/**/*.lua') assert.equal(args.source, '/foo/**/*.lua') end) end) context('using an --expanded-key and space as a delimiter', function() it('works', function() local args = helpers.parse(cli, '--source /foo/**/*.lua') assert.equal(args.source, '/foo/**/*.lua') end) end) context('using an --expanded-key and = as a delimiter', function() it('works', function() local args = helpers.parse(cli, '--source=/foo/**/*.lua') assert.equal(args.source, '/foo/**/*.lua') end) end) context('for an option with a short key longer than 1 char', function() before_each(function() cli:option('-Xassembler OPTIONS', '...') end) it('works', function() local args = helpers.parse(cli, '-Xassembler foo') assert.equal(args.Xassembler, 'foo') end) end) context('given multiple values', function() before_each(function() cli:option('-k, --key=OPTIONS', '...', {}) end) it('works', function() local args = helpers.parse(cli, '-k 1 --key=3 -k asdf') assert.equal(type(args.k), 'table') assert.equal(#args.k, 3) assert.equal(args.k[1], '1') assert.equal(args.k[2], '3') assert.equal(args.k[3], 'asdf') end) end) context('given an unknown option', function() it('bails', function() local _, err = helpers.parse(cli, '--asdf=jkl;', true) assert.matches('unknown', err) end) end) it('bails if no value was passed', function() local _, err = helpers.parse(cli, '-s') assert.matches("option %-s requires a value to be set", err) end) end) describe('parsing with a default value', function() it('accepts a nil', function() cli:option('--compress=VALUE', '...', nil) assert.equal(helpers.parse(cli, '').compress, nil) end) it('accepts a string', function() cli:option('--compress=VALUE', '...', 'lzma') assert.equal(helpers.parse(cli, '').compress, 'lzma') end) it('accepts a number', function() cli:option('--count=VALUE', '...', 5) assert.equal(helpers.parse(cli, '').count, 5) end) it('accepts a boolean', function() cli:option('--quiet=VALUE', '...', true) assert.equal(helpers.parse(cli, '').quiet, true) end) it('accepts an empty table', function() cli:option('--sources=VALUE', '...', {}) assert.same(helpers.parse(cli, '').sources, {}) end) it('lets me override/reset the default value', function() cli:option('--compress=URL', '...', 'lzma') assert.equal(helpers.parse(cli, '--compress=').compress, nil) end) end) describe('@callback', function() local call_args local function capture(key, value, altkey) table.insert(call_args, { key, value, altkey }) end context('given a single option', function() before_each(function() call_args = {} cli:option('-c, --compress=VALUE', '...', nil, capture) end) it('invokes the callback when the option is parsed', function() helpers.parse(cli, '--compress=lzma') assert.equal(call_args[1][1], 'compress') assert.equal(call_args[1][2], 'lzma') assert.equal(call_args[1][3], 'c') end) it('invokes the callback with the latest value when the option is a list', function() cli:option('--tags=VALUE', '...', {}, capture) helpers.parse(cli, '--tags only --tags foo') assert.equal(call_args[1][1], 'tags') assert.equal(call_args[1][2], 'only') assert.equal(call_args[1][3], nil) assert.equal(call_args[2][1], 'tags') assert.equal(call_args[2][2], 'foo') assert.equal(call_args[2][3], nil) end) end) context('when the callback returns an error message', function() it('propagates the error', function() cli:option('-c, --compress=VALUE', '...', nil, function() return nil, ">>> bad argument <<<" end) local _, err = helpers.parse(cli, '-c lzma', true) assert.equal('>>> bad argument <<<', err) end) end) context('given multiple options', function() before_each(function() call_args = {} cli:option('-c, --compress=VALUE', '...', nil, capture) cli:option('--input=PATH', '...', nil, capture) end) it('invokes the callback for each option parsed', function() helpers.parse(cli, '-c lzma --input=/tmp') assert.equal(call_args[1][1], 'c') assert.equal(call_args[1][2], 'lzma') assert.equal(call_args[1][3], 'compress') assert.equal(call_args[2][1], 'input') assert.equal(call_args[2][2], '/tmp') assert.equal(call_args[2][3], nil) end) end) end) end)
--- -- @author wesen -- @copyright 2019 wesen <[email protected]> -- @release 0.1 -- @license MIT -- local BaseClientOutput = require("AC-ClientOutput/ClientOutput/BaseClientOutput") local StringSplitter = require("AC-ClientOutput/ClientOutput/ClientOutputString/StringSplitter") local StringWidthCalculator = require("AC-ClientOutput/ClientOutput/ClientOutputString/StringWidthCalculator") --- -- Represents a output string for the console in the players games. -- Allows to split a string into rows based on a specified width. -- -- @type ClientOutputString -- local ClientOutputString = {} --- -- The raw string -- The text may not contain the special character "\n" -- -- @tfield string string -- ClientOutputString.string = nil -- -- The client output string splitter -- -- @tfield ClientOutputStringSplitter splitter -- ClientOutputString.splitter = nil -- Metamethods --- -- ClientOutputString constructor. -- This is the __call metamethod. -- -- @tparam SymbolWidthLoader _symbolWidthLoader The symbol width loader -- @tparam TabStopCalculator _tabStopCalculator The tab stop calculator -- @tparam int _maximumLineWidth The maximum line width -- -- @treturn ClientOutputString The ClientOutputString instance -- function ClientOutputString:__construct(_symbolWidthLoader, _tabStopCalculator, _maximumLineWidth) local instance = BaseClientOutput(_symbolWidthLoader, _tabStopCalculator, _maximumLineWidth) setmetatable(instance, {__index = ClientOutputString}) instance.splitter = StringSplitter(instance, _symbolWidthLoader, _tabStopCalculator) return instance end -- Getters and Setters --- -- Returns the target string. -- -- @treturn string The target string -- function ClientOutputString:getString() return self.string end -- Public Methods --- -- Parses a string into this ClientOutputString. -- -- @tparam string _string The string to parse -- function ClientOutputString:parse(_string) self.string = _string:gsub("\n", "") end --- -- Returns the number of tabs that this client output's content requires. -- -- @treturn int The number of required tabs -- function ClientOutputString:getNumberOfRequiredTabs() local stringWidthCalculator = StringWidthCalculator(self.symbolWidthLoader, self.tabStopCalculator) return self.tabStopCalculator:getNextTabStopNumber(stringWidthCalculator:getStringWidth(self.string)) end --- -- Returns the minimum number of tabs that this client output's content requires. -- -- @treturn int The minimum number of required tabs -- function ClientOutputString:getMinimumNumberOfRequiredTabs() return 1 end --- -- Returns the output rows to display this client output's contents. -- -- @treturn string[] The output rows -- function ClientOutputString:getOutputRows() return self.splitter:getRows() end --- -- Returns the output rows padded with tabs until a specified tab number. -- -- @tparam int _tabNumber The tab number -- -- @treturn string[] The output rows padded with tabs -- function ClientOutputString:getOutputRowsPaddedWithTabs(_tabNumber) return self.splitter:getRows(_tabNumber) end setmetatable( ClientOutputString, { -- ClientOutputString inherits methods and attributes from BaseClientOutput __index = BaseClientOutput, -- When ClientOutputString() is called, call the __construct method __call = ClientOutputString.__construct } ) return ClientOutputString
data.raw["generator"]["steam-engine"].fast_replaceable_group = "steam-engine" data.raw["accumulator"]["accumulator"].fast_replaceable_group = "accumulator" data.raw["solar-panel"]["solar-panel"].fast_replaceable_group = "solar-panel"
RegisterServerEvent('stationLock:LockDoor') AddEventHandler('stationLock:LockDoor', function(door, bool) doorList[door]["locked"] = bool TriggerClientEvent('stationLock:LockDoor', -1, door, bool) end) RegisterServerEvent('stationLock:checkDoor') AddEventHandler('stationLock:checkDoor', function() TriggerClientEvent('stationLock:checkDoor', source, doorList) end) doorList = { -- Mission Row To locker room & roof [1] = { ["objName"] = "v_ilev_ph_gendoor004", ["x"]= 449.69815063477, ["y"]= -986.46911621094,["z"]= 30.689594268799,["locked"]= true,["txtX"]=450.104,["txtY"]=-986.388,["txtZ"]=31.739}, -- Mission Row Armory [2] = { ["objName"] = "v_ilev_arm_secdoor", ["x"]= 452.61877441406, ["y"]= -982.7021484375,["z"]= 30.689598083496,["locked"]= true,["txtX"]=453.079,["txtY"]=-982.600,["txtZ"]=31.739}, -- Mission Row Captain Office [3] = { ["objName"] = "v_ilev_ph_gendoor002", ["x"]= 447.23818969727, ["y"]= -980.63006591797,["z"]= 30.689598083496,["locked"]= true,["txtX"]=447.200,["txtY"]=-980.010,["txtZ"]=31.739}, -- Mission Row To downstairs right [4] = { ["objName"] = "v_ilev_ph_gendoor005", ["x"]= 443.97, ["y"]= -989.033,["z"]= 30.6896,["locked"]= true,["txtX"]=444.020,["txtY"]=-989.445,["txtZ"]=31.739}, -- Mission Row To downstairs left [5] = { ["objName"] = "v_ilev_ph_gendoor005", ["x"]= 445.37, ["y"]= -988.705,["z"]= 30.6896,["locked"]= true,["txtX"]=445.350,["txtY"]=-989.445,["txtZ"]=31.739}, -- Mission Row Main cells [6] = { ["objName"] = "v_ilev_ph_cellgate", ["x"]= 464.0, ["y"]= -992.265,["z"]= 24.9149,["locked"]= true,["txtX"]=463.465,["txtY"]=-992.664,["txtZ"]=25.064}, -- Mission Row Cell 1 [7] = { ["objName"] = "v_ilev_ph_cellgate", ["x"]= 462.381, ["y"]= -993.651,["z"]= 24.9149,["locked"]= true,["txtX"]=461.806,["txtY"]=-993.308,["txtZ"]=25.064}, -- Mission Row Cell 2 [8] = { ["objName"] = "v_ilev_ph_cellgate", ["x"]= 462.331, ["y"]= -998.152,["z"]= 24.9149,["locked"]= true,["txtX"]=461.806,["txtY"]=-998.800,["txtZ"]=25.064}, -- Mission Row Cell 3 [9] = { ["objName"] = "v_ilev_ph_cellgate", ["x"]= 462.704, ["y"]= -1001.92,["z"]= 24.9149,["locked"]= true,["txtX"]=461.806,["txtY"]=-1002.450,["txtZ"]=25.064}, -- Mission Row Backdoor in [10] = { ["objName"] = "v_ilev_gtdoor", ["x"]= 464.126, ["y"]= -1002.78,["z"]= 24.9149,["locked"]= true,["txtX"]=464.100,["txtY"]=-1003.538,["txtZ"]=26.064}, -- Mission Row Backdoor out [11] = { ["objName"] = "v_ilev_gtdoor", ["x"]= 464.18, ["y"]= -1004.31,["z"]= 24.9152,["locked"]= true,["txtX"]=464.100,["txtY"]=-1003.538,["txtZ"]=26.064}, -- Mission Row Rooftop In [12] = { ["objName"] = "v_ilev_gtdoor02", ["x"]= 465.467, ["y"]= -983.446,["z"]= 43.6918,["locked"]= true,["txtX"]=464.361,["txtY"]=-984.050,["txtZ"]=44.834}, -- Mission Row Rooftop Out [13] = { ["objName"] = "v_ilev_gtdoor02", ["x"]= 462.979, ["y"]= -984.163,["z"]= 43.6919,["locked"]= true,["txtX"]=464.361,["txtY"]=-984.050,["txtZ"]=44.834}, }
Weapon.PrettyName = "Pistol" Weapon.WeaponID = "weapon_pistol" Weapon.WeaponType = WEAPON_SECONDARY Weapon.DamageMultiplier = 2
local range = 5000.0 Citizen.CreateThread(function() SetGarbageTrucks(0.3) SetRandomBoats(0) SetRandomTrains(0) while true do SetPedDensityMultiplierThisFrame(0.5) SetVehicleDensityMultiplierThisFrame(0.0) SetScenarioPedDensityMultiplierThisFrame(0.0, 0.0) SetSomeVehicleDensityMultiplierThisFrame(0.5) SetParkedVehicleDensityMultiplierThisFrame(0.5) SetRandomVehicleDensityMultiplierThisFrame(0.5) Citizen.Wait(0) end end) --[[ Citizen.CreateThread(function() while true do local ply = PlayerPedId(0.5) local pos = GetEntityCoords(ply) for i = 1, 15 do EnableDispatchService(i, false) end RemoveVehiclesFromGeneratorsInArea(pos.x - range, pos.y - range, pos.z - range, pos.x + range, pos.y + range, pos.z + range); Citizen.Wait(1000) end end) ]]
Citizen.CreateThread(function() -- lafa2k motel RequestIpl("lafa2k_interior_v_motel_mp_milo_1") RequestIpl("lafa2k_interior_v_motel_mp_milo_2") RequestIpl("lafa2k_interior_v_motel_mp_milo_3") RequestIpl("lafa2k_interior_v_motel_mp_milo_4") RequestIpl("lafa2k_interior_v_motel_mp_milo_5") RequestIpl("lafa2k_interior_v_motel_mp_milo_6") RequestIpl("lafa2k_interior_v_motel_mp_milo_7") RequestIpl("lafa2k_interior_v_motel_mp_milo_8") RequestIpl("lafa2k_interior_v_motel_mp_milo_9") RequestIpl("lafa2k_interior_v_motel_mp_milo_10") RequestIpl("lafa2k_interior_v_motel_mp_milo_11") RequestIpl("lafa2k_interior_v_motel_mp_milo_12") RequestIpl("lafa2k_interior_v_motel_mp_milo_13") RequestIpl("lafa2k_interior_v_motel_mp_milo_14") RequestIpl("lafa2k_interior_v_motel_mp_milo_15") RequestIpl("lafa2k_interior_v_motel_mp_milo_16") RequestIpl("lafa2k_interior_v_motel_mp_milo_17") RequestIpl("lafa2k_interior_v_motel_mp_milo_18") RequestIpl("lafa2k_interior_v_motel_mp_milo_19") RequestIpl("lafa2k_interior_v_motel_mp_milo_20") RequestIpl("lafa2k_interior_v_motel_mp_milo_21") RequestIpl("lafa2k_interior_v_motel_mp_milo_22") RequestIpl("lafa2k_interior_v_motel_mp_milo_23") RequestIpl("lafa2k_interior_v_motel_mp_milo_24") RequestIpl("lafa2k_interior_v_motel_mp_milo_25") RequestIpl("lafa2k_interior_v_motel_mp_milo_26") RequestIpl("lafa2k_interior_v_motel_mp_milo_27") RequestIpl("lafa2k_interior_v_motel_mp_milo_28") RequestIpl("lafa2k_interior_v_motel_mp_milo_29") RequestIpl("lafa2k_interior_v_motel_mp_milo_30") RequestIpl("lafa2k_interior_v_motel_mp_milo_31") RequestIpl("lafa2k_interior_v_motel_mp_milo_32") RequestIpl("lafa2k_interior_v_motel_mp_milo_33") RequestIpl("lafa2k_interior_v_motel_mp_milo_34") RequestIpl("lafa2k_interior_v_motel_mp_milo_35") RequestIpl("lafa2k_interior_v_motel_mp_milo_36") RequestIpl("lafa2k_interior_v_motel_mp_milo_37") RequestIpl("lafa2k_interior_v_motel_mp_milo_38") end)
-- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!! -- This file is automaticly generated. Don't edit manualy! -- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!! ---@class C_LegendaryCrafting C_LegendaryCrafting = {} ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.CloseRuneforgeInteraction) function C_LegendaryCrafting.CloseRuneforgeInteraction() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.CraftRuneforgeLegendary) ---@param description RuneforgeLegendaryCraftDescription function C_LegendaryCrafting.CraftRuneforgeLegendary(description) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgeItemPreviewInfo) ---@param baseItem table ---@param runeforgePowerID number ---@param modifiers table ---@return RuneforgeItemPreviewInfo @info function C_LegendaryCrafting.GetRuneforgeItemPreviewInfo(baseItem, runeforgePowerID, modifiers) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgeLegendaryComponentInfo) ---@param runeforgeLegendary table ---@return RuneforgeLegendaryComponentInfo @componentInfo function C_LegendaryCrafting.GetRuneforgeLegendaryComponentInfo(runeforgeLegendary) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgeLegendaryCost) ---@param baseItem table ---@return table @cost function C_LegendaryCrafting.GetRuneforgeLegendaryCost(baseItem) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgeLegendaryCraftSpellID) ---@return number @spellID function C_LegendaryCrafting.GetRuneforgeLegendaryCraftSpellID() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgeLegendaryCurrencies) ---@return table @currencies function C_LegendaryCrafting.GetRuneforgeLegendaryCurrencies() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgeLegendaryUpgradeCost) ---@param runeforgeLegendary table ---@param upgradeItem table ---@return table @cost function C_LegendaryCrafting.GetRuneforgeLegendaryUpgradeCost(runeforgeLegendary, upgradeItem) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgeModifierInfo) ---@param baseItem table ---@param powerID number ---@param addedModifierIndex number ---@param modifiers table ---@return string, string @name, description function C_LegendaryCrafting.GetRuneforgeModifierInfo(baseItem, powerID, addedModifierIndex, modifiers) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgeModifiers) ---@return table @modifiedReagentItemIDs function C_LegendaryCrafting.GetRuneforgeModifiers() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgePowerInfo) ---@param runeforgePowerID number ---@return RuneforgePower @power function C_LegendaryCrafting.GetRuneforgePowerInfo(runeforgePowerID) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgePowerSlots) ---@param runeforgePowerID number ---@return table @slotNames function C_LegendaryCrafting.GetRuneforgePowerSlots(runeforgePowerID) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgePowers) ---@param baseItem table ---@return table @runeforgePowerIDs function C_LegendaryCrafting.GetRuneforgePowers(baseItem) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.GetRuneforgePowersByClassAndSpec) ---@param classID number ---@param specID number ---@return table @runeforgePowerIDs function C_LegendaryCrafting.GetRuneforgePowersByClassAndSpec(classID, specID) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.IsRuneforgeLegendary) ---@param item table ---@return boolean @isRuneforgeLegendary function C_LegendaryCrafting.IsRuneforgeLegendary(item) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.IsRuneforgeLegendaryMaxLevel) ---@param runeforgeLegendary table ---@return boolean @isMaxLevel function C_LegendaryCrafting.IsRuneforgeLegendaryMaxLevel(runeforgeLegendary) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.IsUpgradeItemValidForRuneforgeLegendary) ---@param runeforgeLegendary table ---@param upgradeItem table ---@return boolean @isValid function C_LegendaryCrafting.IsUpgradeItemValidForRuneforgeLegendary(runeforgeLegendary, upgradeItem) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.IsValidRuneforgeBaseItem) ---@param baseItem table ---@return boolean @isValid function C_LegendaryCrafting.IsValidRuneforgeBaseItem(baseItem) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.MakeRuneforgeCraftDescription) ---@param baseItem table ---@param runeforgePowerID number ---@param modifiers table ---@return RuneforgeLegendaryCraftDescription @description function C_LegendaryCrafting.MakeRuneforgeCraftDescription(baseItem, runeforgePowerID, modifiers) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_LegendaryCrafting.UpgradeRuneforgeLegendary) ---@param runeforgeLegendary table ---@param upgradeItem table function C_LegendaryCrafting.UpgradeRuneforgeLegendary(runeforgeLegendary, upgradeItem) end
-- P26 - [实例:换零钱方式的统计] function count_change(amount) function cc(amount, kinds_of_coins) if amount == 0 then return 1 elseif amount < 0 or kinds_of_coins == 0 then return 0 else return cc(amount, kinds_of_coins - 1) + cc(amount - first_denomination(kinds_of_coins), kinds_of_coins) end end function first_denomination(kinds_of_coins) if kinds_of_coins == 1 then return 1 elseif kinds_of_coins == 2 then return 5 elseif kinds_of_coins == 3 then return 10 elseif kinds_of_coins == 4 then return 25 elseif kinds_of_coins == 5 then return 50 end end return cc(amount, 5) end print(count_change(100))
--New includeFile("custom_content/building/mustafar/particle/must_floating_embers.lua") includeFile("custom_content/building/mustafar/particle/must_jedi_rock_throw_01.lua") includeFile("custom_content/building/mustafar/particle/must_jedi_rock_throw_02.lua") includeFile("custom_content/building/mustafar/particle/must_jedi_rock_throw_03.lua") includeFile("custom_content/building/mustafar/particle/must_jedi_rock_throw_10.lua") includeFile("custom_content/building/mustafar/particle/must_lava_bubble.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_01.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_15x45.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_15x80.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_20x37.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_20x45.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_20x56.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_20x75.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_20x175.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_25x50.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_25x65.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_25x111.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_25x220.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_30x40.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_30x140.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_40x114.lua") includeFile("custom_content/building/mustafar/particle/must_lava_falls_ribbon_40x220.lua") includeFile("custom_content/building/mustafar/particle/must_lava_fire.lua") includeFile("custom_content/building/mustafar/particle/must_lava_flare.lua") includeFile("custom_content/building/mustafar/particle/must_lava_flare_interior.lua") includeFile("custom_content/building/mustafar/particle/must_lightning.lua") includeFile("custom_content/building/mustafar/particle/must_lightning_02.lua") includeFile("custom_content/building/mustafar/particle/must_lightning_03.lua") includeFile("custom_content/building/mustafar/particle/must_smoke_plume_01.lua") includeFile("custom_content/building/mustafar/particle/must_smoke_plume_02.lua") includeFile("custom_content/building/mustafar/particle/must_steam_clouds.lua") includeFile("custom_content/building/mustafar/particle/must_steam_geyser.lua") includeFile("custom_content/building/mustafar/particle/must_steam_geyser_med.lua") includeFile("custom_content/building/mustafar/particle/must_steam_geyser_med_yellow.lua") includeFile("custom_content/building/mustafar/particle/must_steam_geyser_small_yellow.lua") includeFile("custom_content/building/mustafar/particle/must_steam_geyser_sml.lua") includeFile("custom_content/building/mustafar/particle/must_steam_geyser_yellow.lua")
--[[ /////// ////////////////// /////// PROJECT: MTA iLife - German Fun Reallife Gamemode /////// VERSION: 1.7.2 /////// DEVELOPERS: See DEVELOPERS.md in the top folder /////// LICENSE: See LICENSE.md in the top folder /////// ///////////////// ]] CLSPD = {} function CLSPD:constructor() addEvent("onPlayerGrabRequest", true) addEventHandler("onPlayerGrabRequest", getRootElement(), function(sPlayername) local uPlayer = client; local uPlayer2; if(getPlayerFromName(sPlayername)) then uPlayer2 = getPlayerFromName(sPlayername) if(isPedInVehicle(uPlayer)) then local veh = uPlayer:getOccupiedVehicle(); if(uPlayer:getFaction():getType() == 1) then if(uPlayer2.Crack) and (uPlayer2.CrackCounter > 1) then local x, y, z = uPlayer:getPosition() local x2, y2, z2 = uPlayer2:getPosition() if(getDistanceBetweenPoints3D(x, y, z, x2, y2, z2) < 10) then local seat = getVehicleFreeSeat(veh) if(seat) then warpPedIntoVehicle(uPlayer2, veh, seat) uPlayer:showInfoBox("sucess", "Der Spieler wurde in dein Auto gezogen!") uPlayer2:showInfoBox("info", "Du wurdest in ein Auto gezogen!") uPlayer2.CrackCounter = 0; else uPlayer:showInfoBox("error", "In deinem Fahrzeug ist kein Platz mehr!") end else uPlayer:showInfoBox("error", "Der Spieler ist zu weit weg!") end else uPlayer:showInfoBox("error", "Der Spieler ist nicht getazert!") end end end end end) self.DachMarkerIn = createMarker(1564.9041748047, -1666.6864013672, 28.395606994629, "corona", 1, 255, 255, 255, 255); -- Davor: 1564.8591308594, -1664.8547363281, 28.395606994629 addEventHandler("onMarkerHit", self.DachMarkerIn, function(hitElement, matching) if (matching) then if (getElementType(hitElement) == "player") then if (not(isPedInVehicle(hitElement))) then if (hitElement:getFaction():getType() == 1) then hitElement:fadeInPosition(1556.2912597656, -2935.939453125, 219.09289550781, 20141, 10) hitElement:setRotation(0,0,0) else hitElement:showInfoBox("error", "Es ist abgeschlossen!") end end end end end ) self.DachMarkerOut = createMarker(1556.0463867188, -2933.8024902344, 219.09289550781, "corona", 1, 255, 255, 255, 255); setElementInterior(self.DachMarkerOut, 10) setElementDimension(self.DachMarkerOut, 20141) -- Davor: 1556.2912597656, -2935.939453125, 219.09289550781 addEventHandler("onMarkerHit", self.DachMarkerOut, function(hitElement, matching) if (matching) then if (getElementType(hitElement) == "player") then if (not(isPedInVehicle(hitElement))) then if (hitElement:getFaction():getType() == 1) then hitElement:fadeInPosition(1564.8591308594, -1664.8547363281, 28.395606994629, 0, 0) else hitElement:showInfoBox("error", "Es ist abgeschlossen!") end end end end end ) self.GaragenMarkerIn = createMarker(1552.1259765625, -2954.587890625, 219.09289550781, "corona", 1, 255, 255, 255, 255, getRootElement()) setElementInterior(self.GaragenMarkerIn, 10, 1552.1259765625, -2954.587890625, 219.09289550781) setElementDimension(self.GaragenMarkerIn, 20141) addEventHandler("onMarkerHit", self.GaragenMarkerIn, function(hitElement, matching) if (matching) then if (getElementType(hitElement) == "player") then if (not(isPedInVehicle(hitElement))) then if (hitElement:getFaction():getType() == 1) then hitElement:fadeInPosition(1568.6787109375, -1691.57421875, 5.890625, 0, 0) hitElement:setRotation(0,0,0) else hitElement:showInfoBox("error", "Es ist abgeschlossen!") end end end end end ) self.GaragenMarkerOut = createMarker(1568.630859375,-1689.9716796875,6.21875, "corona", 1, 255, 255, 255, 255,getRootElement()) addEventHandler("onMarkerHit", self.GaragenMarkerOut, function(hitElement, matching) if (matching) then if (getElementType(hitElement) == "player") then if (not(isPedInVehicle(hitElement))) then hitElement:fadeInPosition(1553.8515625, -2954.8369140625, 219.09289550781, 20141, 10) hitElement:setRotation(0,0,180) end end end end ) self.PrisonMarkerIn = createMarker(3776.0673828125, -1599.67578125, 120.96875, "corona", 1, 255, 255, 255, 255,getRootElement()) setElementInterior(self.PrisonMarkerIn, 1, 3776.0673828125, -1599.67578125, 120.96875) setElementDimension(self.PrisonMarkerIn, 0) addEventHandler("onMarkerHit", self.PrisonMarkerIn, function(hitElement, matching) if (matching) then if (getElementType(hitElement) == "player") then if (not(isPedInVehicle(hitElement))) then if (hitElement:getJailtime() <= 0) then hitElement:fadeInPosition(1557.9619140625, -2933.9638671875, 219.09289550781, 20141, 10) hitElement:setRotation(0,0,90) else hitElement:showInfoBox("warning", "Du musst deine Strafe absitzen!") end end end end end ) self.PrisonMarkerOut = createMarker(1559.966796875, -2934.1015625, 218.40992736816, "corona", 1, 255, 255, 255, 255, getRootElement()) setElementInterior(self.PrisonMarkerOut, 10, 1559.966796875, -2934.1015625, 218.40992736816) setElementDimension(self.PrisonMarkerOut, 20141) addEventHandler("onMarkerHit", self.PrisonMarkerOut, function(hitElement, matching) if (matching) then if (getElementType(hitElement) == "player") then if (not(isPedInVehicle(hitElement))) then hitElement:fadeInPosition(3771.5751953125,-1599.5302734375,120.96875, 0, 1) hitElement:setRotation(0,0,90) end end end end ) self.trainingMarkerOut = createMarker(1540.5018310547, -1670.7862548828, 1912.5562744141, "corona", 1, 0, 255, 0, 255); setElementInterior(self.trainingMarkerOut, 2); setElementDimension(self.trainingMarkerOut, 1337); -- Davor: 1540.4644775391, -1668.9951171875, 1912.5562744141 self.trainingMarkerIn = createMarker(1524.4831542969, -1677.8615722656, 6.21875, "corona", 1, 0, 255, 0, 255); -- Davor: 1526.3999023438, -1677.8438720703, 5.890625 addEventHandler("onMarkerHit", self.trainingMarkerIn, function(uElement, dim) if(dim) then uElement:fadeInPosition(1540.4644775391, -1668.9951171875, 1912.5562744141, 1337, 2); end end) addEventHandler("onMarkerHit", self.trainingMarkerOut, function(uElement, dim) if(dim) then uElement:fadeInPosition(1526.3999023438, -1677.8438720703, 5.890625, 0, 0); end end) self.DutyPickup = createPickup(1564.1484375, -2941.783203125, 219.09289550781, 3, 1275, 100) setElementInterior(self.DutyPickup, 10) setElementDimension(self.DutyPickup, 20141) addEventHandler("onPickupHit", self.DutyPickup, function(thePlayer) if (thePlayer:getFaction():getID() == 1) then if (thePlayer:isDuty()) then thePlayer:setDuty(false) thePlayer:setSkin(thePlayer:getSkin()) thePlayer:showInfoBox("info", "Du hast deinen Dienst beendet!") thePlayer:resetWeapons() else thePlayer:setDuty(true) thePlayer:setSkin(Factions[1]:getRankSkin(thePlayer:getRank()), true) thePlayer:showInfoBox("info", "Du bist nun in Dienst!") thePlayer:getInventory():addItem(Items[273], 1); end else thePlayer:showInfoBox("error", "Du bist kein Beamter beim LSPD!") end end ) self.m_uAsservatenPickup = createMarker(1528.4302978516, -2950.0439453125, 220.49133300781, "corona", 1.0, 0, 255, 0, 200); self.m_uAsservatenPickup:setInterior(10) self.m_uAsservatenPickup:setDimension(20141); addEventHandler("onMarkerHit", self.m_uAsservatenPickup, function(hitElement, dim) if(dim) and(hitElement) and (getElementType(hitElement) == "player") then if(hitElement:getFaction():getType() == 1) then -- Gute Fraktion cAsservatenkammer:getInstance():sendPlayerInfo(hitElement) end end end) addEventHandler("onMarkerLeave", self.m_uAsservatenPickup, function(hitElement, dim) if(dim) and(hitElement) and (getElementType(hitElement) == "player") then if(hitElement:getFaction():getType() == 1) then -- Gute Fraktion cAsservatenkammer:getInstance():unsendPlayerInfo(hitElement) end end end) self.WeaponPickup = createPickup(1542.3359375, -2950.251953125, 220.49133300781, 3, 1242, 100) setElementInterior(self.WeaponPickup, 10) setElementDimension(self.WeaponPickup, 20141) addEventHandler("onPickupHit", self.WeaponPickup, function(thePlayer) if (thePlayer:getFaction():getID() == 1) then if (thePlayer:isDuty()) then thePlayer:resetWeapons() setElementHealth(thePlayer, 100); if (thePlayer:getRank() == 1) then thePlayer:addWeapon(22, 150, false) -- 9mm setPedStat(thePlayer,69,500) -- 9mm Skill auf 500 da sonst Dual-9mm end if (thePlayer:getRank() == 2) then thePlayer:addWeapon(23, 30, false) -- Tazer thePlayer:addWeapon(25, 150, false) -- Shotgun thePlayer:addWeapon(29, 540, false) -- MP5 end if (thePlayer:getRank() == 3) then thePlayer:addWeapon(23, 30, false) -- Tazer thePlayer:addWeapon(31, 540, false) -- M4 thePlayer:addWeapon(25, 150, false) -- Shotgun thePlayer:addWeapon(29, 540, false) -- MP5 thePlayer:addWeapon(17, 1, false) -- Tear Gas end if (thePlayer:getRank() == 4) then thePlayer:addWeapon(23, 30, false) -- Tazer thePlayer:addWeapon(31, 540, false) -- M4 thePlayer:addWeapon(25, 150, false) -- Shotgun thePlayer:addWeapon(17, 3, false) -- Tear Gas thePlayer:addWeapon(29, 540, false) -- MP5 thePlayer:addWeapon(34, 10, false) -- Sniper end if (thePlayer:getRank() > 4) then thePlayer:addWeapon(23, 30, false) -- Tazer thePlayer:addWeapon(31, 540, false) -- M4 thePlayer:addWeapon(17, 3, false) -- Tear Gas thePlayer:addWeapon(25, 150, false) -- Shotgun thePlayer:addWeapon(34, 10, false) -- Sniper thePlayer:addWeapon(29, 540, false) -- MP5 end thePlayer:addWeapon(3, 1, false) thePlayer:showInfoBox("info", "Du bist nun ausgerüstet!") setPedArmor(thePlayer, 100) else thePlayer:showInfoBox("error", "Du bist nicht im Dienst!") end else thePlayer:showInfoBox("error", "Du bist kein Beamter beim LSPD!") end end ) self.Jailmarker1 = createColSphere(1568.7600097656, -1694.1672363281, 5.890625, 5) self.Jailmarker2 = createColSphere(1564.474609375, -1694.451171875, 4.890625, 5) local function einknasten(hitElement, matching) jailFunction(hitElement, matching, 1) end addEventHandler("onColShapeHit", self.Jailmarker1, einknasten) addEventHandler("onColShapeHit", self.Jailmarker2, einknasten) --[[ self.GarageGate1 = createObject(988, 1589.69995, -1637.76001, 13.1, 0, 0, 181.5) self.GarageGate2 = createObject(988, 1584.19995, -1637.81006, 13.1, 0, 0, 179.747) self.GarageShapeSphere = createColSphere(1589.19995, -1637.81006, 13.1, 10) addEventHandler("onColShapeHit", self.GarageShapeSphere, function(hitElement, matching) if ((getElementType(hitElement) == "player") and (matching)) then if (hitElement:getFaction():getType() == 1) then local x,y,z = getElementPosition(self.GarageGate1) local x2,y2,z2 = getElementPosition(self.GarageGate2) if (math.floor(z) == (13)) then moveObject(self.GarageGate1, 4000, x,y,z-5) moveObject(self.GarageGate2, 4000, x2,y2,z-5) end end end end ) addEventHandler("onColShapeLeave", self.GarageShapeSphere, function(hitElement, matching) if ((getElementType(hitElement) == "player") and (matching)) then if (hitElement:getFaction():getType() == 1) then local x,y,z = getElementPosition(self.GarageGate1) local x2,y2,z2 = getElementPosition(self.GarageGate2) if (math.floor(z) == (13)-5) then for k,v in ipairs(getElementsWithinColShape (source, "player")) do if (v:getFaction():getType() == 1) then if (v ~= hitElement) then return false end end end moveObject(self.GarageGate1, 4000, x,y,13) moveObject(self.GarageGate2, 4000, x2,y2,13) end end end end ) setTimer( function() local x,y,z = getElementPosition(self.GarageGate1) local x2,y2,z2 = getElementPosition(self.GarageGate2) if (math.floor(z) == (13)-5) then for k,v in ipairs(getElementsWithinColShape (self.GarageShapeSphere, "player")) do if (v:getFaction():getType() == 1) then return false end end moveObject(self.GarageGate1, 4000, x,y,13) moveObject(self.GarageGate2, 4000, x2,y2,13) end end, 20000, 0 ) ]] self.Jailped = createPed(281,1561.38916, -2954.85669, 219.10001, 90, false) setElementInterior(self.Jailped, 10) setElementDimension(self.Jailped, 20141) addEventHandler("onElementClicked", self.Jailped, function(btn, state, thePlayer) if ((btn == "left") and (state == "down")) then outputChatBox("Officer: Klicke mich mit Rechtsklick an um dich zu stellen! (8 Minuten für jedes Wanted)", thePlayer, 255,255,255) end if ((btn == "right") and (state == "down")) then if thePlayer:getWanteds() > 0 then toggleAllControls (thePlayer, false) thePlayer:showInfoBox("info","Du wirst in 10 Sekunden eingesperrt!") setTimer( function() if thePlayer:getWanteds() > 0 then Factions[1]:addDepotMoney(thePlayer:getWanteds()*100) toggleAllControls (thePlayer, true) for k2,v2 in ipairs( getElementsByType("player")) do if (getElementData(v2, "online")) and (v2:getFaction():getType() == 1) then if (thePlayer:getFaction():getType() == 2) then outputChatBox("Der Spieler "..thePlayer:getName().." hat sich gestellt und wurde für "..tostring(thePlayer:getWanteds()*4).." Minuten eingesperrt!", v2, 0, 255, 0) else outputChatBox("Der Spieler "..thePlayer:getName().." hat sich gestellt und wurde für "..tostring(thePlayer:getWanteds()*8).." Minuten eingesperrt!", v2, 0, 255, 0) end end end thePlayer:jail(thePlayer:getWanteds()*8, true, 1) end end, 10000, 1 ) else outputChatBox("Officer: Sie werden nicht gesucht!", thePlayer, 255,255,255) end end end ) setElementData(self.Jailped, "EastereggPed", true) setElementFrozen(self.Jailped, true) setWeaponProperty(23, "poor", "damage", 10) setWeaponProperty(23, "poor", "maximum_clip_ammo", 1) setWeaponProperty(23, "pro", "damage", 10) setWeaponProperty(23, "pro", "maximum_clip_ammo", 1) addCommandHandler("m", function(thePlayer, cmd, ...) if not (getElementData(thePlayer, "online")) then return false end if (thePlayer:getFaction():getType() == 1) then if (getPedOccupiedVehicle(thePlayer) and getElementData(getPedOccupiedVehicle(thePlayer), "Fraktion") and Factions[getElementData(getPedOccupiedVehicle(thePlayer), "Fraktion")]:getType() == 1 and thePlayer:isDuty()) then local x,y,z = thePlayer:getPosition() local sphere = createColSphere(x, y,z, 70) local parametersTable = {...} local stringWithAllParameters = table.concat( parametersTable, " " ) for k,v in ipairs(getElementsWithinColShape(sphere, "player")) do if ((getElementDimension(v) == getElementDimension(thePlayer)) and (getElementInterior(v) == getElementInterior(thePlayer))) then outputChatBox("[Officer]"..getPlayerName(thePlayer)..": "..stringWithAllParameters, v, 255, 255, 20) end end destroyElement(sphere) end end end ) setModelHandling(596, "maxVelocity", getOriginalHandling(596)["maxVelocity"]*1.15) setModelHandling(599, "maxVelocity", getOriginalHandling(599)["maxVelocity"]*1.15) setModelHandling(523, "maxVelocity", getOriginalHandling(523)["maxVelocity"]*1.15) end function CLSPD:destructor() end LSPD = new(CLSPD)
local tortusBase = require "tortus.tortusBase" local navModule = {} ---Returns the turtle's position ---@return table function navModule.getPos() tortusBase.updatePosition() return tortusBase.cache.position.handle end ---Returns the turtle's cardinal direction ---@return string function navModule.getFacing() return tortusBase.cache.direction end -------------------------------------------------- --[[ internal logic for most movement functions ]] local function internalMovement(count, direction, reverse) count = count or 1 local is_success local blocksMoved = count if count > tortusBase.turtle.getFuelLevel() then return false, 0 end tortusBase.updatePosition() for i = 1, count do is_success = tortusBase.turtle[direction]() if not is_success then blocksMoved = i - 1 break else tortusBase.cache.lastCardinalMovement = tortusBase.cache.direction tortusBase.cache.movementLog[#tortusBase.cache.movementLog.handle + 1] = { move = direction, reverse = reverse } end end return is_success, blocksMoved end -- ---Moves the turtle forward. ---@param count number ---@return boolean ---@return number function navModule.forward(count) return internalMovement(count, "forward", "back") end ---Moves the turtle backward. ---@param count number ---@return boolean ---@return number function navModule.back(count) return internalMovement(count, "back", "forward") end ---Moves the turtle upward. ---@param count number ---@return boolean ---@return number function navModule.up(count) internalMovement(count, "up", "down") end ---Moves the turtle downward. ---@param count number ---@return boolean ---@return number function navModule.down(count) internalMovement(count, "down", "up") end ---Turns the turtle left once. function navModule.turnLeft() tortusBase.cache.direction = tortusBase.directionLookup[tortusBase.cache.direction].left tortusBase.cache.movementLog[#tortusBase.cache.movementLog.handle + 1] = { move = "turnLeft", reverse = "turnRight" } return tortusBase.turtle.turnLeft() end ---Turns the turtle right once. function navModule.turnRight() tortusBase.cache.direction = tortusBase.directionLookup[tortusBase.cache.direction].right tortusBase.cache.movementLog[#tortusBase.cache.movementLog.handle + 1] = { move = "turnRight", reverse = "turnLeft" } return tortusBase.turtle.turnRight() end ---Turns the turtle the opposite direction. function navModule.reverse() tortusBase.cache.direction = tortusBase.directionLookup[tortusBase.cache.direction].back tortusBase.cache.movementLog[#tortusBase.cache.movementLog.handle + 1] = { move = "turnRight", reverse = "turnLeft" } tortusBase.cache.movementLog[#tortusBase.cache.movementLog.handle + 1] = { move = "turnRight", reverse = "turnLeft" } tortusBase.turtle.turnRight() return tortusBase.turtle.turnRight() end -------------------------------------------------- --[[ internal logic for both strafe functions ]] local function internalStrafe(firstDir, secDir, count) firstDir() local is_success, blocksMoved = navModule.forward(count) secDir() return is_success, blocksMoved end -- ---Moves the turtle to its left ---@param count number function navModule.strafeLeft(count) return internalStrafe(navModule.turnLeft, navModule.turnRight, count) end ---Moves the turtle to its right ---@param count number function navModule.strafeRight(count) return internalStrafe(navModule.turnRight, navModule.turnLeft, count) end ---Undoes any movements made previously by the turtle. ---@param count number ---@return boolean ---@return number ---@return string|nil function navModule.undoMovement(count) local reduceRotations = 0 local lastRotation = "none" local movementLog = {} count = count or 1 if count > #tortusBase.cache.movementLog.handle then count = #tortusBase.cache.movementLog.handle end for i = 1, count do movementLog[i] = tortusBase.cache.movementLog[i].reverse end local fuelCheck = 0 for i = 1, count do if movementLog[i] ~= "turnLeft" and movementLog[i] ~= "turnRight" then fuelCheck = fuelCheck + 1 end end if fuelCheck > tortusBase.turtle.getFuelLevel() then return false, 0 end for i = 1, count do local movement = table.remove(movementLog, #movementLog) if reduceRotations > 0 and (movement ~= lastRotation or i == count) then if movement == lastRotation then reduceRotations = reduceRotations + 1 end local totalRots = reduceRotations % 4 if totalRots == 3 then totalRots = 1 lastRotation = lastRotation == "turnLeft" and "turnRight" or "turnLeft" end if totalRots > 0 then for _ = 1, totalRots do navModule[lastRotation]() end end end if (movement == "turnLeft" or movement == "turnRight") then if i < count then if lastRotation~=movement then lastRotation = movement reduceRotations = 1 else reduceRotations = reduceRotations + 1 end elseif reduceRotations == 0 then navModule[movement]() end else local is_Success = navModule[movement]() reduceRotations = 0 lastRotation = "none" if not is_Success then table.insert(movementLog, 1, movement) tortusBase.cache.movementLog = movementLog return false, i, movement end end end tortusBase.cache.movementLog = movementLog return true, count end ---Undoes all movement recorded by the turtle. ---@return boolean ---@return number ---@return string|nil function navModule.undoAllMovement() return navModule.undoMovement(#tortusBase.cache.movementLog.handle) end ---Clears the turtle's movement history. function navModule.clearLog() tortusBase.cache.movementLog = {} end for k, v in next, navModule do tortusBase.library[k] = v end return navModule
-- _ _ _ _ -- /\ | | | | | | | | -- / \ | |_| | __ _ ___ ___| |__ __ _| |_ -- / /\ \| __| |/ _` / __| / __| '_ \ / _` | __| -- / ____ \ |_| | (_| \__ \ | (__| | | | (_| | |_ -- /_/ \_\__|_|\__,_|___/ \___|_| |_|\__,_|\__| -- -- -- © 2014 metromod.net do not share or re-distribute -- without permission of its author (Chewgum - [email protected]). -- AddCSLuaFile() if (SERVER) then AddCSLuaFile("atlaschat/cl_init.lua") include("atlaschat/init.lua") else include("atlaschat/cl_init.lua") end if (atlaschat) then if (CLIENT) then MsgC(color_green, "Atlas chat v" .. atlaschat.version:GetString() .. " has loaded!\n") else MsgC(color_green, "Atlas chat has loaded!\n") end else MsgC(color_red, "Atlas chat failed to load!\n") end