repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
dickeyf/darkstar
scripts/globals/spells/cure_ii.lua
26
4497
----------------------------------------- -- Spell: Cure II -- Restores target's HP. -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local divisor = 0; local constant = 0; local basepower = 0; local power = 0; local basecure = 0; local final = 0; local minCure = 60; if (USE_OLD_CURE_FORMULA == true) then power = getCurePowerOld(caster); divisor = 1; constant = 20; if (power > 170) then divisor = 35.6666; constant = 87.62; elseif (power > 110) then divisor = 2; constant = 47.5; end else power = getCurePower(caster); if (power < 70) then divisor = 1; constant = 60; basepower = 40; elseif (power < 125) then divisor = 5.5; constant = 90; basepower = 70; elseif (power < 200) then divisor = 7.5; constant = 100; basepower = 125; elseif (power < 400) then divisor = 10; constant = 110; basepower = 200; elseif (power < 700) then divisor = 20; constant = 130; basepower = 400; else divisor = 999999; constant = 145; basepower = 0; end end if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCure(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); if (caster:hasStatusEffect(EFFECT_AFFLATUS_SOLACE) and target:hasStatusEffect(EFFECT_STONESKIN) == false) then local solaceStoneskin = 0; local equippedBody = caster:getEquipID(SLOT_BODY); if (equippedBody == 11186) then solaceStoneskin = math.floor(final * 0.30); elseif (equippedBody == 11086) then solaceStoneskin = math.floor(final * 0.35); else solaceStoneskin = math.floor(final * 0.25); end target:addStatusEffect(EFFECT_STONESKIN,solaceStoneskin,0,25); end; final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); --Applying server mods.... final = final * CURE_POWER; local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); else if (target:isUndead()) then spell:setMsg(2); local dmg = calculateMagicDamage(minCure,1,caster,spell,target,HEALING_MAGIC_SKILL,MOD_MND,false)*0.5; local resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),HEALING_MAGIC_SKILL,1.0); dmg = dmg*resist; dmg = addBonuses(caster,spell,target,dmg); dmg = adjustForTarget(target,dmg,spell:getElement()); dmg = finalMagicAdjustments(caster,target,spell,dmg); final = dmg; target:delHP(final); target:updateEnmityFromDamage(caster,final); elseif (caster:getObjType() == TYPE_PC) then spell:setMsg(75); else -- e.g. monsters healing themselves. if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCureOld(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); end end return final; end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c90219263.lua
2
1411
--万華鏡-華麗なる分身- function c90219263.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCondition(c90219263.condition) e1:SetTarget(c90219263.target) e1:SetOperation(c90219263.activate) c:RegisterEffect(e1) end function c90219263.cfilter(c) return c:IsFaceup() and c:IsCode(76812113) end function c90219263.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.IsExistingMatchingCard(c90219263.cfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end function c90219263.filter(c,e,tp) return c:IsCode(76812113,12206212) and c:IsCanBeSpecialSummoned(e,0,tp,true,false) end function c90219263.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c90219263.filter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK) end function c90219263.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c90219263.filter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil,e,tp) local tc=g:GetFirst() if tc and Duel.SpecialSummon(tc,0,tp,tp,true,false,POS_FACEUP)~=0 then tc:CompleteProcedure() end end
gpl-2.0
Turttle/darkstar
scripts/globals/weaponskills/one_inch_punch.lua
30
1549
----------------------------------- -- One Inch Punch -- Hand-to-Hand weapon skill -- Skill level: 75 -- Delivers an attack that ignores target's defense. Amount ignored varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Shadow Gorget. -- Aligned with the Shadow Belt. -- Element: None -- Modifiers: VIT:100% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.4; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; --Defense ignored is 0%, 25%, 50% as per http://www.bg-wiki.com/bg/One_Inch_Punch params.ignoresDef = true; params.ignored100 = 0; params.ignored200 = 0.25; params.ignored300 = 0.5; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.vit_wsc = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
fgenesis/Aquaria_experimental
game_scripts/_mods/aquariaeditortutorial/scripts/node_tileedit04.lua
6
1937
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.started = false v.n = 0 v.timer = 999 v.thingsToSay = 20 v.thingSaying = -1 v.timeToSay = 5 function init(me) v.n = getNaija() node_setCursorActivation(me, true) end local function sayNext() if v.thingSaying == 0 then setControlHint("All the backdrop objects in Aquaria are on one of 16 layers.", 0, 0, 0, 16) elseif v.thingSaying == 1 then setControlHint("The first nine layers are mapped to the 1-9 keys on your keyboard.", 0, 0, 0, 16) elseif v.thingSaying == 2 then setControlHint("This starfish is on layer '4'. Press '4' to select that layer and then you can edit it.", 0, 0, 0, 16) end end function update(me, dt) if getStringFlag("editorhint") ~= node_getName(me) then v.started = false return end if v.started then v.timer = v.timer + dt if v.timer > v.timeToSay then v.timer = 0 v.thingSaying = v.thingSaying + 1 sayNext() end end end function activate(me) clearControlHint() v.started = true v.thingSaying = -1 v.timer = 999 setStringFlag("editorhint", node_getName(me)) end
gpl-2.0
fgenesis/Aquaria_experimental
game_scripts/scripts/entities/whelknoshell.lua
6
1151
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end -- ================================================================================================ -- WHELK NO SHELL -- ================================================================================================ dofile("scripts/entities/whelkcommon.lua") function init(me) -- init without shell v.commonInit(me, false) end
gpl-2.0
Turttle/darkstar
scripts/globals/items/bowl_of_sutlac.lua
36
1315
----------------------------------------- -- ID: 5577 -- Item: Bowl of Sutlac -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +8 -- MP +10 -- INT +1 -- MP Recovered while healing +2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5577); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 8); target:addMod(MOD_MP, 10); target:addMod(MOD_INT, 1); target:addMod(MOD_MPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 8); target:delMod(MOD_MP, 10); target:delMod(MOD_INT, 1); target:delMod(MOD_MPHEAL, 2); end;
gpl-3.0
tjschuck/redis
deps/lua/test/sort.lua
889
1494
-- two implementations of a sort function -- this is an example only. Lua has now a built-in function "sort" -- extracted from Programming Pearls, page 110 function qsort(x,l,u,f) if l<u then local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u x[l],x[m]=x[m],x[l] -- swap pivot to first position local t=x[l] -- pivot value m=l local i=l+1 while i<=u do -- invariant: x[l+1..m] < t <= x[m+1..i-1] if f(x[i],t) then m=m+1 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m] end i=i+1 end x[l],x[m]=x[m],x[l] -- swap pivot to a valid place -- x[l+1..m-1] < x[m] <= x[m+1..u] qsort(x,l,m-1,f) qsort(x,m+1,u,f) end end function selectionsort(x,n,f) local i=1 while i<=n do local m,j=i,i+1 while j<=n do if f(x[j],x[m]) then m=j end j=j+1 end x[i],x[m]=x[m],x[i] -- swap x[i] and x[m] i=i+1 end end function show(m,x) io.write(m,"\n\t") local i=1 while x[i] do io.write(x[i]) i=i+1 if x[i] then io.write(",") end end io.write("\n") end function testsorts(x) local n=1 while x[n] do n=n+1 end; n=n-1 -- count elements show("original",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort",x) selectionsort(x,n,function (x,y) return x>y end) show("after reverse selection sort",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort again",x) end -- array to be sorted x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"} testsorts(x)
bsd-3-clause
dickeyf/darkstar
scripts/zones/Lower_Jeuno/npcs/Alrauverat.lua
14
3677
----------------------------------- -- Area: Lower Jeuno -- NPC:Alrauverat -- @pos -101 0 -182 245 ------------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/conquest"); require("scripts/zones/Lower_Jeuno/TextIDs"); local guardnation = OTHER; -- SANDORIA, BASTOK, WINDURST, OTHER(Jeuno). local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Menu1 = getArg1(guardnation,player); local Menu3 = conquestRanking(); local Menu6 = getArg6(player); local Menu7 = player:getCP(); player:startEvent(0x7ffb,Menu1,0,Menu3,0,0,Menu6,Menu7,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); if (player:getNation() == 0) then inventory = SandInv; size = table.getn(SandInv); elseif (player:getNation() == 1) then inventory = BastInv; size = table.getn(BastInv); else inventory = WindInv; size = table.getn(WindInv); end if (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then CPVerify = 1; if (player:getCP() >= inventory[Item + 1]) then CPVerify = 0; end; player:updateEvent(2,CPVerify,inventory[Item + 2]); -- can't equip = 2 ? break; end; end; end; end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then if (player:getFreeSlotsCount() >= 1) then -- Logic to impose limits on exp bands if (option >= 32933 and option <= 32935) then if (checkConquestRing(player) > 0) then player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]); break; else player:setVar("CONQUEST_RING_TIMER",getConquestTally()); end end itemCP = inventory[Item + 1]; player:delCP(itemCP); player:addItem(inventory[Item + 2],1); player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end; break; end; end; end; end;
gpl-3.0
dickeyf/darkstar
scripts/zones/Ghelsba_Outpost/bcnms/holy_crest.lua
1
2233
----------------------------------- -- Area: Ghelsba Outpost -- Name: Holy Crest - DRG flag quest -- @pos -162 -11 78 140 ----------------------------------- package.loaded["scripts/zones/Ghelsba_Outpost/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/pets"); require("scripts/zones/Ghelsba_Outpost/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print(leave code ..leavecode); if (leavecode == 2) then --play end CS. Need time and battle id for record keeping + storage if (player:getQuestStatus(SANDORIA,THE_HOLY_CREST) == QUEST_ACCEPTED) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,1); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print(bc update csid ..csid.. and option ..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid: "..csid.."and option: "..option); if (csid == 0x7d01 and option ~= 0 and player:hasKeyItem(DRAGON_CURSE_REMEDY) == true) then player:addTitle(HEIR_TO_THE_HOLY_CREST); player:delKeyItem(DRAGON_CURSE_REMEDY); player:unlockJob(14); player:messageSpecial(YOU_CAN_NOW_BECOME_A_DRAGOON); player:setVar("TheHolyCrest_Event",0); player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,THE_HOLY_CREST); player:setPetName(PETTYPE_WYVERN,option); end end;
gpl-3.0
eugeneia/snabb
src/lib/protocol/ipv4.lua
2
6581
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local header = require("lib.protocol.header") local ipsum = require("lib.checksum").ipsum local htons, ntohs, htonl, ntohl = lib.htons, lib.ntohs, lib.htonl, lib.ntohl -- TODO: generalize local AF_INET = 2 local INET_ADDRSTRLEN = 16 local ipv4hdr_pseudo_t = ffi.typeof[[ struct { uint8_t src_ip[4]; uint8_t dst_ip[4]; uint8_t ulp_zero; uint8_t ulp_protocol; uint16_t ulp_length; } __attribute__((packed)) ]] local ipv4_addr_t = ffi.typeof("uint8_t[4]") local ipv4_addr_t_size = ffi.sizeof(ipv4_addr_t) local ipv4 = subClass(header) -- Class variables ipv4._name = "ipv4" ipv4._ulp = { class_map = { [6] = "lib.protocol.tcp", [17] = "lib.protocol.udp", [47] = "lib.protocol.gre", [58] = "lib.protocol.icmp.header", [1] = "lib.protocol.icmp.header", }, method = 'protocol' } ipv4:init( { [1] = ffi.typeof[[ struct { uint16_t ihl_v_tos; // ihl:4, version:4, tos(dscp:6 + ecn:2) uint16_t total_length; uint16_t id; uint16_t frag_off; // flags:3, fragmen_offset:13 uint8_t ttl; uint8_t protocol; uint16_t checksum; uint8_t src_ip[4]; uint8_t dst_ip[4]; } __attribute__((packed)) ]], }) -- Class methods function ipv4:new (config) local o = ipv4:superClass().new(self) if not o._recycled then o._ph = ipv4hdr_pseudo_t() end o:header().ihl_v_tos = htons(0x4000) -- v4 o:ihl(o:sizeof() / 4) o:dscp(config.dscp or 0) o:ecn(config.ecn or 0) o:total_length(o:sizeof()) -- default to header only o:id(config.id or 0) o:flags(config.flags or 0) o:frag_off(config.frag_off or 0) o:ttl(config.ttl or 0) o:protocol(config.protocol or 0xff) o:src(config.src) o:dst(config.dst) o:checksum() return o end function ipv4:new_from_mem(mem, size) local o = ipv4:superClass().new_from_mem(self, mem, size) if not o._recycled then o._ph = ipv4hdr_pseudo_t() end return o end function ipv4:pton (p) local in_addr = ffi.new("uint8_t[4]") local result = C.inet_pton(AF_INET, p, in_addr) if result ~= 1 then return false, "malformed IPv4 address: " .. p end return in_addr end function ipv4:ntop (n) local p = ffi.new("char[?]", INET_ADDRSTRLEN) local c_str = C.inet_ntop(AF_INET, n, p, INET_ADDRSTRLEN) return ffi.string(c_str) end function ipv4:pton_cidr (p) local prefix, length = p:match("([^/]*)/([0-9]*)") return ipv4:pton(prefix), assert(tonumber(length), "Invalid length "..length) end -- Instance methods function ipv4:version (v) return lib.bitfield(16, self:header(), 'ihl_v_tos', 0, 4, v) end function ipv4:ihl (ihl) return lib.bitfield(16, self:header(), 'ihl_v_tos', 4, 4, ihl) end function ipv4:dscp (dscp) return lib.bitfield(16, self:header(), 'ihl_v_tos', 8, 6, dscp) end function ipv4:ecn (ecn) return lib.bitfield(16, self:header(), 'ihl_v_tos', 14, 2, ecn) end function ipv4:total_length (length) if length ~= nil then self:header().total_length = htons(length) else return(ntohs(self:header().total_length)) end end function ipv4:id (id) if id ~= nil then self:header().id = htons(id) else return(ntohs(self:header().id)) end end function ipv4:flags (flags) return lib.bitfield(16, self:header(), 'frag_off', 0, 3, flags) end function ipv4:frag_off (frag_off) return lib.bitfield(16, self:header(), 'frag_off', 3, 13, frag_off) end function ipv4:ttl (ttl) if ttl ~= nil then self:header().ttl = ttl else return self:header().ttl end end function ipv4:protocol (protocol) if protocol ~= nil then self:header().protocol = protocol else return self:header().protocol end end function ipv4:checksum () self:header().checksum = 0 self:header().checksum = htons(ipsum(ffi.cast("uint8_t *", self:header()), self:sizeof(), 0)) return ntohs(self:header().checksum) end function ipv4:src (ip) if ip ~= nil then ffi.copy(self:header().src_ip, ip, ipv4_addr_t_size) else return self:header().src_ip end end function ipv4:src_eq (ip) return C.memcmp(ip, self:header().src_ip, ipv4_addr_t_size) == 0 end function ipv4:dst (ip) if ip ~= nil then ffi.copy(self:header().dst_ip, ip, ipv4_addr_t_size) else return self:header().dst_ip end end function ipv4:dst_eq (ip) return C.memcmp(ip, self:header().dst_ip, ipv4_addr_t_size) == 0 end -- override the default equality method function ipv4:eq (other) --compare significant fields return (self:ihl() == other:ihl()) and (self:id() == other:id()) and (self:protocol() == other:protocol()) and self:src_eq(other:src()) and self:dst_eq(other:dst()) end -- Return a pseudo header for checksum calculation in a upper-layer -- protocol (e.g. icmp). Note that the payload length and next-header -- values in the pseudo-header refer to the effective upper-layer -- protocol. They differ from the respective values of the ipv6 -- header if extension headers are present. function ipv4:pseudo_header (ulplen, proto) local ph = self._ph ffi.fill(ph, ffi.sizeof(ph)) local h = self:header() ffi.copy(ph, h.src_ip, 2*ipv4_addr_t_size) -- Copy source and destination ph.ulp_length = htons(ulplen) ph.ulp_protocol = proto return(ph) end local function test_ipv4_checksum () local IP_BASE = 14 local IP_HDR_SIZE = 20 local p = packet.from_string(lib.hexundump([[ 52:54:00:02:02:02 52:54:00:01:01:01 08 00 45 00 00 34 59 1a 40 00 40 06 b0 8e c0 a8 14 a9 6b 15 f0 b4 de 0b 01 bb e7 db 57 bc 91 cd 18 32 80 10 05 9f 00 00 00 00 01 01 08 0a 06 0c 5c bd fa 4a e1 65 ]], 66)) local ip_hdr = ipv4:new_from_mem(p.data + IP_BASE, IP_HDR_SIZE) assert(ip_hdr) local csum = ip_hdr:checksum() assert(csum == 0xb08e, "Wrong IPv4 checksum") end function selftest() local ipv4_address = "192.168.1.1" assert(ipv4_address == ipv4:ntop(ipv4:pton(ipv4_address)), 'ipv4 text to binary conversion failed.') test_ipv4_checksum() local ipv4hdr = ipv4:new({}) assert(C.ntohs(ipv4hdr:header().ihl_v_tos) == 0x4500, 'ipv4 header field ihl_v_tos not initialized correctly.') end ipv4.selftest = selftest return ipv4
apache-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c89474727.lua
2
2996
--真閃珖竜 スターダスト・クロニクル function c89474727.initial_effect(c) --synchro summon aux.AddSynchroProcedure(c,aux.FilterBoolFunction(Card.IsType,TYPE_SYNCHRO),aux.NonTuner(Card.IsType,TYPE_SYNCHRO),1) c:EnableReviveLimit() --special summon condition local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetValue(aux.synlimit) c:RegisterEffect(e1) --immune local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(89474727,0)) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetCode(EVENT_FREE_CHAIN) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCost(c89474727.immcost) e2:SetOperation(c89474727.immop) c:RegisterEffect(e2) --spsummon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(89474727,1)) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_DESTROYED) e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e3:SetCondition(c89474727.spcon) e3:SetTarget(c89474727.sptg) e3:SetOperation(c89474727.spop) c:RegisterEffect(e3) end function c89474727.cfilter(c) return c:IsType(TYPE_SYNCHRO) and c:IsAbleToRemoveAsCost() end function c89474727.immcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c89474727.cfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c89474727.cfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c89474727.immop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_IMMUNE_EFFECT) e1:SetValue(c89474727.efilter) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) c:RegisterEffect(e1) end end function c89474727.efilter(e,re) return re:GetOwner()~=e:GetOwner() end function c89474727.spcon(e,tp,eg,ep,ev,re,r,rp) return rp~=tp and e:GetHandler():GetPreviousControler()==tp end function c89474727.spfilter(c,e,tp) return c:IsType(TYPE_SYNCHRO) and c:IsRace(RACE_DRAGON) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c89474727.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(tp) and c89474727.spfilter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c89474727.spfilter,tp,LOCATION_REMOVED,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c89474727.spfilter,tp,LOCATION_REMOVED,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c89474727.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
Team-CC-Corp/ClamShell
lib/readline.lua
1
12542
function read(replaceChar, history, completeFunction, default) term.setCursorBlink(true) local line if type(default) == "string" then line = default else line = "" end local historyPos local pos = #line local downKeys = {} local modifier = 0 if replaceChar then replaceChar = replaceChar:sub(1, 1) end local completions, currentCompletion local function recomplete() if completeFunction and pos == #line then completions = completeFunction(line) if completions and #completions > 0 then currentCompletion = 1 else currentCompletion = nil end else completions = nil currentCompletion = nil end end local function uncomplete() completions = nil currentCompletion = nil end local function updateModifier() modifier = 0 if downKeys[keys.leftCtrl] or downKeys[keys.rightCtrl] then modifier = modifier + 1 end if downKeys[keys.leftAlt] or downKeys[keys.rightAlt] then modifier = modifier + 2 end end local function nextWord() -- Attempt to find the position of the next word local offset = line:find("%w%W", pos + 1) if offset then return offset else return #line end end local function prevWord() -- Attempt to find the position of the previous word local offset = 1 while offset <= #line do local nNext = line:find("%W%w", offset) if nNext and nNext < pos then offset = nNext + 1 else return offset - 1 end end end local w, h = term.getSize() local sx = term.getCursorPos() local function redraw(clear) local scroll = 0 if sx + pos >= w then scroll = (sx + pos) - w end local cx,cy = term.getCursorPos() term.setCursorPos(sx, cy) local replace = (clear and " ") or replaceChar if replace then term.write(replace:rep(math.max(#line - scroll, 0))) else term.write(line:sub(scroll + 1)) end if currentCompletion then local sCompletion = completions[currentCompletion] local oldText if not clear then oldText = term.getTextColor() term.setTextColor(colors.gray) end if replace then term.write(replace:rep(#sCompletion)) else term.write(sCompletion) end if not clear then term.setTextColor(oldText) end end term.setCursorPos(sx + pos - scroll, cy) end local function clear() redraw(true) end recomplete() redraw() local function acceptCompletion() if currentCompletion then -- Clear clear() -- Find the common prefix of all the other suggestions which start with the same letter as the current one local completion = completions[currentCompletion] local firstLetter = completion:sub(1, 1) local commonPrefix = completion for n=1, #completions do local result = completions[n] if n ~= currentCompletion and result:find(firstLetter, 1, true) == 1 then while #commonPrefix > 1 do if result:find(commonPrefix, 1, true) == 1 then break else commonPrefix = commonPrefix:sub(1, #commonPrefix - 1) end end end end -- Append this string line = line .. commonPrefix pos = #line -- Redraw recomplete() redraw() end end while true do local event, param = os.pullEvent() if modifier == 0 and event == "char" then -- Typed key clear() line = string.sub(line, 1, pos) .. param .. string.sub(line, pos + 1) pos = pos + 1 recomplete() redraw() elseif event == "paste" then -- Pasted text clear() line = string.sub(line, 1, pos) .. param .. string.sub(line, pos + 1) pos = pos + #param recomplete() redraw() elseif event == "key" then if param == keys.leftCtrl or param == keys.rightCtrl or param == keys.leftAlt or param == keys.rightAlt then downKeys[param] = true updateModifier() elseif param == keys.enter then -- Enter if currentCompletion then clear() uncomplete() redraw() end break elseif modifier == 1 and param == keys.d then -- Enter if currentCompletion then clear() uncomplete() redraw() end line = nil pos = 0 break elseif (modifier == 0 and param == keys.left) or (modifier == 1 and param == keys.b) then -- Left if pos > 0 then clear() pos = pos - 1 recomplete() redraw() end elseif (modifier == 0 and param == keys.right) or (modifier == 1 and param == keys.f) then -- Right if pos < #line then -- Move right clear() pos = pos + 1 recomplete() redraw() else -- Accept autocomplete acceptCompletion() end elseif modifier == 2 and param == keys.b then -- Word left local nNewPos = prevWord() if nNewPos ~= pos then clear() pos = nNewPos recomplete() redraw() end elseif modifier == 2 and param == keys.f then -- Word right local nNewPos = nextWord() if nNewPos ~= pos then clear() pos = nNewPos recomplete() redraw() end elseif (modifier == 0 and (param == keys.up or param == keys.down)) or (modifier == 1 and (param == keys.p or param == keys.n)) then -- Up or down if currentCompletion then -- Cycle completions clear() if param == keys.up or param == keys.p then currentCompletion = currentCompletion - 1 if currentCompletion < 1 then currentCompletion = #completions end elseif param == keys.down or param == keys.n then currentCompletion = currentCompletion + 1 if currentCompletion > #completions then currentCompletion = 1 end end redraw() elseif history then -- Cycle history clear() if param == keys.up or param == keys.p then -- Up if historyPos == nil then if #history > 0 then historyPos = #history end elseif historyPos > 1 then historyPos = historyPos - 1 end elseif param == keys.down or param == keys.n then -- Down if historyPos == #history then historyPos = nil elseif historyPos ~= nil then historyPos = historyPos + 1 end end if historyPos then line = history[historyPos] pos = #line else line = "" pos = 0 end uncomplete() redraw() end elseif modifier == 0 and param == keys.backspace then -- Backspace if pos > 0 then clear() line = string.sub(line, 1, pos - 1) .. string.sub(line, pos + 1) pos = pos - 1 recomplete() redraw() end elseif (modifier == 0 and param == keys.home) or (modifier == 1 and param == keys.a) then -- Home if pos > 0 then clear() pos = 0 recomplete() redraw() end elseif modifier == 0 and param == keys.delete then -- Delete if pos < #line then clear() line = string.sub(line, 1, pos) .. string.sub(line, pos + 2) recomplete() redraw() end elseif (modifier == 0 and param == keys["end"]) or (modifier == 1 and param == keys.e) then -- End if pos < #line then clear() pos = #line recomplete() redraw() end elseif modifier == 1 and param == keys.u then -- Delete from cursor to beginning of line if pos > 0 then clear() line = line:sub(pos + 1) pos = 0 recomplete() redraw() end elseif modifier == 1 and param == keys.k then -- Delete from cursor to end of line if pos < #line then clear() line = line:sub(1, pos) pos = #line recomplete() redraw() end elseif modifier == 2 and param == keys.d then -- Delete from cursor to end of next word if pos < #line then local nNext = nextWord() if nNext ~= pos then clear() line = line:sub(1, pos) .. line:sub(nNext + 1) recomplete() redraw() end end elseif modifier == 1 and param == keys.w then -- Delete from cursor to beginning of previous word if pos > 0 then local nPrev = prevWord(pos) if nPrev ~= pos then clear() line = line:sub(1, nPrev) .. line:sub(pos + 1) pos = nPrev recomplete() redraw() end end elseif modifier == 0 and param == keys.tab then -- Tab (accept autocomplete) acceptCompletion() end elseif event == "key_up" then -- Update the status of the modifier flag if param == keys.leftCtrl or param == keys.rightCtrl or param == keys.leftAlt or param == keys.rightAlt then downKeys[param] = false updateModifier() end elseif event == "term_resize" then -- Terminal resized w, h = term.getSize() redraw() end end local cx, cy = term.getCursorPos() term.setCursorBlink(false) if cy >= h then term.scroll(1) term.setCursorPos(1, cy) else term.setCursorPos(1, cy + 1) end return line end
mit
Andrey2470T/Advanced-Trains-Optinal-Additional-
advtrains_freight_train/init.lua
1
5861
local S if minetest.get_modpath("intllib") then S = intllib.Getter() else S = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end end advtrains.register_wagon("diesel_lokomotive", { mesh="advtrains_engine_diesel.b3d", textures = {"advtrains_engine_diesel.png"}, is_locomotive=true, drives_on={default=true}, max_speed=10, seats = { { name=S("Driver Stand (left)"), attach_offset={x=-3, y=12, z=-2}, view_offset={x=0, y=3, z=0}, driving_ctrl_access=true, group = "dstand", }, -- { -- name=S("Driver Stand (right)"), -- attach_offset={x=5, y=10, z=-10}, -- view_offset={x=0, y=6, z=0}, -- driving_ctrl_access=true, -- group = "dstand", -- }, }, seat_groups = { dstand={ name = "Driver Stand", access_to = {}, }, }, assign_to_seat_group = {"dstand"}, visual_size = {x=1, y=1}, wagon_span=1.85, collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0}, update_animation=function(self, velocity) if self.old_anim_velocity~=advtrains.abs_ceil(velocity) then self.object:set_animation({x=1,y=80}, advtrains.abs_ceil(velocity)*15, 0, true) self.old_anim_velocity=advtrains.abs_ceil(velocity) end end, custom_on_activate = function(self, staticdata_table, dtime_s) minetest.add_particlespawner({ amount = 10, time = 0, -- ^ If time is 0 has infinite lifespan and spawns the amount on a per-second base minpos = {x=0, y=2, z=1.2}, maxpos = {x=0, y=2, z=1.2}, minvel = {x=-0.2, y=1.8, z=-0.2}, maxvel = {x=0.2, y=2, z=0.2}, minacc = {x=0, y=-0.1, z=0}, maxacc = {x=0, y=-0.3, z=0}, minexptime = 2, maxexptime = 4, minsize = 1, maxsize = 4, -- ^ The particle's properties are random values in between the bounds: -- ^ minpos/maxpos, minvel/maxvel (velocity), minacc/maxacc (acceleration), -- ^ minsize/maxsize, minexptime/maxexptime (expirationtime) collisiondetection = true, -- ^ collisiondetection: if true uses collision detection vertical = false, -- ^ vertical: if true faces player using y axis only texture = "smoke_puff.png", -- ^ Uses texture (string) attached = self.object, }) end, drops={"advtrains:engine_diesel"}, }, S("diesel Engine"), "advtrains_engine_diesel_inv.png") minetest.register_craft({ output = 'advtrains:diesel_lokomotive', recipe = { {'default:steelblock', 'dye:grey', 'default:steelblock'}, {'dye:cyan', 'dye:grey', 'dye:cyan'}, {'default:steelblock', 'dye:cyan', 'default:steelblock'}, }, }) advtrains.register_wagon("wagon_gravel", { mesh="advtrains_wagon_gravel.b3d", textures = {"advtrains_wagon_gravel.png"}, drives_on={default=true}, max_speed=10, seats = {}, visual_size = {x=1, y=1}, wagon_span=1.6, collisionbox = {-1.0,-0.5,-1.0, 1.0,1.5,1.0}, drops={"advtrains:wagon_gravel"}, has_inventory = true, get_inventory_formspec = function(self) return "size[8,11]".. "list[detached:advtrains_wgn_"..self.unique_id..";box;0,0;8,6;]".. "list[current_player;main;0,7;8,4;]".. "listring[]" end, inventory_list_sizes = { box=8*6, }, }, S("gravel Wagon"), "advtrains_wagon_gravel_inv.png") minetest.register_craft({ output = 'advtrains:wagon_gravel', recipe = { {'group:wood', 'dye:grey', 'default:steelblock'}, {'dye:red', 'dye:grey', 'dye:red'}, {'default:steelblock', 'dye:red', 'group:wood'}, }, }) advtrains.register_wagon("wagon_track", { mesh="advtrains_wagon_stick.b3d", textures = {"advtrains_wagon_stick.png"}, drives_on={default=true}, max_speed=10, seats = {}, visual_size = {x=1, y=1}, wagon_span=1.6, collisionbox = {-1.0,-0.5,-1.0, 1.0,1.5,1.0}, drops={"advtrains:wagon_track"}, has_inventory = true, get_inventory_formspec = function(self) return "size[8,11]".. "list[detached:advtrains_wgn_"..self.unique_id..";box;0,0;8,6;]".. "list[current_player;main;0,7;8,4;]".. "listring[]" end, inventory_list_sizes = { box=8*6, }, }, S("track wagon"), "advtrains_wagon_track_inv.png") minetest.register_craft({ output = 'advtrains:wagon_track', recipe = { {'group:wood', 'dye:black', 'default:steelblock'}, {'dye:red', 'dye:black', 'dye:red'}, {'default:steelblock', 'dye:red', 'group:wood'}, }, }) advtrains.register_wagon("wagon_lava", { mesh="advtrains_wagon_lava.b3d", textures = {"advtrains_wagon_lava.png"}, drives_on={default=true}, max_speed=10, seats = {}, visual_size = {x=1, y=1}, wagon_span=1.6, collisionbox = {-1.0,-0.5,-1.0, 1.0,1.5,1.0}, drops={"advtrains:wagon_lava"}, has_inventory = true, get_inventory_formspec = function(self) return "size[8,11]".. "list[detached:advtrains_wgn_"..self.unique_id..";box;0,0;8,6;]".. "list[current_player;main;0,7;8,4;]".. "listring[]" end, inventory_list_sizes = { box=8*6, }, }, S("lava wagon"), "advtrains_wagon_lava_inv.png") minetest.register_craft({ output = 'advtrains:wagon_lava', recipe = { {'group:wood', 'dye:black', 'group:wood'}, {'dye:orange', 'default:lava_source', 'dye:orange'}, {'group:wood', 'dye:orange', 'group:wood'}, }, }) advtrains.register_wagon("wagon_tree", { mesh="advtrains_wagon_tree.b3d", textures = {"advtrains_wagon_tree.png"}, drives_on={default=true}, max_speed=10, seats = {}, visual_size = {x=1, y=1}, wagon_span=1.6, collisionbox = {-1.0,-0.5,-1.0, 1.0,1.5,1.0}, drops={"advtrains:wagon_tree"}, has_inventory = true, get_inventory_formspec = function(self) return "size[8,11]".. "list[detached:advtrains_wgn_"..self.unique_id..";box;0,0;8,6;]".. "list[current_player;main;0,7;8,4;]".. "listring[]" end, inventory_list_sizes = { box=8*6, }, }, S("tree wagon"), "advtrains_wagon_tree_inv.png") minetest.register_craft({ output = 'advtrains:wagon_tree', recipe = { {'group:wood', 'dye:black', 'group:wood'}, {'group:tree', 'dye:black', 'group:tree'}, {'group:wood', 'dye:black', 'group:wood'}, }, })
lgpl-2.1
SalvationDevelopment/Salvation-Scripts-TCG
c81275020.lua
9
1600
--SRベイゴマックス function c81275020.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_HAND) e1:SetCondition(c81275020.spcon) c:RegisterEffect(e1) --search local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(81275020,0)) e2:SetCategory(CATEGORY_SEARCH+CATEGORY_TOHAND) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e2:SetCountLimit(1,81275020) e2:SetTarget(c81275020.thtg) e2:SetOperation(c81275020.thop) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e3) end function c81275020.spcon(e,c) if c==nil then return true end return Duel.GetFieldGroupCount(c:GetControler(),LOCATION_MZONE,0)==0 and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0 end function c81275020.thfilter(c) return c:IsSetCard(0x2016) and not c:IsCode(81275020) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c81275020.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c81275020.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c81275020.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c81275020.thfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c58169731.lua
5
1107
--分断の壁 function c58169731.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_ATTACK_ANNOUNCE) e1:SetCondition(c58169731.condition) e1:SetTarget(c58169731.target) e1:SetOperation(c58169731.activate) c:RegisterEffect(e1) end function c58169731.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetAttacker():IsControler(1-tp) end function c58169731.filter(c) return c:IsPosition(POS_FACEUP_ATTACK) end function c58169731.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c58169731.filter,tp,0,LOCATION_MZONE,1,nil) end end function c58169731.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(c58169731.filter,tp,0,LOCATION_MZONE,nil) if g:GetCount()==0 then return end local atk=Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)*800 local tc=g:GetFirst() while tc do local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(-atk) e1:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e1) tc=g:GetNext() end end
gpl-2.0
dickeyf/darkstar
scripts/globals/abilities/repair.lua
26
4408
----------------------------------- -- Ability: Repair -- Uses oil to restore pet's HP. -- Obtained: Puppetmaster Level 15 -- Recast Time: 3:00 -- Duration: Instant ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/pets"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getPet() == nil) then return MSGBASIC_REQUIRES_A_PET,0; else local id = player:getEquipID(SLOT_AMMO); if (id >= 18731 and id <= 18733 or id == 19185) then return 0,0; else return MSGBASIC_UNABLE_TO_USE_JA,0; end end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) -- 1st need to get the pet food is equipped in the range slot. local rangeObj = player:getEquipID(SLOT_AMMO); local totalHealing = 0; local regenAmount = 0; local regenTime = 0; local pet = player:getPet(); local petCurrentHP = pet:getHP(); local petMaxHP = pet:getMaxHP(); -- Need to start to calculate the HP to restore to the pet. -- Please note that I used this as base for the calculations: -- http://ffxiclopedia.wikia.com/wiki/Repair switch (rangeObj) : caseof { [18731] = function (x) -- Automaton Oil regenAmount = 10; totalHealing = petMaxHP * 0.1; regenTime = 30; end, [18732] = function (x) -- Automaton Oil + 1 regenAmount = 20; totalHealing = petMaxHP * 0.2; regenTime = 60; end, [18733] = function (x) -- Automaton Oil + 2 regenAmount = 30; totalHealing = petMaxHP * 0.3; regenTime = 90; end, [19185] = function (x) -- Automaton Oil + 3 regenAmount = 40; totalHealing = petMaxHP * 0.4; regenTime = 120; end, } -- Now calculating the bonus based on gear. local feet = player:getEquipID(SLOT_FEET); local earring1 = player:getEquipID(SLOT_EAR1); local earring2 = player:getEquipID(SLOT_EAR2); if (feet == 11387 or feet == 15686 or feet == 28240 or feet == 28261) then -- This will remove most debuffs from the automaton. -- Checks for Puppetry Babouches, + 1, Foire Babouches, + 1 pet:delStatusEffect(EFFECT_PARALYSIS); pet:delStatusEffect(EFFECT_POISON); pet:delStatusEffect(EFFECT_BLINDNESS); pet:delStatusEffect(EFFECT_BIND); pet:delStatusEffect(EFFECT_WEIGHT); pet:delStatusEffect(EFFECT_ADDLE); pet:delStatusEffect(EFFECT_BURN); pet:delStatusEffect(EFFECT_FROST); pet:delStatusEffect(EFFECT_CHOKE); pet:delStatusEffect(EFFECT_RASP); pet:delStatusEffect(EFFECT_SHOCK); pet:delStatusEffect(EFFECT_DIA); pet:delStatusEffect(EFFECT_BIO); pet:delStatusEffect(EFFECT_STR_DOWN); pet:delStatusEffect(EFFECT_DEX_DOWN); pet:delStatusEffect(EFFECT_VIT_DOWN); pet:delStatusEffect(EFFECT_AGI_DOWN); pet:delStatusEffect(EFFECT_INT_DOWN); pet:delStatusEffect(EFFECT_MND_DOWN); pet:delStatusEffect(EFFECT_CHR_DOWN); pet:delStatusEffect(EFFECT_MAX_HP_DOWN); pet:delStatusEffect(EFFECT_MAX_MP_DOWN); pet:delStatusEffect(EFFECT_ATTACK_DOWN); pet:delStatusEffect(EFFECT_EVASION_DOWN); pet:delStatusEffect(EFFECT_DEFENSE_DOWN); pet:delStatusEffect(EFFECT_MAGIC_DEF_DOWN); pet:delStatusEffect(EFFECT_INHIBIT_TP); pet:delStatusEffect(EFFECT_MAGIC_ACC_DOWN); pet:delStatusEffect(EFFECT_MAGIC_ATK_DOWN); end if (earring1 == 15999 or earring2 == 15999) then --Check for Guignol Earring regenAmount = regenAmount + 0.2 * regenAmount; end local diff = petMaxHP - petCurrentHP; if (diff < totalHealing) then totalHealing = diff; end pet:addHP(totalHealing); pet:wakeUp(); -- Apply regen effect. pet:delStatusEffect(EFFECT_REGEN); pet:addStatusEffect(EFFECT_REGEN,regenAmount,3,regenTime); -- 3 = tick, each 3 seconds. player:removeAmmo(); return totalHealing; end;
gpl-3.0
Turttle/darkstar
scripts/globals/abilities/ice_shot.lua
22
2936
----------------------------------- -- Ability: Ice Shot -- Consumes a Ice Card to enhance ice-based debuffs. Deals ice-based magic damage -- Frost Effect: Enhanced DoT and AGI- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) --ranged weapon/ammo: You do not have an appropriate ranged weapon equipped. --no card: <name> cannot perform that action. if (player:getWeaponSkillType(SLOT_RANGED) ~= SKILL_MRK or player:getWeaponSkillType(SLOT_AMMO) ~= SKILL_MRK) then return 216,0; end if (player:hasItem(2177, 0) or player:hasItem(2974, 0)) then return 0,0; else return 71, 0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) local params = {}; params.includemab = true; local dmg = 2 * player:getRangedDmg() + player:getAmmoDmg() + player:getMod(MOD_QUICK_DRAW_DMG); dmg = addBonusesAbility(player, ELE_ICE, target, dmg, params); dmg = dmg * applyResistanceAbility(player,target,ELE_ICE,SKILL_MRK, (player:getStat(MOD_AGI)/2) + player:getMerit(MERIT_QUICK_DRAW_ACCURACY)); dmg = adjustForTarget(target,dmg,ELE_ICE); dmg = utils.stoneskin(target, dmg); target:delHP(dmg); target:updateEnmityFromDamage(player,dmg); local effects = {}; local counter = 1; local frost = target:getStatusEffect(EFFECT_FROST); if (frost ~= nil) then effects[counter] = frost; counter = counter + 1; end local threnody = target:getStatusEffect(EFFECT_THRENODY); if (threnody ~= nil and threnody:getSubPower() == MOD_WINDRES) then effects[counter] = threnody; counter = counter + 1; end local paralyze = target:getStatusEffect(EFFECT_PARALYSIS); if (paralyze ~= nil) then effects[counter] = paralyze; counter = counter + 1; end if counter > 1 then local effect = effects[math.random(1, counter-1)]; local duration = effect:getDuration(); local startTime = effect:getStartTime(); local tick = effect:getTick(); local power = effect:getPower(); local subpower = effect:getSubPower(); local tier = effect:getTier(); local effectId = effect:getType(); local subId = effect:getSubType(); power = power * 1.2; target:delStatusEffectSilent(effectId); target:addStatusEffect(effectId, power, tick, duration, subId, subpower, tier); local newEffect = target:getStatusEffect(effectId); newEffect:setStartTime(startTime); end return dmg; end;
gpl-3.0
mimetic/DIG-corona-library
examples/dialog/scripts/funx/spinner.lua
4
5135
-- -- created with TexturePacker (http://www.codeandweb.com/texturepacker) -- -- $TexturePacker:SmartUpdate:459fc7091d0a2612fe2f6ac2521fece9:796598a08e961b575f09566039a37861:7f3c883f0651180a344ed5c6ae525a42$ -- -- 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 = { { -- spinner-18 x=2, y=2, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-17 x=376, y=2, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-16 x=750, y=2, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-15 x=1124, y=2, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-14 x=2, y=371, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-13 x=376, y=371, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-12 x=750, y=371, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-11 x=1124, y=371, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-10 x=2, y=740, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-9 x=376, y=740, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-8 x=750, y=740, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-7 x=1124, y=740, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-6 x=2, y=1109, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-5 x=376, y=1109, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-4 x=750, y=1109, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-3 x=1124, y=1109, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-2 x=2, y=1478, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, { -- spinner-1 x=376, y=1478, width=372, height=367, sourceX = 6, sourceY = 6, sourceWidth = 384, sourceHeight = 379 }, }, sheetContentWidth = 1498, sheetContentHeight = 1847 } SheetInfo.sequenceData = { name = "spinner", start = 1, count = 18, time = 2000, } function SheetInfo:getSheet() return self.sheet; end return SheetInfo
mit
SalvationDevelopment/Salvation-Scripts-TCG
c54360049.lua
4
1465
--カトブレパスと運命の魔女 function c54360049.initial_effect(c) --destroy local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(54360049,0)) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetRange(LOCATION_MZONE) e1:SetCost(c54360049.cost) e1:SetTarget(c54360049.target) e1:SetOperation(c54360049.operation) c:RegisterEffect(e1) end function c54360049.cfilter(c) return c:GetTextAttack()==-2 and c:IsAbleToRemoveAsCost() and c:IsType(TYPE_MONSTER) end function c54360049.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c54360049.cfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c54360049.cfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c54360049.filter(c,tp) return c:GetSummonPlayer()~=tp end function c54360049.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return eg:IsExists(c54360049.filter,1,nil,tp) end local g=eg:Filter(c54360049.filter,nil,tp) Duel.SetTargetCard(eg) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) end function c54360049.dfilter(c,e,tp) return c:GetSummonPlayer()~=tp and c:IsRelateToEffect(e) end function c54360049.operation(e,tp,eg,ep,ev,re,r,rp) local g=eg:Filter(c54360049.dfilter,nil,e,tp) if g:GetCount()>0 then Duel.Destroy(g,REASON_EFFECT) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c4779091.lua
2
3643
--ユベル-Das Abscheulich Ritter function c4779091.initial_effect(c) c:EnableReviveLimit() --battle local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_AVOID_BATTLE_DAMAGE) e1:SetValue(1) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e2:SetValue(1) c:RegisterEffect(e2) --damage local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(4779091,0)) e3:SetCategory(CATEGORY_DAMAGE) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e3:SetCode(EVENT_BATTLE_CONFIRM) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetCondition(c4779091.damcon) e3:SetTarget(c4779091.damtg) e3:SetOperation(c4779091.damop) c:RegisterEffect(e3) --destroy local e4=Effect.CreateEffect(c) e4:SetCategory(CATEGORY_RELEASE+CATEGORY_DESTROY) e4:SetDescription(aux.Stringid(4779091,1)) e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e4:SetRange(LOCATION_MZONE) e4:SetCountLimit(1) e4:SetCode(EVENT_PHASE+PHASE_END) e4:SetCondition(c4779091.descon) e4:SetTarget(c4779091.destg) e4:SetOperation(c4779091.desop) c:RegisterEffect(e4) --special summon local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(4779091,2)) e5:SetCategory(CATEGORY_SPECIAL_SUMMON) e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e5:SetCode(EVENT_LEAVE_FIELD) e5:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e5:SetCondition(c4779091.spcon) e5:SetTarget(c4779091.sptg) e5:SetOperation(c4779091.spop) c:RegisterEffect(e5) --cannot special summon local e6=Effect.CreateEffect(c) e6:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e6:SetType(EFFECT_TYPE_SINGLE) e6:SetCode(EFFECT_SPSUMMON_CONDITION) c:RegisterEffect(e6) end function c4779091.damcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler()==Duel.GetAttackTarget() end function c4779091.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAttackPos() end Duel.SetTargetPlayer(1-tp) local atk=Duel.GetAttacker():GetAttack() Duel.SetTargetParam(atk) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,atk) end function c4779091.damop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end function c4779091.descon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c4779091.destg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local g=Duel.GetMatchingGroup(aux.TRUE,tp,LOCATION_MZONE,LOCATION_MZONE,e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) end function c4779091.desop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(aux.TRUE,tp,LOCATION_MZONE,LOCATION_MZONE,e:GetHandler()) Duel.Destroy(g,REASON_EFFECT) end function c4779091.spcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsPreviousPosition(POS_FACEUP) and c:GetLocation()~=LOCATION_DECK end function c4779091.filter(c,e,tp) return c:IsCode(31764700) and c:IsCanBeSpecialSummoned(e,0,tp,true,true) end function c4779091.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c4779091.filter,tp,0x13,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,0x13) end function c4779091.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c4779091.filter),tp,0x13,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,true,true,POS_FACEUP) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c18205590.lua
5
2208
--天架ける星因士 function c18205590.initial_effect(c) -- local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TODECK) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCountLimit(1,18205590+EFFECT_COUNT_CODE_OATH) e1:SetTarget(c18205590.target) e1:SetOperation(c18205590.operation) c:RegisterEffect(e1) end function c18205590.filter(c,e,tp) return c:IsFaceup() and c:IsSetCard(0x9c) and c:IsAbleToDeck() and Duel.IsExistingMatchingCard(c18205590.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp,c:GetCode()) end function c18205590.spfilter(c,e,tp,code) return c:IsSetCard(0x9c) and not c:IsCode(code) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c18205590.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and c18205590.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c18205590.filter,tp,LOCATION_MZONE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g=Duel.SelectTarget(tp,c18205590.filter,tp,LOCATION_MZONE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c18205590.operation(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end local tc=Duel.GetFirstTarget() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c18205590.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp,tc:GetCode()) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) if tc:IsRelateToEffect(e) and tc:IsFaceup() then Duel.SendtoDeck(tc,nil,2,REASON_EFFECT) end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetAbsoluteRange(tp,1,0) e1:SetTarget(c18205590.splimit) e1:SetReset(RESET_EVENT+0x1fe0000) g:GetFirst():RegisterEffect(e1,true) end end function c18205590.splimit(e,c) return not c:IsSetCard(0x9c) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c45662855.lua
9
1886
--ジェムナイト・アイオーラ function c45662855.initial_effect(c) aux.EnableDualAttribute(c) --salvage local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetDescription(aux.Stringid(45662855,0)) e1:SetCategory(CATEGORY_TOHAND) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCondition(aux.IsDualState) e1:SetCost(c45662855.cost) e1:SetTarget(c45662855.target) e1:SetOperation(c45662855.operation) c:RegisterEffect(e1) end function c45662855.costfilter(c,tp) return c:IsSetCard(0x47) and c:IsType(TYPE_MONSTER) and c:IsAbleToRemoveAsCost() and Duel.IsExistingTarget(c45662855.tgfilter,tp,LOCATION_GRAVE,0,1,c) end function c45662855.tgfilter(c) return c:IsSetCard(0x1047) and c:IsAbleToHand() end function c45662855.cost(e,tp,eg,ep,ev,re,r,rp,chk) e:SetLabel(1) return true end function c45662855.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c45662855.tgfilter(chkc) end if chk==0 then if e:GetLabel()==1 then e:SetLabel(0) return Duel.IsExistingMatchingCard(c45662855.costfilter,tp,LOCATION_GRAVE,0,1,nil,tp) else return Duel.IsExistingTarget(c45662855.tgfilter,tp,LOCATION_GRAVE,0,1,nil) end end if e:GetLabel()==1 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local cg=Duel.SelectMatchingCard(tp,c45662855.costfilter,tp,LOCATION_GRAVE,0,1,1,nil,tp) Duel.Remove(cg,POS_FACEUP,REASON_COST) e:SetLabel(0) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectTarget(tp,c45662855.tgfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0) end function c45662855.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc and tc:IsRelateToEffect(e) then Duel.SendtoHand(tc,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,tc) end end
gpl-2.0
Turttle/darkstar
scripts/zones/Meriphataud_Mountains/npcs/Stone_Monument.lua
32
1308
----------------------------------- -- Area: Meriphataud Mountains -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos 450.741 2.110 -290.736 119 ----------------------------------- package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Meriphataud_Mountains/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x04000); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c69452756.lua
2
2231
--醒めない悪夢 function c69452756.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,TIMING_END_PHASE+TIMING_EQUIP) e1:SetTarget(c69452756.target1) c:RegisterEffect(e1) --destroy local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(69452756,0)) e2:SetCategory(CATEGORY_DESTROY) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetRange(LOCATION_SZONE) e2:SetCode(EVENT_FREE_CHAIN) e2:SetHintTiming(0,TIMING_END_PHASE+TIMING_EQUIP) e2:SetCost(c69452756.cost2) e2:SetTarget(c69452756.target2) e2:SetOperation(c69452756.operation) c:RegisterEffect(e2) end function c69452756.filter(c) return c:IsFaceup() and c:IsType(TYPE_SPELL+TYPE_TRAP) end function c69452756.target1(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return c69452756.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc) end if chk==0 then return true end if c69452756.cost2(e,tp,eg,ep,ev,re,r,rp,0) and c69452756.target2(e,tp,eg,ep,ev,re,r,rp,0,chkc) and Duel.SelectYesNo(tp,94) then e:SetCategory(CATEGORY_DESTROY) e:SetProperty(EFFECT_FLAG_CARD_TARGET) e:SetOperation(c69452756.operation) c69452756.cost2(e,tp,eg,ep,ev,re,r,rp,1) c69452756.target2(e,tp,eg,ep,ev,re,r,rp,1,chkc) else e:SetProperty(0) e:SetOperation(nil) end end function c69452756.cost2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckLPCost(tp,1000) and Duel.GetFlagEffect(tp,69452756)==0 end Duel.PayLPCost(tp,1000) Duel.RegisterFlagEffect(tp,69452756,RESET_CHAIN,0,1) end function c69452756.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and c69452756.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c69452756.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,c69452756.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function c69452756.operation(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end
gpl-2.0
Metastruct/pac3
lua/pac3/core/client/parts/material2.lua
1
13601
local shader_params = include("pac3/libraries/shader_params.lua") local material_flags = { debug = bit.lshift(1, 0), no_debug_override = bit.lshift(1, 1), no_draw = bit.lshift(1, 2), use_in_fillrate_mode = bit.lshift(1, 3), vertexcolor = bit.lshift(1, 4), vertexalpha = bit.lshift(1, 5), selfillum = bit.lshift(1, 6), additive = bit.lshift(1, 7), alphatest = bit.lshift(1, 8), multipass = bit.lshift(1, 9), znearer = bit.lshift(1, 10), model = bit.lshift(1, 11), flat = bit.lshift(1, 12), nocull = bit.lshift(1, 13), nofog = bit.lshift(1, 14), ignorez = bit.lshift(1, 15), decal = bit.lshift(1, 16), envmapsphere = bit.lshift(1, 17), noalphamod = bit.lshift(1, 18), envmapcameraspace = bit.lshift(1, 19), basealphaenvmapmask = bit.lshift(1, 20), translucent = bit.lshift(1, 21), normalmapalphaenvmapmask = bit.lshift(1, 22), needs_software_skinning = bit.lshift(1, 23), opaquetexture = bit.lshift(1, 24), envmapmode = bit.lshift(1, 25), suppress_decals = bit.lshift(1, 26), halflambert = bit.lshift(1, 27), wireframe = bit.lshift(1, 28), allowalphatocoverage = bit.lshift(1, 29), ignore_alpha_modulation = bit.lshift(1, 30), } local function TableToFlags(flags, valid_flags) if type(flags) == "string" then flags = {flags} end local out = 0 for k, v in pairs(flags) do if v then local flag = valid_flags[v] or valid_flags[k] if not flag then error("invalid flag", 2) end out = bit.bor(out, tonumber(flag)) end end return out end local function FlagsToTable(flags, valid_flags) if not flags then return valid_flags.default_valid_flag end local out = {} for k, v in pairs(valid_flags) do if bit.band(flags, v) > 0 then out[k] = true end end return out end local shader_name_translate = { vertexlitgeneric = "3d", unlitgeneric = "2d", eyerefract = "eye refract", } for shader_name, groups in pairs(shader_params.shaders) do for group_name, base_group in pairs(shader_params.base) do if groups[group_name] then for k,v in pairs(base_group) do groups[group_name][k] = v end else groups[group_name] = base_group end end end for shader_name, groups in pairs(shader_params.shaders) do local temp = CreateMaterial(tostring({}), shader_name, {}) local PART = {} PART.ClassName = "material_" .. (shader_name_translate[shader_name] or shader_name) PART.Description = shader_name PART.NonPhysical = true PART.Group = "pac4" PART.Icon = "icon16/paintcan.png" pac.StartStorableVars() pac.SetPropertyGroup(PART, "generic") -- move this to tools or something pac.GetSet(PART, "LoadVmt", "", {editor_panel = "material"}) function PART:SetLoadVmt(path) if not path or path == "" then return end local str = file.Read("materials/" .. path .. ".vmt", "GAME") if not str then return end local vmt = util.KeyValuesToTable(str) local shader = str:match("^(.-)%{"):gsub("%p", ""):Trim() for k,v in pairs(self:GetVars()) do if PART.ShaderParams[k] and PART.ShaderParams[k].default ~= nil then self["Set" .. k](self, PART.ShaderParams[k].default) end end print(str) print("======") PrintTable(vmt) print("======") for k,v in pairs(vmt) do if k:StartWith("$") then k = k:sub(2) end local func = self["Set" .. k] if func then local t = type(v) local info = PART.ShaderParams[k] if type(v) == "string" then if v:find("[", nil, true) then v = Vector(v:gsub("[%[%]]", ""):gsub("%s+", " "):Trim()) if type(info.default) == "number" then v = v.x end end end if type(v) == "number" then if info.type == "bool" or info.is_flag then v = v == 1 end end func(self, v) else pac.Message("cannot convert material parameter " .. k) end end end pac.GetSet(PART, "MaterialOverride", "all", {enums = function(self, str) local materials = {} if pace.current_part:HasParent() and pace.current_part:GetParent().GetEntity and pace.current_part:GetParent():GetEntity():IsValid() and pace.current_part:GetParent():GetEntity():GetMaterials() then materials = pace.current_part:GetParent():GetEntity():GetMaterials() end table.insert(materials, "all") local tbl = {} for _, v in ipairs(materials) do v = v:match(".+/(.+)") or v tbl[v] = v:lower() end return tbl end}) local function update_submaterial(self, remove, parent) pac.RunNextFrame("refresh materials" .. self.Id, function() local name = self:GetName() for _, part in ipairs(self:GetRootPart():GetChildrenList()) do if part.GetMaterials then for _, path in ipairs(part.Materials:Split(";")) do if path == name then part:SetMaterials(part.Materials) break end end end end local str = self.MaterialOverride parent = parent or self:GetParent() local num = 0 if parent:IsValid() then if tonumber(str) then num = tonumber(str) elseif str ~= "all" and parent.GetEntity and parent:GetEntity():IsValid() and parent:GetEntity():GetMaterials() then for i, v in ipairs(parent:GetEntity():GetMaterials()) do if (v:match(".+/(.+)") or v):lower() == str:lower() then num = i break end end end parent.material_override = parent.material_override or {} parent.material_override[num] = parent.material_override[num] or {} for _, stack in pairs(parent.material_override) do for i, v in ipairs(stack) do if v == self then table.remove(stack, i) break end end end if not remove then table.insert(parent.material_override[num], self) end end end) end function PART:Initialize() self.translation_vector = Vector() self.rotation_angle = Angle(0, 0, 0) end function PART:SetMaterialOverride(num) self.MaterialOverride = num update_submaterial(self) end PART.ShaderParams = {} PART.TransformVars = {} local sorted_groups = {} for k, v in pairs(groups) do table.insert(sorted_groups, {k = k, v = v}) end table.sort(sorted_groups, function(a, b) return a.k:lower() < b.k:lower() end) for _, v in ipairs(sorted_groups) do local group, params = v.k, v.v local sorted_params = {} for k, v in pairs(params) do table.insert(sorted_params, {k = k, v = v}) end table.sort(sorted_params, function(a, b) return a.k:lower() < b.k:lower() end) for _, v in ipairs(sorted_params) do local key, info = v.k, v.v PART.ShaderParams[key] = info if info.is_flag and group == "generic" then pac.SetPropertyGroup(PART, "flags") else pac.SetPropertyGroup(PART, group) end if info.default == nil then if info.type == "vec3" then info.default = Vector(0,0,0) elseif info.type == "color" then info.default = Vector(1,1,1) elseif info.type == "float" then info.default = 0 elseif info.type == "vec2" then info.default = Vector(0, 0) end end local property_name = key local description = (info.description or "") .. " ($" .. key .. ")" if info.type == "matrix" then local position_key = property_name .. "Position" local scale_key = property_name .. "Scale" local angle_key = property_name .. "Angle" local angle_center_key = property_name .. "AngleCenter" local friendly_name = info.friendly:gsub("Transform", "") pac.GetSet(PART, position_key, Vector(0, 0, 0), {editor_friendly = friendly_name .. "Position", description = description}) pac.GetSet(PART, scale_key, Vector(1, 1, 1), {editor_friendly = friendly_name .. "Scale", description = description}) pac.GetSet(PART, angle_key, 0, {editor_panel = "number", editor_friendly = friendly_name .. "Angle", description = description}) pac.GetSet(PART, angle_center_key, Vector(0.5, 0.5, 0), {editor_friendly = friendly_name .. "AngleCenter", description = description}) PART.TransformVars[position_key] = true PART.TransformVars[scale_key] = true PART.TransformVars[angle_key] = true PART.TransformVars[angle_center_key] = true local shader_key = "$" .. key local function setup_matrix(self) self.matrix = self.matrix or Matrix() self.matrix:Identity() self.matrix:Translate(self.translation_vector) self.matrix:Translate(self[angle_center_key]) self.matrix:Rotate(self.rotation_angle) self.matrix:Translate(-self[angle_center_key]) self.matrix:SetScale(self[scale_key]) end PART["Set" .. position_key] = function(self, vec) self[position_key] = vec self.translation_vector.x = self[position_key].x self.translation_vector.y = self[position_key].y setup_matrix(self) self:GetRawMaterial():SetMatrix(shader_key, self.matrix) end PART["Set" .. scale_key] = function(self, vec) self[scale_key] = vec setup_matrix(self) self:GetRawMaterial():SetMatrix(shader_key, self.matrix) end PART["Set" .. angle_key] = function(self, num) self[angle_key] = num self.rotation_angle.y = self[angle_key]*360 setup_matrix(self) self:GetRawMaterial():SetMatrix(shader_key, self.matrix) end PART["Set" .. angle_center_key] = function(self, vec) self[angle_center_key] = vec setup_matrix(self) self:GetRawMaterial():SetMatrix(shader_key, self.matrix) end elseif info.type == "texture" then info.default = info.default or "" pac.GetSet(PART, property_name, info.default, { editor_panel = "textures", editor_friendly = info.friendly, description = description, shader_param_info = info, }) local key = "$" .. key PART["Set" .. property_name] = function(self, val) self[property_name] = val if val == "" then self:GetRawMaterial():SetUndefined(key) self:GetRawMaterial():Recompute() else if not pac.resource.DownloadTexture(val, function(tex, frames) if frames then self.vtf_frame_limit = self.vtf_frame_limit or {} self.vtf_frame_limit[group] = frames end self:GetRawMaterial():SetTexture(key, tex) end, self:GetPlayerOwner()) then self:GetRawMaterial():SetTexture(key, val) end end end else pac.GetSet(PART, property_name, info.default, { editor_friendly = info.friendly, enums = info.enums, description = description, editor_sensitivity = (info.type == "vec3" or info.type == "color") and 0.25 or nil, editor_panel = (info.type == "color" and "color2") or (property_name == "model" and "boolean") or nil, editor_round = info.type == "integer", }) local flag_key = key local key = "$" .. key if type(info.default) == "number" then PART["Set" .. property_name] = function(self, val) self[property_name] = val local mat = self:GetRawMaterial() mat:SetFloat(key, val) if info.recompute then mat:Recompute() end end if property_name:lower():find("frame") then PART["Set" .. property_name] = function(self, val) self[property_name] = val if self.vtf_frame_limit and self.vtf_frame_limit[group] then self:GetRawMaterial():SetInt(key, math.abs(val)%self.vtf_frame_limit[group]) end end end elseif type(info.default) == "boolean" then if info.is_flag then PART["Set" .. property_name] = function(self, val) self[property_name] = val local mat = self:GetRawMaterial() local tbl = FlagsToTable(mat:GetInt("$flags"), material_flags) tbl[flag_key] = val mat:SetInt("$flags", TableToFlags(tbl, material_flags)) mat:Recompute() end else PART["Set" .. property_name] = function(self, val) self[property_name] = val local mat = self:GetRawMaterial() mat:SetInt(key, val and 1 or 0) if info.recompute then mat:Recompute() end end end elseif type(info.default) == "Vector" or info.type == "vec3" or info.type == "vec2" then PART["Set" .. property_name] = function(self, val) if type(val) == "string" then val = Vector() end self[property_name] = val local mat = self:GetRawMaterial() mat:SetVector(key, val) end elseif info.type == "vec4" then -- need vec4 type PART["Set" .. property_name] = function(self, val) local x,y,z,w if type(val) == "string" then x,y,z,w = unpack(val:Split(" ")) x = tonumber(x) or 0 y = tonumber(y) or 0 z = tonumber(z) or 0 w = tonumber(w) or 0 elseif type(val) == "Vector" then x,y,z = val.x, val.y, val.z w = 0 else x, y, z, w = 0, 0, 0, 0 end self[property_name] = ("%f %f %f %f"):format(x, y, z, w) local mat = self:GetRawMaterial() mat:SetString(key, ("[%f %f %f %f]"):format(x,y,z,w)) if info.recompute then mat:Recompute() end end end end end end pac.EndStorableVars() function PART:GetRawMaterial() if not self.Materialm then self.material_name = tostring({}) local mat = CreateMaterial(self.material_name, shader_name, {}) self.Materialm = mat for k,v in pairs(self:GetVars()) do self["Set" .. k](self, v) end end return self.Materialm end function PART:OnParent(parent) update_submaterial(self) end function PART:OnRemove() update_submaterial(self, true) end function PART:OnUnParent(parent) update_submaterial(self, true, parent) end function PART:OnHide() update_submaterial(self, true) end function PART:OnShow() update_submaterial(self) end pac.RegisterPart(PART) end
gpl-3.0
bartekbp/graphics
glsdk/glload/codegen/MakeAllFiles.lua
5
6077
--[[ Calling dofile on this will generate all of the header and source files needed for GLE. ]] require "_LoadLuaSpec" require "_MakeExtHeaderFile" require "_MakeMainHeaderFile" require "_MakeMainSourceFile" require "_MakeCoreHeaderFile" require "_MakeCoreSourceFile" require "_MakeInclTypeFile" require "_MakeInclCoreFile" require "_MakeInclExtFile" require "_MakeInclVersionFile" require "_util" local specFileLoc = GetSpecFilePath(); --------------------------- --Create standard OpenGL files. local specData = LoadLuaSpec(specFileLoc .. "glspec.lua"); local glPreceedData = { dofile(GetDataFilePath() .. "headerGlProtect.lua"), dofile(GetDataFilePath() .. "glDefStr.lua"), dofile(GetDataFilePath() .. "headerFunc.lua"), } --Write the external headers. local glOutputs = { {"gl_2_1", "2.1", true}, {"gl_3_0", "3.0", true}, {"gl_3_1", "3.1", true}, {"gl_3_1_comp", "3.1", false}, {"gl_3_2", "3.2", true}, {"gl_3_2_comp", "3.2", false}, {"gl_3_3", "3.3", true}, {"gl_3_3_comp", "3.3", false}, {"gl_4_0", "4.0", true}, {"gl_4_0_comp", "4.0", false}, {"gl_4_1", "4.1", true}, {"gl_4_1_comp", "4.1", false}, {"gl_4_2", "4.2", true}, {"gl_4_2_comp", "4.2", false}, }; local glTruncPreceedData = {} local removalVersions = { "3.1" } local listOfCoreVersions = dofile(GetDataFilePath() .. "listOfCoreVersions.lua"); local newGlOutputs = {}; local function GetCoreInclBasename(coreVersion, removalVersion) local baseName = "_int_gl_" .. coreVersion:gsub("%.", "_"); if(removalVersion) then baseName = baseName .. "_rem_" .. removalVersion:gsub("%.", "_"); end return baseName; end for i, coreVersion in ipairs(listOfCoreVersions) do local baseFilename = GetCoreInclBasename(coreVersion); local output = {}; output[1] = baseFilename; output[2] = coreVersion; output[3] = nil; newGlOutputs[baseFilename] = output; for i, removalVersion in ipairs(removalVersions) do output = {}; local newFilename = GetCoreInclBasename(coreVersion, removalVersion); output[1] = newFilename; output[2] = coreVersion; output[3] = removalVersion; newGlOutputs[newFilename] = output; end end local typeHeaderName = "_int_gl_type"; local extHeaderName = "_int_gl_exts"; MakeInclTypeFile(typeHeaderName, specData, glPreceedData); for baseFilename, output in pairs(newGlOutputs) do output[4] = MakeInclCoreFile(output[1], specData, "GL", "gl", output[2], output[3], glTruncPreceedData); end MakeInclExtFile(extHeaderName, specData, "GL", "gl", glTruncPreceedData); ---------------------------------- -- Write include files for the new headers. for i, output in ipairs(glOutputs) do local outVersion = output[2]; local numOutVersion = tonumber(outVersion); local includeList = {typeHeaderName, extHeaderName}; for i, version in ipairs(listOfCoreVersions) do local numVersion = tonumber(version); if(numVersion > numOutVersion) then break; end local coreName = GetCoreInclBasename(version); if(newGlOutputs[coreName][4]) then includeList[#includeList + 1] = coreName; end if(not output[3]) then for i, removalVersion in ipairs(removalVersions) do local baseName = GetCoreInclBasename(version, removalVersion) if(newGlOutputs[baseName][4]) then includeList[#includeList + 1] = baseName; end end else for i, removalVersion in ipairs(removalVersions) do if(tonumber(removalVersion) > numOutVersion) then --Has been removed from core, but not this version. local baseName = GetCoreInclBasename(version, removalVersion) if(newGlOutputs[baseName][4]) then includeList[#includeList + 1] = baseName; end end end end end MakeInclVersionFile(output[1], includeList); end local function GetVersionProfIterator() local currIx = 1; return function() if(currIx > #glOutputs) then return nil, nil; end; local currValue = glOutputs[currIx]; currIx = currIx + 1; local profile = nil; if(currValue[3]) then profile = "core"; else profile = "compatibility"; end; return currValue[2], profile; end end --Write the internal headers. local baseData = { enums = {"VERSION", "EXTENSIONS", "NUM_EXTENSIONS", "CONTEXT_PROFILE_MASK", "CONTEXT_CORE_PROFILE_BIT", "CONTEXT_COMPATIBILITY_PROFILE_BIT", "TRUE", "FALSE"}, funcs = {"GetString", "GetStringi", "GetIntegerv"}, bFuncsAreCore = true, enumPrefix = "GL", preceedData = glPreceedData, }; MakeMainHeaderFile("gll_gl_ext", specData, "gl", GetVersionProfIterator(), baseData); --MakeCoreHeaderFile("gll_gl_core", specData, "gl"); --Write the internal source files. local platformDef = dofile(GetDataFilePath() .. "stdPlatformDef.lua"); MakeMainSourceFile("gll_gl_ext", specData, "GL", "gl", GetVersionProfIterator(), glPreceedData, baseData, nil); --MakeCoreSourceFile("gll_gl_core", specData, "gl", platformDef); --------------------------- --Create WGL files. local wglSpecData = LoadLuaSpec(specFileLoc .. "wglspec.lua"); local wglPreceedData = { dofile(GetDataFilePath() .. "wglPreceed.lua"), dofile(GetDataFilePath() .. "wglHeaderFunc.lua"), dofile(GetDataFilePath() .. "glDefStr.lua"), } local wglbaseData = { enums = {}, funcs = {"GetExtensionsStringARB"}, bFuncsAreCore = false, enumPrefix = "WGL", preceedData = wglPreceedData }; MakeExtHeaderFile("wgl_exts", wglSpecData, "WGL", "wgl", nil, false, wglPreceedData); MakeMainHeaderFile("wgll_ext", wglSpecData, "wgl", nil, wglbaseData); MakeMainSourceFile("wgll_ext", wglSpecData, "WGL", "wgl", nil, wglPreceedData, wglbaseData, nil); --------------------------- --Create GLX files. local glxSpecData = LoadLuaSpec(specFileLoc .. "glxspec.lua"); local glxPreceedData = { dofile(GetDataFilePath() .. "glxPreceed.lua"), dofile(GetDataFilePath() .. "glxHeaderFunc.lua"), dofile(GetDataFilePath() .. "glDefStr.lua"), } MakeExtHeaderFile("glx_exts", glxSpecData, "GLX", "glX", nil, false, glxPreceedData); MakeMainHeaderFile("glxl_ext", glxSpecData, "glX", nil, glxbaseData); MakeMainSourceFile("glxl_ext", glxSpecData, "GLX", "glX", nil, glxPreceedData, glxbaseData, nil);
mit
Turttle/darkstar
scripts/zones/Port_San_dOria/npcs/Teilsa.lua
34
1795
----------------------------------- -- Area: Port San d'Oria -- NPC: Teilsa -- Adventurer's Assistant -- Only recieving Adv.Coupon and simple talk event are scrited -- This NPC participates in Quests and Missions ------------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ------------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(0x218,1) == true) then player:startEvent(0x0264); player:addGil(GIL_RATE*50); player:tradeComplete(); end -- "Flyers for Regine" conditional script count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x023d); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0264) then player:messageSpecial(GIL_OBTAINED,GIL_RATE*50); end end;
gpl-3.0
dickeyf/darkstar
scripts/zones/Feretory/Zone.lua
32
1164
----------------------------------- -- -- Zone: Feretory -- ----------------------------------- package.loaded["scripts/zones/Marjami_Ravine/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Marjami_Ravine/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; player:setPos(-358.000, -3.400, -440.00, 63); return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
piXelicidio/locas-ants
libs/suit/theme.lua
1
4521
-- This file is part of SUIT, copyright (c) 2016 Matthias Richter local BASE = (...):match('(.-)[^%.]+$') local theme = {} theme.cornerRadius = 4 theme.color = { normal = {bg = { 66, 66, 66}, fg = {188,188,188}}, hovered = {bg = { 50,153,187}, fg = {255,255,255}}, active = {bg = {255,153, 0}, fg = {225,225,225}} } -- HELPER function theme.getColorForState(opt) local s = opt.state or "normal" return (opt.color and opt.color[opt.state]) or theme.color[s] end function theme.drawBox(x,y,w,h, colors, cornerRadius) colors = colors or theme.getColorForState(opt) cornerRadius = cornerRadius or theme.cornerRadius w = math.max(cornerRadius/2, w) if h < cornerRadius/2 then y,h = y - (cornerRadius - h), cornerRadius/2 end love.graphics.setColor(colors.bg) love.graphics.rectangle('fill', x,y, w,h, cornerRadius) end function theme.getVerticalOffsetForAlign(valign, font, h) if valign == "top" then return 0 elseif valign == "bottom" then return h - font:getHeight() end -- else: "middle" return (h - font:getHeight()) / 2 end -- WIDGET VIEWS function theme.Label(text, opt, x,y,w,h) y = y + theme.getVerticalOffsetForAlign(opt.valign, opt.font, h) love.graphics.setColor((opt.color and opt.color.normal or {}).fg or theme.color.normal.fg) love.graphics.setFont(opt.font) love.graphics.printf(text, x+2, y, w-4, opt.align or "center") end function theme.Button(text, opt, x,y,w,h) local c = theme.getColorForState(opt) theme.drawBox(x,y,w,h, c, opt.cornerRadius) love.graphics.setColor(c.fg) love.graphics.setFont(opt.font) y = y + theme.getVerticalOffsetForAlign(opt.valign, opt.font, h) love.graphics.printf(text, x+2, y, w-4, opt.align or "center") end function theme.Checkbox(chk, opt, x,y,w,h) local c = theme.getColorForState(opt) local th = opt.font:getHeight() theme.drawBox(x+h/10,y+h/10,h*.8,h*.8, c, opt.cornerRadius) love.graphics.setColor(c.fg) if chk.checked then love.graphics.setLineStyle('smooth') love.graphics.setLineWidth(5) love.graphics.setLineJoin("bevel") love.graphics.line(x+h*.2,y+h*.55, x+h*.45,y+h*.75, x+h*.8,y+h*.2) end if chk.text then love.graphics.setFont(opt.font) y = y + theme.getVerticalOffsetForAlign(opt.valign, opt.font, h) love.graphics.printf(chk.text, x + h, y, w - h, opt.align or "left") end end function theme.Slider(fraction, opt, x,y,w,h) local xb, yb, wb, hb -- size of the progress bar local r = math.min(w,h) / 2.1 if opt.vertical then x, w = x + w*.25, w*.5 xb, yb, wb, hb = x, y+h*(1-fraction), w, h*fraction else y, h = y + h*.25, h*.5 xb, yb, wb, hb = x,y, w*fraction, h end local c = theme.getColorForState(opt) theme.drawBox(x,y,w,h, c, opt.cornerRadius) theme.drawBox(xb,yb,wb,hb, {bg=c.fg}, opt.cornerRadius) if opt.state ~= nil and opt.state ~= "normal" then love.graphics.setColor((opt.color and opt.color.active or {}).fg or theme.color.active.fg) if opt.vertical then love.graphics.circle('fill', x+wb/2, yb, r) else love.graphics.circle('fill', x+wb, yb+hb/2, r) end end end function theme.Input(input, opt, x,y,w,h) local utf8 = require 'utf8' theme.drawBox(x,y,w,h, (opt.color and opt.color.normal) or theme.color.normal, opt.cornerRadius) x = x + 3 w = w - 6 local th = opt.font:getHeight() -- set scissors local sx, sy, sw, sh = love.graphics.getScissor() love.graphics.setScissor(x-1,y,w+2,h) x = x - input.text_draw_offset -- text love.graphics.setColor((opt.color and opt.color.normal and opt.color.normal.fg) or theme.color.normal.fg) love.graphics.setFont(opt.font) love.graphics.print(input.text, x, y+(h-th)/2) -- candidate text local tw = opt.font:getWidth(input.text) local ctw = opt.font:getWidth(input.candidate_text.text) love.graphics.setColor((opt.color and opt.color.normal and opt.color.normal.fg) or theme.color.normal.fg) love.graphics.print(input.candidate_text.text, x + tw, y+(h-th)/2) -- candidate text rectangle box love.graphics.rectangle("line", x + tw, y+(h-th)/2, ctw, th) -- cursor if opt.hasKeyboardFocus and (love.timer.getTime() % 1) > .5 then local ct = input.candidate_text; local ss = ct.text:sub(1, utf8.offset(ct.text, ct.start)) local ws = opt.font:getWidth(ss) if ct.start == 0 then ws = 0 end love.graphics.setLineWidth(1) love.graphics.setLineStyle('rough') love.graphics.line(x + opt.cursor_pos + ws, y + (h-th)/2, x + opt.cursor_pos + ws, y + (h+th)/2) end -- reset scissor love.graphics.setScissor(sx,sy,sw,sh) end return theme
mit
SalvationDevelopment/Salvation-Scripts-TCG
c1372887.lua
4
2174
--相乗り function c1372887.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DRAW) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1,1372887+EFFECT_COUNT_CODE_OATH) e1:SetOperation(c1372887.activate) c:RegisterEffect(e1) end function c1372887.activate(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCode(EVENT_TO_HAND) e1:SetCondition(c1372887.drcon1) e1:SetOperation(c1372887.drop1) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD) e2:SetCode(EVENT_TO_HAND) e2:SetCondition(c1372887.regcon) e2:SetOperation(c1372887.regop) e2:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e2,tp) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD) e3:SetCode(EVENT_CHAIN_SOLVED) e3:SetCondition(c1372887.drcon2) e3:SetOperation(c1372887.drop2) e3:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e3,tp) end function c1372887.cfilter(c,tp) return c:IsControler(1-tp) and not c:IsReason(REASON_DRAW) and c:IsPreviousLocation(LOCATION_DECK+LOCATION_GRAVE) end function c1372887.drcon1(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c1372887.cfilter,1,nil,tp) and (not re:IsHasType(EFFECT_TYPE_ACTIONS) or re:IsHasType(EFFECT_TYPE_CONTINUOUS)) end function c1372887.drop1(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_CARD,0,1372887) Duel.Draw(tp,1,REASON_EFFECT) end function c1372887.regcon(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c1372887.cfilter,1,nil,tp) and Duel.GetFlagEffect(tp,1372887)==0 and re:IsHasType(EFFECT_TYPE_ACTIONS) and not re:IsHasType(EFFECT_TYPE_CONTINUOUS) end function c1372887.regop(e,tp,eg,ep,ev,re,r,rp) Duel.RegisterFlagEffect(tp,1372887,RESET_CHAIN,0,1) end function c1372887.drcon2(e,tp,eg,ep,ev,re,r,rp) return Duel.GetFlagEffect(tp,1372887)>0 end function c1372887.drop2(e,tp,eg,ep,ev,re,r,rp) Duel.ResetFlagEffect(tp,1372887) Duel.Hint(HINT_CARD,0,1372887) Duel.Draw(tp,1,REASON_EFFECT) end
gpl-2.0
Metastruct/pac3
lua/pac3/editor/client/panels/browser.lua
3
1720
local L = pace.LanguageString local PANEL = {} PANEL.ClassName = "browser" PANEL.Base = "DListView" PANEL.Dir = "" AccessorFunc(PANEL, "Dir", "Dir") function PANEL:SetDir(str) self.Dir = str self:PopulateFromClient() end function PANEL:Init() self:AddColumn(L"name") self:AddColumn(L"size") self:AddColumn(L"modified") self:PopulateFromClient() self:FixColumnsLayout() end local function OnMousePressed(self, mcode) if mcode == MOUSE_RIGHT then self:GetListView():OnRowRightClick(self:GetID(), self) elseif mcode == MOUSE_LEFT then self:GetListView():OnClickLine(self, true) self:OnSelect() end end function PANEL:AddOutfits(folder, callback) for i, name in pairs(file.Find(folder.."*", "DATA")) do if name:find("%.txt") then local outfit = folder .. name if file.Exists(outfit, "DATA") then local filenode = self:AddLine( name:gsub("%.txt", ""), string.NiceSize(file.Size(outfit, "DATA")), os.date("%m/%d/%Y %H:%M", file.Time(outfit, "DATA")) ) filenode.FileName = name filenode.OnSelect = callback filenode.OnMousePressed = OnMousePressed end end end end function PANEL:PopulateFromClient() self:Clear() self:AddOutfits("pac3/" .. self.Dir, function(node) pace.LoadParts(self.Dir .. node.FileName, true) pace.RefreshTree() end) end function PANEL.OnRowRightClick(_self,id, self) local m=DermaMenu() m:AddOption(L"View",function() self:GetListView():OnClickLine(self, true) self:OnSelect() end) m:AddOption(L"wear on server",function() self:GetListView():OnClickLine(self, true) self:OnSelect() timer.Simple(0,function() RunConsoleCommand"pac_wear_parts" end) end) m:Open() end pace.RegisterPanel(PANEL)
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c76543119.lua
4
2444
--ギミック・パペット-死の木馬 function c76543119.initial_effect(c) --destroy local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(76543119,0)) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_NO_TURN_RESET) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetTarget(c76543119.target) e1:SetOperation(c76543119.operation) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(76543119,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e2:SetCode(EVENT_TO_GRAVE) e2:SetCondition(c76543119.spcon) e2:SetTarget(c76543119.sptg) e2:SetOperation(c76543119.spop) c:RegisterEffect(e2) end function c76543119.filter(c) return c:IsFaceup() and c:IsSetCard(0x83) end function c76543119.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and c76543119.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c76543119.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,c76543119.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function c76543119.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end function c76543119.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) end function c76543119.spfilter(c,e,tp) return c:IsSetCard(0x83) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c76543119.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c76543119.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND) end function c76543119.spop(e,tp,eg,ep,ev,re,r,rp) local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft<=0 then return end if ft>2 then ft=2 end if Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c76543119.spfilter,tp,LOCATION_HAND,0,1,ft,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
dickeyf/darkstar
scripts/globals/items/bowl_of_whitefish_stew.lua
18
1536
----------------------------------------- -- ID: 4440 -- Item: Bowl of Whitefish Stew -- Food Effect: 180Min, All Races ----------------------------------------- -- Health 10 -- Dexterity 3 -- Mind -3 -- Accuracy 3 -- Ranged ACC % 7 -- Ranged ACC Cap 10 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4440); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_DEX, 3); target:addMod(MOD_MND, -3); target:addMod(MOD_ACC, 3); target:addMod(MOD_FOOD_RACCP, 7); target:addMod(MOD_FOOD_RACC_CAP, 10); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_DEX, 3); target:delMod(MOD_MND, -3); target:delMod(MOD_ACC, 3); target:delMod(MOD_FOOD_RACCP, 7); target:delMod(MOD_FOOD_RACC_CAP, 10); end;
gpl-3.0
Turttle/darkstar
scripts/globals/abilities/wind_shot.lua
22
2984
----------------------------------- -- Ability: Wind Shot -- Consumes a Wind Card to enhance wind-based debuffs. Deals wind-based magic damage -- Choke Effect: Enhanced DoT and VIT- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) --ranged weapon/ammo: You do not have an appropriate ranged weapon equipped. --no card: <name> cannot perform that action. if (player:getWeaponSkillType(SLOT_RANGED) ~= SKILL_MRK or player:getWeaponSkillType(SLOT_AMMO) ~= SKILL_MRK) then return 216,0; end if (player:hasItem(2178, 0) or player:hasItem(2974, 0)) then return 0,0; else return 71, 0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) local params = {}; params.includemab = true; local dmg = 2 * player:getRangedDmg() + player:getAmmoDmg() + player:getMod(MOD_QUICK_DRAW_DMG); dmg = addBonusesAbility(player, ELE_WIND, target, dmg, params); dmg = dmg * applyResistanceAbility(player,target,ELE_WIND,SKILL_MRK, (player:getStat(MOD_AGI)/2) + player:getMerit(MERIT_QUICK_DRAW_ACCURACY)); dmg = adjustForTarget(target,dmg,ELE_WIND); dmg = utils.stoneskin(target, dmg); target:delHP(dmg); target:updateEnmityFromDamage(player,dmg); local effects = {}; local counter = 1; local choke = target:getStatusEffect(EFFECT_CHOKE); if (choke ~= nil) then effects[counter] = choke; counter = counter + 1; end local threnody = target:getStatusEffect(EFFECT_THRENODY); if (threnody ~= nil and threnody:getSubPower() == MOD_EARTHRES) then effects[counter] = threnody; counter = counter + 1; end --TODO: Frightful Roar --[[local frightfulRoar = target:getStatusEffect(EFFECT_); if (frightfulRoar ~= nil) then effects[counter] = frightfulRoar; counter = counter + 1; end]] if counter > 1 then local effect = effects[math.random(1, counter-1)]; local duration = effect:getDuration(); local startTime = effect:getStartTime(); local tick = effect:getTick(); local power = effect:getPower(); local subpower = effect:getSubPower(); local tier = effect:getTier(); local effectId = effect:getType(); local subId = effect:getSubType(); power = power * 1.2; target:delStatusEffectSilent(effectId); target:addStatusEffect(effectId, power, tick, duration, subId, subpower, tier); local newEffect = target:getStatusEffect(effectId); newEffect:setStartTime(startTime); end return dmg; end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c95004025.lua
2
2152
--真竜導士マジェスティM function c95004025.initial_effect(c) --summon with s/t local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(95004025,0)) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SUMMON_PROC) e1:SetCondition(c95004025.otcon) e1:SetOperation(c95004025.otop) e1:SetValue(SUMMON_TYPE_ADVANCE) c:RegisterEffect(e1) --search local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(95004025,1)) e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetCode(EVENT_CHAINING) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCondition(c95004025.thcon) e2:SetTarget(c95004025.thtg) e2:SetOperation(c95004025.thop) c:RegisterEffect(e2) end function c95004025.otfilter(c) return c:IsType(TYPE_CONTINUOUS) and c:IsReleasable() end function c95004025.otcon(e,c,minc) if c==nil then return true end local tp=c:GetControler() return c:GetLevel()>4 and minc<=1 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c95004025.otfilter,tp,LOCATION_SZONE,0,1,nil) end function c95004025.otop(e,tp,eg,ep,ev,re,r,rp,c) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE) local sg=Duel.SelectMatchingCard(tp,c95004025.otfilter,tp,LOCATION_SZONE,0,1,1,nil) c:SetMaterial(sg) Duel.Release(sg,REASON_SUMMON+REASON_MATERIAL) end function c95004025.thcon(e,tp,eg,ep,ev,re,r,rp) return bit.band(e:GetHandler():GetSummonType(),SUMMON_TYPE_ADVANCE)==SUMMON_TYPE_ADVANCE and rp~=tp end function c95004025.thfilter(c) return c:IsSetCard(0xf9) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c95004025.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c95004025.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c95004025.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c95004025.thfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
gpl-2.0
dickeyf/darkstar
scripts/zones/Kazham/npcs/Nti_Badolsoma.lua
15
1053
----------------------------------- -- Area: Kazham -- NPC: Nti Badolsoma -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00B2); -- scent from Blue Rafflesias else player:startEvent(0x0058); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Metastruct/pac3
lua/pac3/core/client/parts/model2.lua
1
20345
local pac = pac local render_SetColorModulation = render.SetColorModulation local render_SetBlend = render.SetBlend local render_CullMode = render.CullMode local MATERIAL_CULLMODE_CW = MATERIAL_CULLMODE_CW local MATERIAL_CULLMODE_CCW = MATERIAL_CULLMODE_CCW local render_SetMaterial = render.SetMaterial local render_ModelMaterialOverride = render.MaterialOverride local render_MaterialOverride = render.ModelMaterialOverride local Vector = Vector local EF_BONEMERGE = EF_BONEMERGE local NULL = NULL local Color = Color local PART = {} PART.ClassName = "model2" PART.Category = "model" PART.ManualDraw = true PART.HandleModifiersManually = true PART.Icon = 'icon16/shape_square.png' PART.Group = 'pac4' PART.is_model_part = true pac.StartStorableVars() pac.SetPropertyGroup(PART, "generic") pac.GetSet(PART, "Model", "", {editor_panel = "model"}) pac.SetPropertyGroup(PART, "orientation") pac.GetSet(PART, "Size", 1, {editor_sensitivity = 0.25}) pac.GetSet(PART, "Scale", Vector(1,1,1)) pac.GetSet(PART, "BoneMerge", false) pac.SetPropertyGroup(PART, "appearance") pac.GetSet(PART, "Color", Vector(1, 1, 1), {editor_panel = "color2"}) pac.GetSet(PART, "NoLighting", false) pac.GetSet(PART, "NoCulling", false) pac.GetSet(PART, "Invert", false) pac.GetSet(PART, "Alpha", 1, {editor_sensitivity = 0.25, editor_clamp = {0, 1}}) pac.GetSet(PART, "ModelModifiers", "", {editor_panel = "model_modifiers"}) pac.GetSet(PART, "Material", "", {editor_panel = "material"}) pac.GetSet(PART, "Materials", "", {editor_panel = "model_materials"}) pac.GetSet(PART, "LevelOfDetail", 0, {editor_clamp = {-1, 8}, editor_round = true}) pac.SetupPartName(PART, "EyeTarget") pac.EndStorableVars() PART.Entity = NULL function PART:GetNiceName() local str = pac.PrettifyName(("/" .. self:GetModel()):match(".+/(.-)%.")) return str and str:gsub("%d", "") or "error" end local temp = CreateMaterial(tostring({}), "VertexLitGeneric", {}) function PART:SetLevelOfDetail(val) self.LevelOfDetail = val local ent = self:GetEntity() if ent:IsValid() then ent:SetLOD(val) end end function PART:SetSkin(var) self.Skin = var self.Entity:SetSkin(var) end function PART:ModelModifiersToTable(str) if str == "" or (not str:find(";", nil, true) and not str:find("=", nil, true)) then return {} end local tbl = {} for _, data in ipairs(str:Split(";")) do local key, val = data:match("(.+)=(.+)") if key then key = key:Trim() val = tonumber(val:Trim()) tbl[key] = val end end return tbl end function PART:ModelModifiersToString(tbl) local str = "" for k,v in pairs(tbl) do str = str .. k .. "=" .. v .. ";" end return str end function PART:SetModelModifiers(str) self.ModelModifiers = str if not self.Entity:IsValid() then return end local tbl = self:ModelModifiersToTable(str) if tbl.skin then self.Entity:SetSkin(tbl.skin) tbl.skin = nil end if not self.Entity:GetBodyGroups() then return end self.draw_bodygroups = {} for i, info in ipairs(self.Entity:GetBodyGroups()) do local val = tbl[info.name] if val then table.insert(self.draw_bodygroups, {info.id, val}) end end end function PART:SetMaterial(str) self.Material = str if str == "" then if self.material_override_self then self.material_override_self[0] = nil end else self.material_override_self = self.material_override_self or {} self.material_override_self[0] = pac.Material(str, self) end if self.material_override_self and not next(self.material_override_self) then self.material_override_self = nil end end function PART:SetMaterials(str) self.Materials = str local materials = self:GetEntity():IsValid() and self:GetEntity():GetMaterials() if not materials then return end self.material_override_self = self.material_override_self or {} local tbl = str:Split(";") for i = 1, #materials do local path = tbl[i] if path and path ~= "" then self.material_override_self[i] = pac.Material(path, self) else self.material_override_self[i] = nil end end if not next(self.material_override_self) then self.material_override_self = nil end end function PART:Reset() self:Initialize() for _, key in pairs(self:GetStorableVars()) do if PART[key] then self["Set" .. key](self, self["Get" .. key](self)) end end end function PART:OnEvent(typ) if typ == "become_physics" then local ent = self:GetEntity() if ent:IsValid() then ent:PhysicsInit(SOLID_NONE) ent:SetMoveType(MOVETYPE_NONE) ent:SetNoDraw(true) ent.RenderOverride = nil self.skip_orient = false end end end function PART:Initialize() self.Entity = pac.CreateEntity(self:GetModel()) self.Entity:SetNoDraw(true) self.Entity.PACPart = self self.material_count = 0 end function PART:GetEntity() return self.Entity or NULL end function PART:OnShow() local owner = self:GetOwner() local ent = self:GetEntity() if ent:IsValid() and owner:IsValid() and owner ~= ent then ent:SetPos(owner:EyePos()) self.BoneIndex = nil end end function PART:OnThink() self:CheckBoneMerge() end function PART:BindMaterials(ent) local materials = self.material_override_self or self.material_override local set_material = false if self.material_override_self then if materials[0] then render_MaterialOverride(materials[0]) set_material = true end for i = 1, self.material_count do local mat = materials[i] if mat then render.MaterialOverrideByIndex(i-1, mat) else render.MaterialOverrideByIndex(i-1, nil) end end elseif self.material_override then if materials[0] and materials[0][1] then render_MaterialOverride(materials[0][1]:GetRawMaterial()) set_material = true end for i = 1, self.material_count do local stack = materials[i] if stack then local mat = stack[1] if mat then render.MaterialOverrideByIndex(i-1, mat:GetRawMaterial()) else render.MaterialOverrideByIndex(i-1, nil) end end end end if (pac.render_material or self.BoneMerge) and not set_material then render_MaterialOverride() end end function PART:PreEntityDraw(owner, ent, pos, ang) if not ent:IsPlayer() and pos and ang then if not self.skip_orient then ent:SetPos(pos) ent:SetAngles(ang) else self.cached_pos = pos self.cached_ang = ang end end if self.Alpha ~= 0 and self.Size ~= 0 then self:ModifiersPreEvent("OnDraw") local r, g, b = self.Color.r, self.Color.g, self.Color.b -- render.SetColorModulation and render.SetAlpha set the material $color and $alpha. render_SetColorModulation(r,g,b) render_SetBlend(self.Alpha) if self.NoLighting then render.SuppressEngineLighting(true) end end if self.draw_bodygroups then for _, v in ipairs(self.draw_bodygroups) do ent:SetBodygroup(v[1], v[2]) end end if self.EyeTarget.cached_pos then if self.ClassName == "model2" then local attachment = ent:GetAttachment( ent:LookupAttachment( "eyes" ) ) ent:SetEyeTarget(WorldToLocal( self.EyeTarget.cached_pos, self.EyeTarget.cached_ang, attachment.Pos, attachment.Ang )) else ent:SetEyeTarget(self.EyeTarget.cached_pos) end end end function PART:PostEntityDraw(owner, ent, pos, ang) if self.Alpha ~= 0 and self.Size ~= 0 then self:ModifiersPostEvent("OnDraw") if self.NoLighting then render.SuppressEngineLighting(false) end end end function PART:OnDraw(owner, pos, ang) local ent = self:GetEntity() if not ent:IsValid() then self:Reset() ent = self:GetEntity() end if self.loading then self:DrawLoadingText(ent, pos, ang) return end self:PreEntityDraw(owner, ent, pos, ang) self:DrawModel(ent, pos, ang) self:PostEntityDraw(owner, ent, pos, ang) pac.ResetBones(ent) end function PART:DrawModel(ent, pos, ang) if self.Alpha == 0 or self.Size == 0 then return end if self.NoCulling or self.Invert then render_CullMode(MATERIAL_CULLMODE_CW) end self:BindMaterials(ent) ent.pac_drawing_model = true ent:DrawModel() ent.pac_drawing_model = false if self.NoCulling then render_CullMode(MATERIAL_CULLMODE_CCW) self:BindMaterials(ent) ent:DrawModel() elseif self.Invert then render_CullMode(MATERIAL_CULLMODE_CCW) end end function PART:DrawLoadingText(ent, pos, ang) cam.Start2D() cam.IgnoreZ(true) local pos2d = pos:ToScreen() surface.SetFont("DermaDefault") surface.SetTextColor(255, 255, 255, 255) local str = self.loading .. string.rep(".", pac.RealTime * 3 % 3) local w, h = surface.GetTextSize(self.loading .. "...") surface.SetTextPos(pos2d.x - w / 2, pos2d.y - h / 2) surface.DrawText(str) cam.IgnoreZ(false) cam.End2D() end local ALLOW_TO_MDL = CreateConVar('pac_allow_mdl', '1', {FCVAR_ARCHIVE, FCVAR_REPLICATED}, 'Allow to use custom MDLs') function PART:RealSetModel(path) local old = self.Entity:GetModel() self.Entity.pac_bones = nil self.Entity:SetModel(path) self.Entity.pac_target_model = path self:SetModelModifiers(self:GetModelModifiers()) self:SetMaterials((not old or self.Entity:GetModel() == old) and self:GetMaterials() or '') local mats = self.Entity:GetMaterials() self.material_count = mats and #mats or 0 self:SetSize(self:GetSize()) self:SetScale(self:GetScale()) end function PART:SetModel(path) self.Model = path self.Entity = self:GetEntity() if path:find("^.-://") then local status, reason = hook.Run('PAC3AllowMDLDownload', self:GetPlayerOwner(), self, path) if ALLOW_TO_MDL:GetBool() and status ~= false then self.loading = "downloading mdl zip" pac.DownloadMDL(path, function(path) self.loading = nil self:RealSetModel(path) if self:GetEntity() == pac.LocalPlayer and pacx and pacx.SetModel then pacx.SetModel(self.Model) end end, function(err) pac.Message(err) self.loading = nil self:RealSetModel("models/error.mdl") end, self:GetPlayerOwner()) else self.loading = reason or "mdl is not allowed" self:RealSetModel("models/error.mdl") pac.Message(self, ' mdl files are not allowed') end else if self:GetEntity() == pac.LocalPlayer and pacx and pacx.SetModel then pacx.SetModel(self.Model) end self:RealSetModel(path) end end local NORMAL = Vector(1,1,1) function PART:CheckScale() -- RenderMultiply doesn't work with this.. if self.BoneMerge and self.Entity:IsValid() and self.Entity:GetBoneCount() and self.Entity:GetBoneCount() > 1 then if self.Scale * self.Size ~= NORMAL then if not self.requires_bone_model_scale then self.requires_bone_model_scale = true end return true end self.requires_bone_model_scale = false end end function PART:SetAlternativeScaling(b) self.AlternativeScaling = b self:SetScale(self.Scale) end function PART:SetScale(var) var = var or Vector(1,1,1) self.Scale = var if not self:CheckScale() then pac.SetModelScale(self.Entity, self.Scale * self.Size, nil) end end function PART:SetSize(var) var = var or 1 self.Size = var if not self:CheckScale() then pac.SetModelScale(self.Entity, self.Scale * self.Size, nil) end end function PART:CheckBoneMerge() local ent = self.Entity if self.skip_orient then return end if ent:IsValid() and not ent:IsPlayer() and ent:GetModel() then if self.BoneMerge then --[[if not self.ragdoll then self.Entity = ClientsideRagdoll(ent:GetModel()) self.requires_bone_model_scale = true ent = self.Entity self.ragdoll = true end]] local owner = self:GetOwner() if owner.pac_owner_override and owner.pac_owner_override:IsValid() then owner = owner.pac_owner_override end if ent:GetParent() ~= owner then ent:SetParent(owner) if not ent:IsEffectActive(EF_BONEMERGE) then ent:AddEffects(EF_BONEMERGE) owner.pac_bonemerged = owner.pac_bonemerged or {} table.insert(owner.pac_bonemerged, ent) ent.RenderOverride = function() ent.pac_drawing_model = true ent:DrawModel() ent.pac_drawing_model = false end end end else --[[if self.ragdoll then self.Entity:Remove() ent = self:GetEntity() self.requires_bone_model_scale = true self.ragdoll = false end]] if ent:GetParent():IsValid() then local owner = ent:GetParent() ent:SetParent(NULL) if ent:IsEffectActive(EF_BONEMERGE) then ent:RemoveEffects(EF_BONEMERGE) ent.RenderOverride = nil if owner:IsValid() then owner.pac_bonemerged = owner.pac_bonemerged or {} for i, v in ipairs(owner.pac_bonemerged) do if v == ent then table.remove(owner.pac_bonemerged, i) break end end end end self.requires_bone_model_scale = false end end end end function PART:OnBuildBonePositions() if self.AlternativeScaling then return end local ent = self:GetEntity() local owner = self:GetOwner() if not ent:IsValid() or not owner:IsValid() or not ent:GetBoneCount() or ent:GetBoneCount() < 1 then return end if self.requires_bone_model_scale then local scale = self.Scale * self.Size for i = 0, ent:GetBoneCount() - 1 do if i == 0 then ent:ManipulateBoneScale(i, ent:GetManipulateBoneScale(i) * Vector(scale.x ^ 0.25, scale.y ^ 0.25, scale.z ^ 0.25)) else ent:ManipulateBonePosition(i, ent:GetManipulateBonePosition(i) + Vector((scale.x-1) ^ 4, 0, 0)) ent:ManipulateBoneScale(i, ent:GetManipulateBoneScale(i) * scale) end end end end pac.RegisterPart(PART) do local PART = {} PART.ClassName = "entity2" PART.Base = "model2" PART.Category = "model" PART.ManualDraw = true PART.HandleModifiersManually = true PART.Icon = 'icon16/shape_square.png' PART.Group = 'pac4' PART.is_model_part = false pac.StartStorableVars() pac.GetSet(PART, "NoDraw", false) pac.EndStorableVars() pac.RemoveProperty(PART, "BoneMerge") pac.RemoveProperty(PART, "Bone") pac.RemoveProperty(PART, "Position") pac.RemoveProperty(PART, "Angles") pac.RemoveProperty(PART, "PositionOffset") pac.RemoveProperty(PART, "AngleOffset") pac.RemoveProperty(PART, "EyeAngles") pac.RemoveProperty(PART, "AimPartName") function PART:Initialize() self.material_count = 0 end function PART:OnDraw(ent, pos, ang) self:PreEntityDraw(ent, ent, pos, ang) self:DrawModel(ent, pos, ang) self:PostEntityDraw(ent, ent, pos, ang) pac.ResetBones(ent) end function PART:GetEntity() local ent = self:GetOwner() self.Entity = ent return ent end local temp_mat = Material( "models/error/new light1" ) function PART:OnShow() local ent = self:GetEntity() ent.pac_originalmodel = ent.pac_originalmodel or ent:GetModel() if self.Model == "" then self.Model = ent:GetModel() or "" end if ent:IsValid() then function ent.RenderOverride() -- if the draw call is not from pac don't bother if not ent.pac_drawing_model then return end if self:IsValid() and self:GetOwner():IsValid() then if ent.pac_bonemerged then for _, e in ipairs(ent.pac_bonemerged) do if e.pac_drawing_model then return end end end -- so eyes work if self.NoDraw then render.SetBlend(0) render.ModelMaterialOverride(temp_mat) ent:DrawModel() render.SetBlend(1) render.ModelMaterialOverride() return end self:Draw(ent:GetPos(), ent:GetAngles(), self.Translucent and "translucent" or "opaque") else ent.RenderOverride = nil end end end end function PART:OnHide() local ent = self:GetOwner() if ent:IsValid() then ent.RenderOverride = nil end end function PART:RealSetModel(path) local ent = self:GetEntity() if not ent:IsValid() then return end ent:SetModel(path) ent.pac_target_model = path self:OnThink() end function PART:OnRemove() local ent = self:GetEntity() if not ent:IsValid() then return end if ent.pac_originalmodel then ent:SetModel(ent.pac_originalmodel) ent.pac_bones = nil if ent == pac.LocalPlayer and pacx and pacx.SetModel then pacx.SetModel(ent.pac_originalmodel) end end ent.pac_originalmodel = nil ent.pac_target_model = nil end function PART:OnThink() self:CheckBoneMerge() local ent = self:GetEntity() if self.last_model ~= ent:GetModel() then local old = ent:GetModel() self:SetModelModifiers(self:GetModelModifiers()) if old ~= nil and old ~= self.Entity:GetModel() then self:SetMaterials("") else self:SetMaterials(self:GetMaterials()) end self.material_count = #self.Entity:GetMaterials() self.last_model = old end end pac.RegisterPart(PART) end do local PART = {} PART.ClassName = "weapon" PART.Base = "model2" PART.Category = "model" PART.ManualDraw = true PART.HandleModifiersManually = true PART.Icon = 'icon16/shape_square.png' PART.Group = 'pac4' PART.is_model_part = false pac.StartStorableVars() pac.SetPropertyGroup(PART, "generic") pac.GetSet(PART, "OverridePosition", false) pac.GetSet(PART, "Class", "all", {enums = function() local out = { ["physgun"] = "weapon_physgun", ["357"] = "weapon_357", ["alyxgun"] = "weapon_alyxgun", ["annabelle"] = "weapon_annabelle", ["ar2"] = "weapon_ar2", ["brickbat"] = "weapon_brickbat", ["bugbait"] = "weapon_bugbait", ["crossbow"] = "weapon_crossbow", ["crowbar"] = "weapon_crowbar", ["frag"] = "weapon_frag", ["physcannon"] = "weapon_physcannon", ["pistol"] = "weapon_pistol", ["rpg"] = "weapon_rpg", ["shotgun"] = "weapon_shotgun", ["smg1"] = "weapon_smg1", ["striderbuster"] = "weapon_striderbuster", ["stunstick"] = "weapon_stunstick", } for _, tbl in pairs(weapons.GetList()) do if not tbl.ClassName:StartWith("ai_") then local friendly = tbl.ClassName:match("weapon_(.+)") or tbl.ClassName out[friendly] = tbl.ClassName end end return out end}) pac.EndStorableVars() pac.RemoveProperty(PART, "Model") function PART:GetNiceName() return self.Class end function PART:Initialize() self.material_count = 0 end function PART:OnDraw(ent, pos, ang) local ent = self:GetEntity() if not ent:IsValid() then return end local old if self.OverridePosition then old = ent:GetParent() ent:SetParent(NULL) ent:SetRenderOrigin(pos) ent:SetRenderAngles(ang) ent:SetupBones() end ent.pac_render = true self:PreEntityDraw(ent, ent, pos, ang) self:DrawModel(ent, pos, ang) self:PostEntityDraw(ent, ent, pos, ang) pac.ResetBones(ent) if self.OverridePosition then ent:MarkShadowAsDirty() --ent:SetParent(old) end ent.pac_render = nil end PART.AlwaysThink = true function PART:OnThink() local ent = self:GetOwner(true) if ent:IsValid() and ent.GetActiveWeapon then local wep = ent:GetActiveWeapon() if wep:IsValid() then if wep ~= self.Entity then if self.Class == "all" or (self.Class:lower() == wep:GetClass():lower()) then self:OnHide() self.Entity = wep self:SetEventHide(false) wep.RenderOverride = function() wep:DrawShadow(false) if wep.pac_render then wep:DrawModel() end end wep.pac_weapon_part = self else self:SetEventHide(true) self:OnHide() end end end end end function PART:OnHide() local ent = self:GetOwner(true) if ent:IsValid() and ent.GetActiveWeapon then for k,v in pairs(ent:GetWeapons()) do if v.pac_weapon_part == self then v.RenderOverride = nil v:DrawShadow(true) v:SetParent(ent) end end self.Entity = NULL end end pac.RegisterPart(PART) end
gpl-3.0
Turttle/darkstar
scripts/zones/Northern_San_dOria/npcs/Justi.lua
36
1852
----------------------------------- -- Area: Northern San d'Oria -- NPC: Justi -- Conquest depending furniture seller ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,JUSTI_SHOP_DIALOG); stock = {0x0037,69888,1, --Cabinet 0x003b,57333,1, --Chiffonier 0x0020,170726,1, --Dresser 0x0031,35272,2, --Coffer 0x002e,8376,3, --Armor Box 0x0679,92,3, --Bundling Twine 0x0039,15881,3, --Cupboard 0x0018,129168,3, --Oak Table 0x005d,518,3} --Water Cask showNationShop(player, SANDORIA, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kiavateam/kiavasecbot
libs/serpent.lua
656
7877
local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
gpl-3.0
walid55/all_wazer2
libs/serpent.lua
656
7877
local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
gpl-2.0
Turttle/darkstar
scripts/zones/FeiYin/npcs/Strange_Apparatus.lua
31
1106
----------------------------------- -- Area: FeiYin -- NPC: Strange Apparatus -- @pos -94 -15 220 204 ----------------------------------- package.loaded["scripts/zones/FeiYin/TextIDs"] = nil; require("scripts/zones/FeiYin/TextIDs"); require("scripts/globals/strangeapparatus"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) player:startEvent(0x001B, 0, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID()); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0019, 0, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Turttle/darkstar
scripts/zones/Upper_Jeuno/npcs/Collet.lua
17
2328
----------------------------------- -- Area: Upper Jeuno -- NPC: Collet -- Involved in Quests: A Clock Most Delicate, Save the Clock Tower -- @zone 244 -- @pos -44 0 107 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then a = player:getVar("saveTheClockTowerNPCz1"); -- NPC zone1 if (a == 0 or (a ~= 2 and a ~= 3 and a ~= 6 and a ~= 10 and a ~= 18 and a ~= 7 and a ~= 26 and a ~= 11 and a ~= 22 and a ~= 14 and a ~= 19 and a ~= 15 and a ~= 23 and a ~= 27 and a ~= 30 and a ~= 31)) then player:startEvent(0x0073,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getFameLevel(JEUNO) >= 5 and aClockMostdelicate == QUEST_AVAILABLE and player:getVar("aClockMostdelicateVar") == 0) then player:startEvent(0x0070); elseif (player:getVar("saveTheClockTowerVar") >= 1) then player:startEvent(0x00a4); elseif (player:getQuestStatus(JEUNO,THE_CLOCKMASTER) == QUEST_COMPLETED) then player:startEvent(0x00a3); else player:startEvent(0x0072); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0070) then player:setVar("aClockMostdelicateVar", 1); elseif (csid == 0x0073) then player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1); player:setVar("saveTheClockTowerNPCz1",player:getVar("saveTheClockTowerNPCz1") + 2); end end;
gpl-3.0
Turttle/darkstar
scripts/globals/effects/yonin.lua
17
1446
----------------------------------- -- -- -- ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) --power=30 initially, subpower=20 for enmity target:addMod(MOD_ACC,-effect:getPower()); target:addMod(MOD_EVA,effect:getPower()); target:addMod(MOD_NINJA_TOOL,effect:getPower()); target:addMod(MOD_ENMITY,effect:getSubPower()); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) --tick down the effect and reduce the overall power effect:setPower(effect:getPower()-1); target:delMod(MOD_ACC,-1); target:delMod(MOD_EVA,1); target:delMod(MOD_NINJA_TOOL,1); if (effect:getPower() % 2 == 0) then -- enmity+ decays from 20 to 10, so half as often as the rest. effect:setSubPower(effect:getSubPower()-1); target:delMod(MOD_ENMITY,1); end; end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) --remove the remaining power target:delMod(MOD_ACC,-effect:getPower()); target:delMod(MOD_EVA,effect:getPower()); target:delMod(MOD_NINJA_TOOL,effect:getPower()); target:delMod(MOD_ENMITY,effect:getSubPower()); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c37198732.lua
2
1932
--レベル・マイスター function c37198732.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCost(c37198732.cost) e1:SetTarget(c37198732.target) e1:SetOperation(c37198732.activate) c:RegisterEffect(e1) end function c37198732.cfilter(c) return c:GetLevel()>0 and c:IsAbleToGraveAsCost() end function c37198732.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then if Duel.IsExistingMatchingCard(c37198732.cfilter,tp,LOCATION_HAND,0,1,nil) then e:SetLabel(1) return true else return false end end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c37198732.cfilter,tp,LOCATION_HAND,0,1,1,nil) Duel.SendtoGrave(g,REASON_COST) e:SetLabelObject(g:GetFirst()) g:GetFirst():CreateEffectRelation(e) end function c37198732.filter(c) return c:IsFaceup() and c:GetLevel()>0 end function c37198732.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c37198732.filter(chkc) end if chk==0 then if e:GetLabel()~=1 then return false end e:SetLabel(0) return Duel.IsExistingTarget(c37198732.filter,tp,LOCATION_MZONE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c37198732.filter,tp,LOCATION_MZONE,0,1,2,nil) end function c37198732.activate(e,tp,eg,ep,ev,re,r,rp) local lc=e:GetLabelObject() if not lc:IsRelateToEffect(e) then return end local lv=lc:GetLevel() local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local tc=g:GetFirst() while tc do if tc:IsRelateToEffect(e) and tc:IsFaceup() then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CHANGE_LEVEL) e1:SetValue(lv) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) end tc=g:GetNext() end end
gpl-2.0
Turttle/darkstar
scripts/zones/Port_Bastok/npcs/Silver_Owl.lua
34
1328
----------------------------------- -- Area: Port Bastok -- NPC: Silver Owl -- Type: Tenshodo Merchant -- @pos -99.155 4.649 23.292 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then if (player:sendGuild(60420, 1, 23, 4)) then player:showText(npc,TENSHODO_SHOP_OPEN_DIALOG); end else player:startEvent(0x0096,1) end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c96223501.lua
2
2427
--竜星因士-セフィラツバーン function c96223501.initial_effect(c) --pendulum summon aux.EnablePendulumAttribute(c) --splimit local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_CANNOT_NEGATE) e2:SetRange(LOCATION_PZONE) e2:SetTargetRange(1,0) e2:SetTarget(c96223501.splimit) c:RegisterEffect(e2) --destroy local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_DESTROY) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e3:SetCode(EVENT_SUMMON_SUCCESS) e3:SetCountLimit(1,96223501) e3:SetTarget(c96223501.target) e3:SetOperation(c96223501.operation) c:RegisterEffect(e3) local e4=e3:Clone() e4:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e4) local e5=e3:Clone() e5:SetCode(EVENT_SPSUMMON_SUCCESS) e5:SetCondition(c96223501.condition) c:RegisterEffect(e5) end function c96223501.splimit(e,c,sump,sumtype,sumpos,targetp) if c:IsSetCard(0x9c) or c:IsSetCard(0xc4) then return false end return bit.band(sumtype,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM end function c96223501.condition(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetSummonType()==SUMMON_TYPE_PENDULUM end function c96223501.filter1(c) return ((c:IsLocation(LOCATION_MZONE) and c:IsFaceup()) or (c:IsLocation(LOCATION_SZONE) and (c:GetSequence()==6 or c:GetSequence()==7))) and (c:IsSetCard(0x9c) or c:IsSetCard(0xc4)) end function c96223501.filter2(c) return c:IsFaceup() end function c96223501.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return false end if chk==0 then return Duel.IsExistingTarget(c96223501.filter1,tp,LOCATION_ONFIELD,0,1,e:GetHandler()) and Duel.IsExistingTarget(c96223501.filter2,tp,0,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g1=Duel.SelectTarget(tp,c96223501.filter1,tp,LOCATION_ONFIELD,0,1,1,e:GetHandler()) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g2=Duel.SelectTarget(tp,c96223501.filter2,tp,0,LOCATION_ONFIELD,1,1,nil) g1:Merge(g2) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g1,2,0,0) end function c96223501.operation(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e) if g:GetCount()>0 then Duel.Destroy(g,REASON_EFFECT) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c100912004.lua
2
5105
--EMユーゴーレム --Performapal Fugolem --Scripted by Eerie Code function c100912004.initial_effect(c) aux.EnablePendulumAttribute(c) --salvage local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TOHAND) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetRange(LOCATION_PZONE) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCountLimit(1) e1:SetCondition(c100912004.thcon) e1:SetTarget(c100912004.thtg) e1:SetOperation(c100912004.thop) c:RegisterEffect(e1) --reg local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e2:SetCondition(c100912004.effcon) e2:SetOperation(c100912004.regop) c:RegisterEffect(e2) --fusion local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_FUSION_SUMMON) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(1) e3:SetCondition(c100912004.spcon) e3:SetTarget(c100912004.sptg) e3:SetOperation(c100912004.spop) c:RegisterEffect(e3) end function c100912004.thcfilter(c,tp) return c:IsControler(tp) and bit.band(c:GetSummonType(),SUMMON_TYPE_FUSION)==SUMMON_TYPE_FUSION end function c100912004.thcon(e,tp,eg,ep,ev,re,r,rp) return eg and eg:IsExists(c100912004.thcfilter,1,nil,tp) end function c100912004.thfilter(c) return (c:IsLocation(LOCATION_GRAVE) or c:IsFaceup()) and (c:IsSetCard(0x98) or c:IsSetCard(0x99) or c:IsSetCard(0x9f)) and c:IsType(TYPE_PENDULUM) and c:IsAbleToHand() end function c100912004.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c100912004.thfilter,tp,LOCATION_GRAVE+LOCATION_EXTRA,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_GRAVE+LOCATION_EXTRA) end function c100912004.thop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c100912004.thfilter),tp,LOCATION_GRAVE+LOCATION_EXTRA,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function c100912004.effcon(e,tp,eg,ep,ev,re,r,rp) return bit.band(e:GetHandler():GetSummonType(),SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM end function c100912004.regop(e,tp,eg,ep,ev,re,r,rp) e:GetHandler():RegisterFlagEffect(100912004,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) end function c100912004.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetFlagEffect(100912004)~=0 end function c100912004.spfilter0(c) return c:IsRace(RACE_DRAGON) and c:IsOnField() end function c100912004.spfilter1(c,e) return c100912004.spfilter0(c) and not c:IsImmuneToEffect(e) end function c100912004.spfilter2(c,e,tp,m,f,gc) return c:IsType(TYPE_FUSION) and (not f or f(c)) and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_FUSION,tp,false,false) and c:CheckFusionMaterial(m,gc) end function c100912004.spfilter3(c) return c:IsCanBeFusionMaterial() and c:IsRace(RACE_DRAGON) end function c100912004.sptg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then local mg1=Duel.GetFusionMaterial(tp):Filter(c100912004.spfilter0,c) local res=Duel.IsExistingMatchingCard(c100912004.spfilter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg1,nil,c) if not res then local ce=Duel.GetChainMaterial(tp) if ce~=nil then local fgroup=ce:GetTarget() local mg2=fgroup(ce,e,tp):Filter(c100912004.spfilter3,nil) local mf=ce:GetValue() res=Duel.IsExistingMatchingCard(c100912004.spfilter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg2,mf,c) end end return res end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) end function c100912004.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsFacedown() or not c:IsRelateToEffect(e) or c:IsImmuneToEffect(e) or c:IsControler(1-tp) then return end local mg1=Duel.GetFusionMaterial(tp):Filter(c100912004.spfilter1,c,e) local sg1=Duel.GetMatchingGroup(c100912004.spfilter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg1,nil,c) local mg2=nil local sg2=nil local ce=Duel.GetChainMaterial(tp) if ce~=nil then local fgroup=ce:GetTarget() mg2=fgroup(ce,e,tp):Filter(c100912004.spfilter3,nil) local mf=ce:GetValue() sg2=Duel.GetMatchingGroup(c100912004.spfilter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg2,mf,c) end if sg1:GetCount()>0 or (sg2~=nil and sg2:GetCount()>0) then local sg=sg1:Clone() if sg2 then sg:Merge(sg2) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local tg=sg:Select(tp,1,1,nil) local tc=tg:GetFirst() if sg1:IsContains(tc) and (sg2==nil or not sg2:IsContains(tc) or not Duel.SelectYesNo(tp,ce:GetDescription())) then local mat1=Duel.SelectFusionMaterial(tp,tc,mg1,c) tc:SetMaterial(mat1) Duel.SendtoGrave(mat1,REASON_EFFECT+REASON_MATERIAL+REASON_FUSION) Duel.BreakEffect() Duel.SpecialSummon(tc,SUMMON_TYPE_FUSION,tp,tp,false,false,POS_FACEUP) else local mat2=Duel.SelectFusionMaterial(tp,tc,mg2,c) local fop=ce:GetOperation() fop(ce,e,tp,tc,mat2) end tc:CompleteProcedure() end end
gpl-2.0
Turttle/darkstar
scripts/globals/weaponskills/double_thrust.lua
30
1320
----------------------------------- -- Double Thrust -- Polearm weapon skill -- Skill Level: 5 -- Delivers a two-hit attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Light Gorget. -- Aligned with the Light Belt. -- Element: None -- Modifiers: STR:30% -- 100%TP 200%TP 300%TP -- 1.00 1.50 2.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 2; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.dex_wsc = 0.3; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c72913666.lua
2
2059
--ゴーストリック・ワーウルフ function c72913666.initial_effect(c) --summon limit local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_SUMMON) e1:SetCondition(c72913666.sumcon) c:RegisterEffect(e1) --turn set local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(72913666,0)) e2:SetCategory(CATEGORY_POSITION) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetTarget(c72913666.postg) e2:SetOperation(c72913666.posop) c:RegisterEffect(e2) --damage local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(72913666,1)) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e3:SetCategory(CATEGORY_DAMAGE) e3:SetCode(EVENT_FLIP) e3:SetCountLimit(1,72913666) e3:SetTarget(c72913666.damtg) e3:SetOperation(c72913666.damop) c:RegisterEffect(e3) end function c72913666.sfilter(c) return c:IsFaceup() and c:IsSetCard(0x8d) end function c72913666.sumcon(e) return not Duel.IsExistingMatchingCard(c72913666.sfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) end function c72913666.postg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsCanTurnSet() and c:GetFlagEffect(72913666)==0 end c:RegisterFlagEffect(72913666,RESET_EVENT+0x1fc0000+RESET_PHASE+PHASE_END,0,1) Duel.SetOperationInfo(0,CATEGORY_POSITION,c,1,0,0) end function c72913666.posop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then Duel.ChangePosition(c,POS_FACEDOWN_DEFENSE) end end function c72913666.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local ct=Duel.GetMatchingGroupCount(Card.IsFacedown,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil) Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(ct*100) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,0,0,1-tp,ct*100) end function c72913666.damop(e,tp,eg,ep,ev,re,r,rp) local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER) local ct=Duel.GetMatchingGroupCount(Card.IsFacedown,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil) Duel.Damage(p,ct*100,REASON_EFFECT) end
gpl-2.0
erictheredsu/eric_git
MGCN/wow/WTF/Account/ERIC/Mangoscn/Erica/SavedVariables/zBar2.lua
1
1364
zBar2Saves = { ["version"] = "2.0.15", ["zShadow1"] = { ["hideTab"] = 1, ["num"] = 1, ["buttons"] = { }, ["max"] = 2, ["layout"] = "line", ["alpha"] = 1, ["linenum"] = 1, ["hide"] = true, ["pos"] = { "CENTER", -- [1] 72, -- [2] 0, -- [3] }, ["scale"] = 1, ["inset"] = 0, ["inCombat"] = "autoHide", }, ["zExBar2"] = { ["hideTab"] = true, ["num"] = 6, ["buttons"] = { }, ["layout"] = "line", ["alpha"] = 1, ["linenum"] = 2, ["hide"] = true, ["inset"] = 0, ["pos"] = { "CENTER", -- [1] -72, -- [2] 0, -- [3] }, }, ["zExBar1"] = { ["hideTab"] = 1, ["num"] = 10, ["buttons"] = { }, ["scale"] = 0.9020000100135803, ["layout"] = "line", ["alpha"] = 1, ["linenum"] = 2, ["inset"] = 0, ["pos"] = { "CENTER", -- [1] 485.902858520898, -- [2] -80.15543336007613, -- [3] }, }, ["zShadow2"] = { ["hideTab"] = true, ["num"] = 6, ["buttons"] = { }, ["max"] = 6, ["layout"] = "line", ["alpha"] = 1, ["linenum"] = 2, ["hide"] = true, ["inset"] = 0, ["pos"] = { "CENTER", -- [1] -144, -- [2] 0, -- [3] }, }, ["zCastBar"] = { ["hideTab"] = 1, ["num"] = 2, ["max"] = 2, ["layout"] = "line", ["alpha"] = 1, ["linenum"] = 2, ["scale"] = 1, ["inset"] = 0, ["pos"] = { "BOTTOM", -- [1] 0, -- [2] 181, -- [3] }, }, }
gpl-3.0
Turttle/darkstar
scripts/globals/spells/suiton_san.lua
17
1629
----------------------------------------- -- Spell: Suiton: San -- Deals water damage to an enemy and lowers its resistance against lightning. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local duration = 15 + caster:getMerit(MERIT_SUITON_EFFECT) -- T1 bonus debuff duration local bonusAcc = 0; local bonusMab = caster:getMerit(MERIT_SUITON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod if(caster:getMerit(MERIT_SUITON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits bonusMab = bonusMab + caster:getMerit(MERIT_SUITON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5 bonusAcc = bonusAcc + caster:getMerit(MERIT_SUITON_SAN) - 5; end; if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower(); end local dmg = doNinjutsuNuke(134,1,caster,spell,target,false,bonusAcc,bonusMab); handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_THUNDERRES); return dmg; end;
gpl-3.0
Turttle/darkstar
scripts/globals/items/loaf_of_homemade_bread.lua
35
1131
----------------------------------------- -- ID: 5228 -- Item: loaf_of_homemade_bread -- Food Effect: 30Min, All Races ----------------------------------------- -- Agility 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5228); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); end;
gpl-3.0
Turttle/darkstar
scripts/globals/spells/bluemagic/occultation.lua
46
1612
----------------------------------------- -- Spell: Occultation -- Creates shadow images that each absorb a single attack directed at you -- Spell cost: 138 MP -- Monster Type: Seethers -- Spell Type: Magical (Wind) -- Blue Magic Points: 3 -- Stat Bonus: VIT+3 CHR-2 -- Level: 88 -- Casting Time: 2 seconds -- Recast Time: 1 minute, 30 seconds -- -- Combos: Evasion Bonus ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end;----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_BLINK; local skill = caster:getSkillLevel(BLUE_SKILL); local power = (skill / 50); local duration = 300; -- 400 skill = 8 shadows, 450 = 9 shadows, so I am assuming every 50 skill is a shadow. -- Also assuming minimum of 2 shadows. -- I've never seen the spell cast with under 100 skill, so I could be wrong. if (skill < 100) then power = 2; end; if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then local diffMerit = caster:getMerit(MERIT_DIFFUSION); if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit; end; caster:delStatusEffect(EFFECT_DIFFUSION); end; if (target:addStatusEffect(typeEffect,power,0,duration) == false) then spell:setMsg(75); end; return typeEffect; end;
gpl-3.0
fgenesis/Aquaria_experimental
game_scripts/scripts/maps/node_hint_rollgear.lua
6
1214
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init(me) end function update(me, dt) if isFlag(FLAG_HINT_ROLLGEAR, 0) then if node_isEntityIn(me, getNaija()) then if isPlat(PLAT_MAC) then setControlHint(getStringBank(85), 1, 0, 0, 8) else setControlHint(getStringBank(65), 1, 0, 0, 8) end setFlag(FLAG_HINT_ROLLGEAR, 1) end end end
gpl-2.0
takke/MZ3
src/MZ3/scripts/gmail.lua
1
58016
--[[ * Copyright (c) MZ3 Project Team All rights reserved. * Code licensed under the BSD License: * http://www.mz3.jp/license.txt ]] -------------------------------------------------- -- MZ3 Script : gmail -- -- $Id$ -------------------------------------------------- mz3.logger_debug('gmail.lua start'); module("gmail", package.seeall) -------------------------------------------------- -- サービスの登録(タブ初期化、ログイン設定用) -------------------------------------------------- mz3.regist_service('gmail', true); -- 旧アカウントの移行 -- -- v1.2.x まで: 'GMail' -- v1.3.x 以降: 'Google' -- -- 'GMail' のものがあり、'Google' のものがなければ、'Google' に移行する -- local GMail_id = mz3_account_provider.get_value('GMail', 'id'); local GMail_pw = mz3_account_provider.get_value('GMail', 'password'); local Google_id = mz3_account_provider.get_value('Google', 'id'); local Google_pw = mz3_account_provider.get_value('Google', 'password'); if GMail_id ~= '' and Google_id == '' and GMail_pw ~= '' and Google_pw == '' then mz3_account_provider.set_value('Google', 'id', GMail_id); mz3_account_provider.set_value('Google', 'password', GMail_pw); mz3.logger_info('GMail の ID/PW を Google に移行しました'); end -- ログイン設定画面のプルダウン名、表示名の設定 mz3_account_provider.set_param('Google', 'id_name', 'メールアドレス'); mz3_account_provider.set_param('Google', 'password_name', 'パスワード'); ---------------------------------------- -- アクセス種別の登録 ---------------------------------------- -- 受信トレイ type = MZ3AccessTypeInfo.create(); type:set_info_type('category'); -- カテゴリ type:set_service_type('gmail'); -- サービス種別 type:set_serialize_key('GMAIL_INBOX'); -- シリアライズキー type:set_short_title('GMail 受信トレイ'); -- 簡易タイトル type:set_request_method('GET'); -- リクエストメソッド type:set_cache_file_pattern('gmail\\inbox_{urlparam:s}.html'); -- キャッシュファイル type:set_request_encoding('utf8'); -- エンコーディング type:set_default_url('https://mail.google.com/mail/h/'); type:set_body_header(1, 'title', '件名'); type:set_body_header(2, 'name', '差出人>>'); type:set_body_header(3, 'date', '日付>>'); type:set_body_integrated_line_pattern(1, '%2 %3'); type:set_body_integrated_line_pattern(2, '%1'); -- ログイン用 type = MZ3AccessTypeInfo.create(); type:set_info_type('category'); -- カテゴリ type:set_service_type('gmail'); -- サービス種別 type:set_serialize_key('GMAIL_LOGIN'); -- シリアライズキー type:set_short_title('GMail ログイン'); -- 簡易タイトル type:set_request_method('POST'); -- リクエストメソッド type:set_cache_file_pattern('gmail\\login.html'); -- キャッシュファイル type:set_request_encoding('sjis'); -- エンコーディング -- メール本文 type = MZ3AccessTypeInfo.create(); type:set_info_type('body'); -- カテゴリ type:set_service_type('gmail'); -- サービス種別 type:set_serialize_key('GMAIL_MAIL'); -- シリアライズキー type:set_short_title('GMail メール'); -- 簡易タイトル type:set_request_method('GET'); -- リクエストメソッド type:set_cache_file_pattern('gmail\\mail.html'); -- キャッシュファイル type:set_request_encoding('utf8'); -- エンコーディング -- 絵文字 type = MZ3AccessTypeInfo.create(); type:set_info_type('other'); -- カテゴリ type:set_service_type('gmail'); -- サービス種別 type:set_serialize_key('GMAIL_EMOJI'); -- シリアライズキー type:set_short_title('GMail 絵文字'); -- 簡易タイトル type:set_request_method('GET'); -- リクエストメソッド type:set_request_encoding('utf8'); -- エンコーディング -- メール送信 -- 書き込み画面用アクセス種別として利用する -- メール送信時は GMAIL_NEW1 でメール作成画面を取得し、 -- 成功時に GMAIL_NEW でPOSTする type = MZ3AccessTypeInfo:create(); type:set_info_type('post'); -- カテゴリ type:set_service_type('gmail'); -- サービス種別 type:set_serialize_key('GMAIL_NEW'); -- シリアライズキー type:set_short_title('GMail 送信'); -- 簡易タイトル type:set_request_method('POST'); -- リクエストメソッド type:set_request_encoding('utf8'); -- エンコーディング -- メール作成画面 type = MZ3AccessTypeInfo:create(); type:set_info_type('post'); -- カテゴリ type:set_service_type('gmail'); -- サービス種別 type:set_serialize_key('GMAIL_NEW1'); -- シリアライズキー type:set_short_title('GMail 作成画面'); -- 簡易タイトル type:set_request_method('GET'); -- リクエストメソッド type:set_request_encoding('utf8'); -- エンコーディング -- メール返信 type = MZ3AccessTypeInfo:create(); type:set_info_type('post'); -- カテゴリ type:set_service_type('gmail'); -- サービス種別 type:set_serialize_key('GMAIL_REPLY'); -- シリアライズキー type:set_short_title('GMail 返信'); -- 簡易タイトル type:set_request_method('POST'); -- リクエストメソッド type:set_request_encoding('utf8'); -- エンコーディング -- スターを付ける type = MZ3AccessTypeInfo:create(); type:set_info_type('post'); -- カテゴリ type:set_service_type('gmail'); -- サービス種別 type:set_serialize_key('GMAIL_ADD_STAR'); -- シリアライズキー type:set_short_title('GMail スター'); -- 簡易タイトル type:set_request_method('POST'); -- リクエストメソッド type:set_request_encoding('utf8'); -- エンコーディング -- スターをはずす type = MZ3AccessTypeInfo:create(); type:set_info_type('post'); -- カテゴリ type:set_service_type('gmail'); -- サービス種別 type:set_serialize_key('GMAIL_REMOVE_STAR'); -- シリアライズキー type:set_short_title('GMail スター'); -- 簡易タイトル type:set_request_method('POST'); -- リクエストメソッド type:set_request_encoding('utf8'); -- エンコーディング -- アーカイブする type = MZ3AccessTypeInfo:create(); type:set_info_type('post'); -- カテゴリ type:set_service_type('gmail'); -- サービス種別 type:set_serialize_key('GMAIL_ARCHIVE'); -- シリアライズキー type:set_short_title('GMail アーカイブ'); -- 簡易タイトル type:set_request_method('POST'); -- リクエストメソッド type:set_request_encoding('utf8'); -- エンコーディング ---------------------------------------- -- メニュー項目登録(静的に用意すること) ---------------------------------------- menu_items = {} -- メイン画面下ペイン用 menu_items.read = mz3_menu.regist_menu("gmail.on_read_menu_item"); menu_items.read_by_reportview = mz3_menu.regist_menu("gmail.on_read_by_reportview_menu_item"); menu_items.open_by_browser = mz3_menu.regist_menu("gmail.on_open_by_browser_menu_item"); menu_items.add_star = mz3_menu.regist_menu("gmail.on_add_star_menu_item"); menu_items.rmv_star = mz3_menu.regist_menu("gmail.on_remove_star_menu_item"); menu_items.archive = mz3_menu.regist_menu("gmail.on_archive_menu_item"); menu_items.send_mail = mz3_menu.regist_menu("gmail.on_send_mail"); -- 書き込み画面用 menu_items.change_to_address = mz3_menu.regist_menu("gmail.on_change_to_address"); -- 新規メールの情報 new_mail_info = {} --new_mail_info.to = TO アドレス --new_mail_info.cc = CC アドレス ---------------------------------------- -- メニューへの登録 ---------------------------------------- --- デフォルトのグループリスト生成イベントハンドラ -- -- @param serialize_key シリアライズキー(nil) -- @param event_name 'creating_default_group' -- @param group MZ3GroupData -- function on_creating_default_group(serialize_key, event_name, group) -- サポートするサービス種別の取得(スペース区切り) services = mz3_group_data.get_services(group); if services:find(' gmail', 1, true) ~= nil then -- 受信トレイ local tab = MZ3GroupItem:create("GMail"); tab:append_category("受信トレイ", "GMAIL_INBOX"); tab:append_category("スター付き", "GMAIL_INBOX", 'https://mail.google.com/mail/h/?s=r'); tab:append_category("送信済み", "GMAIL_INBOX", 'https://mail.google.com/mail/h/?s=s'); tab:append_category("すべて", "GMAIL_INBOX", 'https://mail.google.com/mail/h/?s=a'); mz3_group_data.append_tab(group, tab.item); tab:delete(); end end mz3.add_event_listener("creating_default_group", "gmail.on_creating_default_group"); ---------------------------------------- -- パーサ ---------------------------------------- -------------------------------------------------- -- 【受信トレイ】 -- -- 引数: -- parent: 上ペインの選択オブジェクト(MZ3Data*) -- body: 下ペインのオブジェクト群(MZ3DataList*) -- html: HTMLデータ(CHtmlArray*) -------------------------------------------------- function gmail_inbox_parser(parent, body, html) mz3.logger_debug("gmail_inbox_parser start"); -- wrapperクラス化 parent = MZ3Data:create(parent); body = MZ3DataList:create(body); html = MZ3HTMLArray:create(html); -- 全消去 body:clear(); local t1 = mz3.get_tick_count(); -- ログイン判定 is_logged_in = false; GALX = ''; continue_value = ''; local line_count = html:get_count(); for i=0, line_count-1 do line = html:get_at(i); -- <input id="sbb" type="submit" name="nvp_site_mail" value="メールを検索" /> -- 上記があればログイン済 = 既に受信箱 if line_has_strings(line, '<input', 'nvp_site_mail') then is_logged_in = true; break; end if line_has_strings(line, 'name="GALX"') then i = i+1; line = html:get_at(i); GALX = line:match('value="([^"]*)"'); -- mz3.alert(GALX); elseif line_has_strings(line, 'name="continue"') then i = i+1; line = html:get_at(i); continue_value = line:match('value="([^"]*)"'); -- mz3.alert(continue_value); end -- mz3.logger_debug(line); end if is_logged_in then -- mz3.alert('ログイン済'); -- 複数行に分かれているので1行に結合 line = html:get_all_text(); -- ログイン済みのHTMLのパース parse_gmail_inbox(parent, body, line); else -- ログイン処理 mail_address = mz3_account_provider.get_value('Google', 'id'); mail_password = mz3_account_provider.get_value('Google', 'password'); if (mail_address == "" or mail_password == "") then mz3.alert("メールアドレスとパスワードをログイン設定画面で設定して下さい"); return; end -- URL 生成 -- url = "https://www.google.com/accounts/ServiceLoginAuth?service=mail"; url = "https://accounts.google.com/ServiceLogin?service=mail"; post = mz3_post_data.create(); mz3_post_data.append_post_body(post, "Email=" .. mz3.url_encode(mail_address, 'utf8') .. "&"); mz3_post_data.append_post_body(post, "Passwd=" .. mz3.url_encode(mail_password, 'utf8') .. "&"); mz3_post_data.append_post_body(post, "ltmpl=ecobx&"); mz3_post_data.append_post_body(post, "service=mail&"); mz3_post_data.append_post_body(post, "nui=5&"); mz3_post_data.append_post_body(post, "ltmpl=ecobx&"); mz3_post_data.append_post_body(post, "btmpl=mobile&"); mz3_post_data.append_post_body(post, "ltmpl=ecobx&"); mz3_post_data.append_post_body(post, "scc=1&"); mz3_post_data.append_post_body(post, "GALX=" .. GALX .. "&"); mz3_post_data.append_post_body(post, "PersistentCookie=yes&"); mz3_post_data.append_post_body(post, "rmShown=1&"); mz3_post_data.append_post_body(post, "continue=" .. mz3.url_encode(continue_value, 'utf8')); -- continue_value = continue_value:gsub('&amp;', '&'); -- mz3.alert('continue_value : ' .. mz3.url_encode(continue_value, 'utf8')); -- mz3.alert(url); -- 通信開始 access_type = mz3.get_access_type_by_key("GMAIL_LOGIN"); referer = ''; user_agent = nil; mz3.open_url(mz3_main_view.get_wnd(), access_type, url, referer, "text", user_agent, post); end local t2 = mz3.get_tick_count(); mz3.logger_debug("gmail_inbox_parser end; elapsed : " .. (t2-t1) .. "[msec]"); end mz3.set_parser("GMAIL_INBOX", "gmail.gmail_inbox_parser"); --- ログイン済みの GMail 受信トレイの解析 -- -- @param parent 上ペインの選択オブジェクト(MZ3Data*) -- @param body 下ペインのオブジェクト群(MZ3DataList*) -- @param line HTML 全文を1行に結合した文字列 -- function parse_gmail_inbox(parent, body, line) mz3.logger_debug("parse_gmail_inbox start"); -- <base href="https://mail.google.com/mail/h/xxx/"> base_url = line:match('<base href="(.-)">'); -- mz3.alert(base_url); -- <form action="?at=xxxxx" name="f" method="POST"> post_url = line:match('<form action="(%?[^"].-)" name="f".->'); if post_url == nil then post_url = line:match('<form action="(%?[^"].-)" name=f.->'); end post_url = base_url .. post_url; -- mz3.alert(post_url); -- 新規メール作成用URL new_mail_url = line:match('<a href="([^"]+)" accesskey="c"'); if new_mail_url ~= nil then new_mail_url = base_url .. new_mail_url; parent:set_text('new_mail_url', new_mail_url); end -- 1メールは '<tr ' で始まる pos = line:find('<tr ', 1, true); if pos == nil then -- 解析中止 return; end pos = pos + 1; looping = true; while looping do found = line:find('<tr ', pos, true); if found == nil then looping = false; -- 最後のメールのあとは </table> が来る found = line:find('</table>', pos, true); if found == nil then -- </table> すら見つからないのは怪しいので中止 break; end end -- 1メールの抽出 w = line:sub(pos, found-1); --[[ <tr bgcolor="#E8EEF7"> <td width="1%" nowrap> <input type="checkbox" name="t" value="1216cfad69f86322"> <img src="/mail/images/cleardot.gif" width="15" height="15" border="0" alt=""> </td> <td width="25%"> Twitter (2)</td> <td width="73%"> <a href="?v=c&th=xxx"> <span class="ts"> <font size="1"> <font color="#006633"> </font> </font> xxxからダイレクトメッセージが届きました <font color="#7777CC"> xxx </font> </span> </a> </td> <td width="1%" nowrap> 19:18 <tr bgcolor="#ffffff"> <td width="1%" nowrap> <input type="checkbox" name="t" value="xx"> <img src="/mail/images/cleardot.gif" width="15" height="15" border="0" alt=""> </td> #以上、無視 <td width="25%"> <b>xxx</b> </td> #以上、name <td width="73%"> <a href="?v=c&th=xx"> #上記、URL の一部 <span class="ts"> <font size="1"> <font color="#006633"> </font> </font> <b>たいとる</b> # 上記 <b> タグ、title <font color="#7777CC"> ほんぶんばっすい ほんぶんばっすい &hellip; </font> # 上記、quote </span> </a> </td> <td width="1%" nowrap> <b>0:55</b> # 上記、日付時刻 <tr bgcolor="#ffffff"> <td> ... ]] name, href, span, date = w:match('<td.->.-</td>.-<td.-> ?(.-)</td>.-href="(.-)">.-<span.->(.-)</span>.-<td.->(.-)$'); if name~=nil then -- data 生成 data = MZ3Data:create(); --mz3.logger_debug(span); --mz3.logger_debug(date); -- span には title, quote が含まれるが、とりあえず全部 title に入れる title = span; title = title:gsub('&hellip;', '...'); -- 未読・既読判定:<b> タグの有無で。 is_new = line_has_strings(title, '<b>'); if is_new then data:set_integer('is_new', 1); else data:set_integer('is_new', 0); end title = title:gsub('<.->', ''); title = title:gsub('^ *', ''); title = title:gsub('\n', ''); title = mz3.decode_html_entity(title); data:set_text("title", title); -- URL 生成 : base_url と結合して生成 url = base_url .. href; data:set_text("url", url); date = date:gsub('<.->', ''); date = date:gsub('&nbsp;', ' '); date = date:gsub('\n', ''); date = date:gsub('^ +', ''); data:set_date(date); -- 名前 name = name:gsub('<b>', ''); name = name:gsub('</b>', ''); name = name:gsub('\n', ''); data:set_text("name", mz3.decode_html_entity(name)); data:set_text("author", name); -- スター用POST先URL data:set_text('post_url', post_url); -- URL に応じてアクセス種別を設定 type = mz3.get_access_type_by_key('GMAIL_MAIL'); data:set_access_type(type); -- data 追加 body:add(data.data); -- data 削除 data:delete(); end pos = found + 1; end end -------------------------------------------------- -- 【ログイン】 -- -- 引数: -- parent: 上ペインの選択オブジェクト(MZ3Data*) -- body: 下ペインのオブジェクト群(MZ3DataList*) -- html: HTMLデータ(CHtmlArray*) -------------------------------------------------- function gmail_login_parser(parent, body, html) mz3.logger_debug("gmail_login_parser start"); -- wrapperクラス化 parent = MZ3Data:create(parent); body = MZ3DataList:create(body); html = MZ3HTMLArray:create(html); -- 全消去 body:clear(); local t1 = mz3.get_tick_count(); url = ''; local line_count = html:get_count(); for i=0, line_count-1 do line = html:get_at(i); if line_has_strings(line, "<meta", "refresh") then url = line:match('0; url=([^"]*)'); -- mz3.alert(url); end -- mz3.logger_debug(line); end url = url:gsub('&amp;', '&'); -- mz3.alert('url : ' .. url); if url == '' then mz3.alert('ログインに失敗しました。 \r\n' .. 'メールアドレスとパスワードを確認してください。 \r\n' .. '初回ログイン時は再度アクセスするとログインできる場合があります。'); auto_login_processing = false; return; end -- 自動ログイン、無限ループ判定 if auto_login_processing then mz3.alert('自動ログインに失敗しました。'); auto_login_processing = false; return; end auto_login_processing = true; -- 通信開始 access_type = mz3.get_access_type_by_key("GMAIL_INBOX"); referer = ''; user_agent = nil; post = nil; mz3.open_url(mz3_main_view.get_wnd(), access_type, url, referer, "text", user_agent, post); local t2 = mz3.get_tick_count(); mz3.logger_debug("gmail_login_parser end; elapsed : " .. (t2-t1) .. "[msec]"); end mz3.set_parser("GMAIL_LOGIN", "gmail.gmail_login_parser"); -------------------------------------------------- -- 【メール】 -- -- 引数: -- data: 上ペインのオブジェクト群(MZ3Data*) -- dummy: NULL -- html: HTMLデータ(CHtmlArray*) -------------------------------------------------- function gmail_mail_parser(data, dummy, html) mz3.logger_debug("gmail_mail_parser start"); -- メインビュー、ボディリストのアイコンを既読にする mz3_data.set_integer(mz3_main_view.get_selected_body_item(), 'is_new', 0); mz3_main_view.redraw_body_images(); -- wrapperクラス化 data = MZ3Data:create(data); html = MZ3HTMLArray:create(html); -- 全消去 data:clear(); local t1 = mz3.get_tick_count(); local line_count = html:get_count(); -- 複数行に分かれているので1行に結合 line = html:get_all_text(); -- base url の解析 -- <base href="https://mail.google.com/mail/h/xxx/"> base_url = line:match('<base href="(.-)">'); data:set_text('base_url', base_url); if base_url~=nil then base_host = base_url:match('(https?://.-)/'); end -- 「全て展開」=全スレッド表示対応 -- ※無限ループ対策のため、メイン画面から遷移した場合のみ実施する if read_gmail_mail_first then read_gmail_mail_first = false; -- <a href="?v=c&d=e&th=xxx" class="nu"> -- <img src="/mail/images/expand_icon.gif" width="16" height="16" border="0" alt="すべてのメッセージを展開"> -- &nbsp;<span class="u">すべて展開</span></a> if line_has_strings(line, 'alt="すべてのメッセージを展開"') then expand_url = line:match('<a href="([^">]+)"[^>]+><img[^>]+>&nbsp;<span[^>]+>すべて展開'); -- mz3.alert(expand_url); -- expand_url = nil; if expand_url ~= nil then mz3.logger_debug('全スレッドを取得します'); data:add_text_array("body", "全スレッドを取得しています。しばらくお待ち下さい。。。"); -- 通信開始 url = base_url .. expand_url; key = "GMAIL_MAIL"; access_type = mz3.get_access_type_by_key(key); referer = ''; user_agent = nil; post = nil; mz3.open_url(mz3_main_view.get_wnd(), access_type, url, referer, "text", user_agent, post); return; end end end -- タイトル -- <h2><font size="+1"><b>たいとる</b></font></h2> title = line:match('<h2><font size=.-><b>(.-)</b>'); title = title:gsub('<.->', ''); title = title:gsub('^ *', ''); title = mz3.decode_html_entity(title); data:set_text('title', title); -- スレッド分離 -- 特定のtableと「返信開始タグ」で分離する one_mail_start_tags = '<table width="100%" cellpadding="1" cellspacing="0" border="0" bgcolor="#efefef"> <tr> <td> '; one_mail_start_tags2 = '<table width=98% cellpadding=0 cellspacing=0 border=0 align=center class=h>'; reply_start_tags = '<table width="100%" cellpadding="1" cellspacing="0" border="0" bgcolor="#e0ecff" class="qr"> <tr> '; reply_start_tags2 = 'class=qr>'; -- 絵文字URLリスト -- 例) emoji_urls[0] = 'https://mail.google.com/mail/e/ezweb_ne_jp/B60'; emoji_urls = {} local one_mail = ''; local mail_count = 0; local start = 1; local pos = 1; while true do -- メール開始タグを探す local len = 0; pos = line:find(one_mail_start_tags, start, true); if pos ~= nil then len = one_mail_start_tags:len(); else pos = line:find(one_mail_start_tags2, start, true); len = one_mail_start_tags2:len(); end -- mz3.alert(pos); if pos ~= nil then -- 「返信開始タグ」までを1通とする pos = line:find(reply_start_tags, start, true); if pos == nil then pos = line:find(reply_start_tags2, start, true); end -- mz3.alert(pos); if pos == nil then -- 「返信開始タグ」がないので最後まで。 one_mail = line:sub(start); else one_mail = line:sub(start, pos-1); end -- 整形、Data化 if mail_count == 0 then mail_count = 1; end -- mz3.logger_debug(one_mail); parse_one_mail(data, one_mail, mail_count); break; else one_mail = line:sub(start, pos-1); -- 整形、Data化 parse_one_mail(data, one_mail, mail_count); start = pos + len; mail_count = mail_count +1; end end if pos ~= nil then -- 「返信開始タグ」以降を用いて返信フォームを取得 reply_form = line:sub(pos); -- 最初の <form>..</form> が返信フォーム。 reply_form = reply_form:match('<form.-</form>'); -- data にフォームをそのまま埋め込んでおく -- 返信実行時にこのフォームの内容を利用する data:set_text('reply_form', reply_form); end -- for k, v in pairs(emoji_urls) do -- print(k, v); -- end -- print(#emoji_urls); -- 未ロードの絵文字があればロード開始 get_next_emoji_url(); local t2 = mz3.get_tick_count(); mz3.logger_debug("gmail_mail_parser end; elapsed : " .. (t2-t1) .. "[msec]"); end mz3.set_parser("GMAIL_MAIL", "gmail.gmail_mail_parser"); --- emoji_urls の先頭要素に対してリクエストする function get_next_emoji_url() if #emoji_urls >= 1 then -- 通信開始 url = emoji_urls[1]; -- mz3.alert(url); access_type = mz3.get_access_type_by_key("GMAIL_EMOJI"); referer = ''; user_agent = nil; post = nil; mz3.open_url(mz3_report_view.get_wnd(), access_type, url, referer, "binary", user_agent, post); return true; else return false; end end --- スレッド内の1通のメールを解析し、data に設定する -- -- @param data MZ3Data オブジェクト -- @param line 1通のメールに対応するHTML -- function parse_one_mail(data, line, count) mz3.logger_debug("parse_one_mail(" .. count .. ")"); if count==0 then -- 最初はヘッダーなので無視 return; end if count>=2 then -- 2件目以降は子要素として投入する child = MZ3Data:create(); parse_one_mail(child, line, 1); data:add_child(child); child:delete(); return; end -- mz3.logger_debug(line); -- 名前 -- <h3>... <b>なまえ</b> ...</h3> name = line:match('<h3>.-<b>(.-)</b>'); data:set_text("name", mz3.decode_html_entity(name)); data:set_text("author", mz3.decode_html_entity(name)); -- 日付 -- <td align="right" valign="top"> 2009/05/24 8:17 <tr> date = line:match('<td align="right" valign="top"> (.-) <'); if date == nil then -- <td align=right valign=top>Fri, Mar 5, 2010 at 11:05 PM<tr> date = line:match('<td align=right valign=top>(.-)<'); end -- mz3.alert(date); if date ~= nil then date = date:gsub('<.->', ''); data:set_date(date); end -- 本文 body = line:match('<div class="?msg"?> ?(.*)$'); if body ~= nil then -- 簡易HTML解析 body = body:gsub('<WBR>', ''); body = body:gsub('<wbr />', ''); body = body:gsub('<b .->', "<b>"); body = body:gsub('<p .->', "<p>"); body = body:gsub('<h2.->(.-)</h2>', '<b>%1</b>'); body = body:gsub('<b>', "\n<b>\n<br>"); body = body:gsub('</b>', "<br>\n</b>\n"); body = body:gsub('<br ?/>', "<br>"); body = body:gsub('<font .->', ""); body = body:gsub('</font>', ""); body = body:gsub('<hr .->', "<hr>"); body = body:gsub('<hr>', "<br>----------------------------------------<br>"); body = body:gsub('<tr[^>]*>', ""); body = body:gsub('<td[^>]*>', ""); body = body:gsub('</tr>', "<br>"); body = body:gsub('</td>', ""); body = body:gsub('<table[^>]*>', ""); body = body:gsub('</table>', ""); body = body:gsub('<map.-</map>', ''); -- 内部リンクの補完(/で始まる場合にホストを補完する) body = body:gsub('(<a .-href=")(/.-")', '%1' .. base_host .. '%2'); body = body:gsub('(<img .-src=")(/.-")', '%1' .. base_host .. '%2'); -- 内部リンクの補完(?で始まる場合にbaseを補完する) body = body:gsub('(<a .-href=")(\?.-")', '%1' .. base_host .. '%2'); body = body:gsub('(<img .-src=")\?(.-")', '%1' .. base_url .. '%2'); body = body:gsub("\r\n", "\n"); body = body:gsub('^ *', ''); -- <img タグだが src がないものは削除 local post = 1; local start = 1; local body2 = ''; while true do pos = body:find('<img', start, true); if pos == nil then body2 = body2 .. body:sub(start); break; else body2 = body2 .. body:sub(start, pos-1); img = body:match('<img .->', start); if line_has_strings(img, 'src=') then -- さらに絵文字であれば変換 -- <img src="https://mail.google.com/mail/e/ezweb_ne_jp/B60" goomoji="ezweb_ne_jp.B60" ... /> -- <img src="https://mail.google.com/mail/e/docomo_ne_jp/330" goomoji="docomo_ne_jp.330" ... /> emoji_url, goomoji = img:match('src="(https://mail.google.com/mail/e/.-)" goomoji="(.-)"'); if emoji_url ~= nil and goomoji ~= nil then -- 未ロードの絵文字があればダウンロードする local idx = mz3_image_cache.get_image_index_by_url(emoji_url); if idx==-1 then -- 未ロードなのでダウンロード(予約)する table.insert(emoji_urls, emoji_url); body2 = body2 .. "[loading...]"; else -- ロード済みなのでidxをらんらんビュー形式に変換する body2 = body2 .. "[g:" .. idx .. "]"; end else body2 = body2 .. img; end end start = pos + img:len(); end end body2 = body2:gsub('<a [^>]*></a>', ""); -- print(body2); data:add_text_array("body", "\r\n"); data:add_body_with_extract(body2); end end ---------------------------------------- -- イベントハンドラ ---------------------------------------- --- ボディリストのアイコンのインデックス取得 -- -- @param event_name 'get_end_binary_report_view' -- @param serialize_key シリアライズキー(nil) -- @param http_status http status -- @param url url -- -- @return (1) [bool] 成功時は true, 続行時は false -- function on_get_end_binary_report_view(event_name, serialize_key, http_status, url, filename) mz3.logger_debug('on_get_end_binary_report_view', event_name, serialize_key, http_status, url, filename); if serialize_key == "GMAIL_EMOJI" then -- 保存 local path = mz3.make_image_logfile_path_from_url_md5(url); mz3.logger_debug(path); -- mz3.alert(path); mz3.copy_file(filename, path); -- 絵文字リストから削除 table.remove(emoji_urls, 1); -- 未ロードの絵文字があればロード開始 if get_next_emoji_url()==false then -- 全ロード完了 -- とりあえず再度メールを受信する -- TODO 画面再描画のみにしたい url = mail_url; key = "GMAIL_MAIL"; access_type = mz3.get_access_type_by_key(key); referer = ''; user_agent = nil; post = nil; mz3.open_url(mz3_main_view.get_wnd(), access_type, url, referer, "text", user_agent, post); end return true; end return false; end mz3.add_event_listener("get_end_binary_report_view", "gmail.on_get_end_binary_report_view"); --- ボディリストのアイコンのインデックス取得 -- -- @param event_name 'get_body_list_default_icon_index' -- @param serialize_key シリアライズキー(nil) -- @param body body data -- -- @return (1) [bool] 成功時は true, 続行時は false -- @return (2) [int] アイコンインデックス -- function on_get_body_list_default_icon_index(event_name, serialize_key, body) if serialize_key == "GMAIL_MAIL" then if mz3_data.get_integer(body, 'is_new')~=0 then return true, 6; else return true, 7; end end return false; end mz3.add_event_listener("get_body_list_default_icon_index", "gmail.on_get_body_list_default_icon_index"); --- ViewStyle 変更 -- -- @param event_name 'get_view_style' -- @param serialize_key カテゴリのシリアライズキー -- -- @return (1) [bool] 成功時は true, 続行時は false -- @return (2) [int] VIEW_STYLE_* -- function on_get_view_style(event_name, serialize_key) service_type = mz3.get_service_type(serialize_key); if service_type=='gmail' then return true, VIEW_STYLE_IMAGE; end return false; end mz3.add_event_listener("get_view_style", "gmail.on_get_view_style"); --- 全文表示メニューまたはダブルクリックイベント function on_read_menu_item(serialize_key, event_name, data) mz3.logger_debug('on_read_menu_item : (' .. serialize_key .. ', ' .. event_name .. ')'); data = MZ3Data:create(data); item = ''; item = item .. "名前 : " .. data:get_text('name') .. "\r\n"; item = item .. "日付 : " .. data:get_date() .. "\r\n"; item = item .. "----\r\n"; item = item .. data:get_text('title') .. "\r\n"; item = item .. "\r\n"; item = item .. data:get_text('url') .. "\r\n"; mz3.alert(item, data:get_text('name')); return true; end --- メール送信 function on_send_mail(serialize_key, event_name, data) mz3.logger_debug('on_send_mail: (' .. serialize_key .. ', ' .. event_name .. ')'); data = MZ3Data:create(data); -- 新規メール用の初期化 new_mail_info = {} -- 送信先アドレス取得 if do_input_to_address() == false then return true; end -- 書き込み画面への遷移 mz3.start_write_view('GMAIL_NEW', mz3_main_view.get_selected_category_item()); return true; end function do_input_to_address() while true do local to = mz3.show_common_edit_dlg("送信先設定", "送信先メールアドレスを入力して下さい", new_mail_info.to); if to == nil then return false; end if to:match('^[^@]+@[^@]+$')==nil then mz3.alert("メールアドレスの形式が不正です。再度入力してください。"); else new_mail_info.to = to; break; end end return true; end --- スターを付ける function on_add_star_menu_item(serialize_key, event_name, data) mz3.logger_debug('on_add_star_menu_item: (' .. serialize_key .. ', ' .. event_name .. ')'); data = MZ3Data:create(data); -- POSTパラメータ生成 post = MZ3PostData:create(); -- tパラメータはメールURLから取得する t = data:get_text('url'); t = t:match('th=(.*)$'); post_body = 'redir=%3F&tact=st&nvp_tbu_go=%E5%AE%9F%E8%A1%8C&t=' .. t .. '&bact='; post:append_post_body(post_body); -- 通信開始 url = data:get_text('post_url'); access_type = mz3.get_access_type_by_key("GMAIL_ADD_STAR"); referer = ''; user_agent = nil; mz3.open_url(mz3_main_view.get_wnd(), access_type, url, referer, "text", user_agent, post.post_data); return true; end --- スターをはずす function on_remove_star_menu_item(serialize_key, event_name, data) mz3.logger_debug('on_remove_star_menu_item: (' .. serialize_key .. ', ' .. event_name .. ')'); data = MZ3Data:create(data); -- POSTパラメータ生成 post = MZ3PostData:create(); -- tパラメータはメールURLから取得する t = data:get_text('url'); t = t:match('th=(.*)$'); post_body = 'redir=%3F&tact=xst&nvp_tbu_go=%E5%AE%9F%E8%A1%8C&t=' .. t .. '&bact='; post:append_post_body(post_body); -- 通信開始 url = data:get_text('post_url'); access_type = mz3.get_access_type_by_key("GMAIL_REMOVE_STAR"); referer = ''; user_agent = nil; mz3.open_url(mz3_main_view.get_wnd(), access_type, url, referer, "text", user_agent, post.post_data); return true; end --- アーカイブする function on_archive_menu_item(serialize_key, event_name, data) mz3.logger_debug('on_archive_menu_item: (' .. serialize_key .. ', ' .. event_name .. ')'); data = MZ3Data:create(data); -- POSTパラメータ生成 post = MZ3PostData:create(); -- tパラメータはメールURLから取得する t = data:get_text('url'); t = t:match('th=(.*)$'); post_body = 'redir=%3F&nvp_a_arch=%83A%81%5b%83J%83C%83u&t=' .. t .. '&bact='; post:append_post_body(post_body); -- 通信開始 url = data:get_text('post_url'); access_type = mz3.get_access_type_by_key("GMAIL_ARCHIVE"); referer = ''; user_agent = nil; mz3.open_url(mz3_main_view.get_wnd(), access_type, url, referer, "text", user_agent, post.post_data); return true; end --- POST 完了イベント -- -- @param event_name 'post_end' -- @param serialize_key 完了項目のシリアライズキー -- @param http_status HTTP Status Code (200, 404, etc...) -- @param filename レスポンスファイル -- @param wnd wnd -- function on_post_end(event_name, serialize_key, http_status, filename) service_type = mz3.get_service_type(serialize_key); if service_type~="gmail" then return false; end -- ステータスコードチェック if http_status~=200 then -- エラーアリなので中断するために true を返す local msg="失敗しました"; mz3.logger_error(msg); mz3_main_view.set_info_text(msg); return true; end -- リクエストの種別に応じてメッセージを表示 if serialize_key == "GMAIL_ADD_STAR" then mz3_main_view.set_info_text("スターつけた!"); end if serialize_key == "GMAIL_REMOVE_STAR" then mz3_main_view.set_info_text("スターとったどー!"); end if serialize_key == "GMAIL_ARCHIVE" then mz3_main_view.set_info_text("アーカイブしたー!"); end return true; end mz3.add_event_listener("post_end", "gmail.on_post_end"); --- レポートビューで開く read_gmail_mail_first = true; function on_read_by_reportview_menu_item(serialize_key, event_name, data) mz3.logger_debug('on_read_by_reportview_menu_item : (' .. serialize_key .. ', ' .. event_name .. ')'); -- メールパーサ内無限ループ対策のため、「メイン画面からの遷移フラグ」を立てておく read_gmail_mail_first = true; data = MZ3Data:create(data); -- 通信開始 url = data:get_text('url'); key = "GMAIL_MAIL"; access_type = mz3.get_access_type_by_key(key); referer = ''; user_agent = nil; post = nil; mz3.open_url(mz3_main_view.get_wnd(), access_type, url, referer, "text", user_agent, post); -- 絵文字ロード後の再ロード用 -- TODO 画面再描画のみにしたい mail_url = url; return true; end --- ボディリストのダブルクリック(またはEnter)のイベントハンドラ function on_body_list_click(serialize_key, event_name, data) if serialize_key=="GMAIL_MAIL" then -- レポートビューで開く return on_read_by_reportview_menu_item(serialize_key, event_name, data); -- ダブルクリックで全文表示したい場合は下記のコメントを外すこと -- 全文表示 -- return on_read_menu_item(serialize_key, event_name, data); end -- 標準の処理を続行 return false; end mz3.add_event_listener("dblclk_body_list", "gmail.on_body_list_click"); mz3.add_event_listener("enter_body_list", "gmail.on_body_list_click"); --- 「ブラウザで開く」メニュー用ハンドラ function on_open_by_browser_menu_item(serialize_key, event_name, data) body = MZ3Data:create(mz3_main_view.get_selected_body_item()); mz3.open_url_by_browser_with_confirm(body:get_text('url')); end --- ボディリストのポップアップメニュー表示 -- -- @param event_name 'popup_body_menu' -- @param serialize_key ボディアイテムのシリアライズキー -- @param body body -- @param wnd wnd -- function on_popup_body_menu(event_name, serialize_key, body, wnd) if serialize_key~="GMAIL_MAIL" then return false; end -- インスタンス化 body = MZ3Data:create(body); -- メニュー生成 menu = MZ3Menu:create_popup_menu(); menu:append_menu("string", "最新の一覧を取得", IDM_CATEGORY_OPEN); menu:append_menu("string", "本文を読む...", menu_items.read_by_reportview); menu:append_menu("string", "ブラウザで開く...", menu_items.open_by_browser); menu:append_menu("separator"); menu:append_menu("string", "スターを付ける...", menu_items.add_star); menu:append_menu("string", "スターをはずす...", menu_items.rmv_star); menu:append_menu("string", "アーカイブ...", menu_items.archive); menu:append_menu("string", "メールを作成...", menu_items.send_mail); menu:append_menu("separator"); menu:append_menu("string", "メールのプロパティ...", menu_items.read); -- ポップアップ menu:popup(wnd); -- メニューリソース削除 menu:delete(); return true; end mz3.add_event_listener("popup_body_menu", "gmail.on_popup_body_menu"); --- レポートビューのポップアップメニュー表示 -- -- @param event_name 'popup_report_menu' -- @param serialize_key レポートアイテムのシリアライズキー -- @param report_item レポートアイテム -- @param sub_item_idx 選択アイテムのインデックス -- @param wnd wnd -- function on_popup_report_menu(event_name, serialize_key, report_item, sub_item_idx, wnd) if serialize_key~="GMAIL_MAIL" then return false; end -- インスタンス化 report_item = MZ3Data:create(report_item); -- メニュー生成 menu = MZ3Menu:create_popup_menu(); menu_edit = MZ3Menu:create_popup_menu(); menu_layout = MZ3Menu:create_popup_menu(); menu:append_menu("string", "戻る", ID_BACK_MENU); menu:append_menu("separator"); menu:append_menu("string", "返信", ID_WRITE_COMMENT); menu:append_menu("string", "再読込", IDM_RELOAD_PAGE); menu_edit:append_menu("string", "コピー", ID_EDIT_COPY); menu:append_submenu("編集", menu_edit); menu:append_menu("string", "ブラウザで開く(このページ)...", ID_OPEN_BROWSER); -- TODO 共通化 menu:append_menu("separator"); menu_layout:append_menu("string", "↑リストを狭くする", IDM_LAYOUT_REPORTLIST_MAKE_NARROW); menu_layout:append_menu("string", "↓リストを広くする", IDM_LAYOUT_REPORTLIST_MAKE_WIDE); menu:append_submenu("画面レイアウト", menu_layout); -- ポップアップ menu:popup(wnd); -- メニューリソース削除 menu:delete(); menu_edit:delete(); menu_layout:delete(); return true; end mz3.add_event_listener("popup_report_menu", "gmail.on_popup_report_menu"); --- レポート画面からの返信時の書き込み種別の判定 -- -- @param event_name 'get_write_view_type_by_report_item_access_type' -- @param report_item [MZ3Data] レポート画面の要素 -- function on_get_write_view_type_by_report_item_access_type(event_name, report_item) report_item = MZ3Data:create(report_item); serialize_key = report_item:get_serialize_key(); service_type = mz3.get_service_type(serialize_key); if service_type=='gmail' then if serialize_key=='GMAIL_MAIL' then return true, mz3.get_access_type_by_key('GMAIL_REPLY'); end end return false; end mz3.add_event_listener("get_write_view_type_by_report_item_access_type", "gmail.on_get_write_view_type_by_report_item_access_type"); --- 書き込み画面の初期化イベント -- -- @param event_name 'init_write_view' -- @param write_view_type 書き込み種別 -- @param write_item [MZ3Data] 書き込み画面の要素 -- -- @return [1] ok true の場合チェーン終了 -- @return [2] is_from_main_view 1 の場合メイン画面に戻る、0 の場合レポート画面に戻る -- @return [3] init_focus 初期フォーカス -- 'body' : 本文から開始 -- 'title' : タイトルから開始 -- @return [4] enable_combo_box 1 の場合コンボボックス有効 -- @return [5] enable_title_change 1 の場合タイトル変更有効 -- function on_init_write_view(event_name, write_view_type, write_item) write_item = MZ3Data:create(write_item); write_view_key = mz3.get_serialize_key_by_access_type(write_view_type); if write_view_key=='GMAIL_REPLY' then -- メール本文|返信 -- タイトル変更:有効化 enable_title_change = 1; -- タイトルの初期値設定 local title = 'Re: ' .. write_item:get_text('title'); mz3_write_view.set_text('title_edit', title); -- 公開範囲コンボボックス:無効 enable_combo_box = 0; -- フォーカス:本文から開始 init_focus = 'body'; -- キャンセル時、レポート画面に戻る is_from_main_view = 0; return true, is_from_main_view, init_focus, enable_combo_box, enable_title_change; elseif write_view_key=='GMAIL_NEW' then -- メール作成 -- タイトル変更:有効化 enable_title_change = 1; -- タイトルの初期値設定 local title = ''; mz3_write_view.set_text('title_edit', ''); -- 公開範囲コンボボックス:無効 enable_combo_box = 0; -- フォーカス:タイトルから開始 init_focus = 'title'; -- キャンセル時、-- メイン画面に戻る is_from_main_view = 1; return true, is_from_main_view, init_focus, enable_combo_box, enable_title_change; end return false; end mz3.add_event_listener("init_write_view", "gmail.on_init_write_view"); --- 書き込み画面で「画像が添付可能なモードか」の判定 -- -- @param event_name 'is_enable_write_view_attach_image_mode' -- @param write_view_type 書き込み種別 -- @param write_item [MZ3Data] 書き込み画面の要素 -- function on_is_enable_write_view_attach_image_mode(event_name, write_view_type, write_item) write_item = MZ3Data:create(write_item); write_view_key = mz3.get_serialize_key_by_access_type(write_view_type); service_type = mz3.get_service_type(write_view_key); if service_type=='gmail' then -- とりあえず添付不可 return true, 0; end return false; end mz3.add_event_listener("is_enable_write_view_attach_image_mode", "gmail.on_is_enable_write_view_attach_image_mode"); --- 書き込み画面の書き込みボタン押下イベント -- -- @param event_name 'click_write_view_send_button' -- @param write_view_type 書き込み種別 -- @param write_item [MZ3Data] 書き込み画面の要素 -- function on_click_write_view_send_button(event_name, write_view_type, write_item) write_item = MZ3Data:create(write_item); write_view_key = mz3.get_serialize_key_by_access_type(write_view_type); service_type = mz3.get_service_type(write_view_key); if service_type=='gmail' then -- 送信処理 local title = mz3_write_view.get_text('title_edit'); local body = mz3_write_view.get_text('body_edit'); if title=='' then mz3.alert('タイトルを入力してください'); return true; end if body=='' then mz3.alert('メール本文を入力して下さい'); return true; end if write_view_key=="GMAIL_REPLY" then -- メール返信処理 local reply_form = write_item:get_text('reply_form'); if reply_form==nil then mz3.alert('返信できません'); return true; end -- <b>To:</b> <input type="hidden" name="qrr" value="o"> xxx@xxx.jp</td> -- <input type="radio" id="reply" name="qrr" value="o" checked> </td> <td colspan="2"> <label for="reply"><b>To:</b> NK &lt;xxx@xxx.jp&gt;</label> </td> local mail_to = reply_form:match('<input type="hidden" name="qrr" value="o".-> ?(.-)</'); if mail_to==nil then mail_to = reply_form:match('<input type="radio" id="reply" name="qrr" value="o".-<b>To:</b> ?(.-)</'); end if mail_to=="" or mail_to==nil then mz3.alert('送信先メールアドレスが取得できませんでした。再度メールを取得して下さい。'); return true; end msg = mz3.decode_html_entity(mail_to) .. ' にメールを送信します。よろしいですか?' .. "\r\n"; msg = msg .. '----' .. "\r\n"; msg = msg .. title .. "\r\n"; -- msg = msg .. '----'; if mz3.confirm(msg, nil, "yes_no") ~= 'yes' then return true; end ------------------------------------------ -- POST パラメータ生成 ------------------------------------------ -- URL 取得 -- <form action="?v=b&qrt=n&..." name="qrf" method="POST"> local url = reply_form:match('<form action="(.-)"'); if url==nil then mz3.alert('返信できません(送信先url取得失敗)'); return true; end url = write_item:get_text('base_url') .. url; --mz3.alert(url); -- hidden 値の収集 local redir = reply_form:match('<input type="hidden" name="redir" value="(.-)"'); redir = redir:gsub('&amp;', '&'); local qrr = reply_form:match('<input type="hidden" name="qrr" value="(.-)"'); if qrr==nil then qrr = 'o'; end -- POSTパラメータ生成 post = MZ3PostData:create(); post:set_content_type('multipart/form-data; boundary=---------------------------7d62ee108071e' .. '\r\n'); -- nvp_bu_send post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="nvp_bu_send"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding('送信', 'sjis', 'utf8') .. '\r\n'); -- redir post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="redir"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding(redir, 'sjis', 'utf8') .. '\r\n'); -- qrr post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="qrr"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding(qrr, 'sjis', 'utf8') .. '\r\n'); -- subject post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="subject"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding(title, 'sjis', 'utf8')); post:append_post_body('\r\n'); -- body post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="body"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding(body, 'sjis', 'utf8')); -- mz3.alert(string.format('%c%c', 0x82, 0xa0)); -- post:append_post_body(string.format('%c%c%c', 0xEE, 0x95, 0x81)); post:append_post_body('\r\n'); -- ucs2 0xE541 = 1110 0101 0100 0001 -- utf8 0xEE9581 = 1110 1110 1001 0101 1000 0001 -- ~~~~ ~~ ~~ -- end of post data post:append_post_body('-----------------------------7d62ee108071e--' .. '\r\n'); -- 通信開始 access_type = mz3.get_access_type_by_key("GMAIL_REPLY"); referer = write_item:get_text('url'); user_agent = nil; mz3.open_url(mz3_write_view.get_wnd(), access_type, url, referer, "text", user_agent, post.post_data); return true; end if write_view_key=="GMAIL_NEW" then -- メール作成 msg = new_mail_info.to .. ' にメールを送信します。よろしいですか?' .. "\r\n"; msg = msg .. '----' .. "\r\n"; msg = msg .. title .. "\r\n"; if mz3.confirm(msg, nil, "yes_no") ~= 'yes' then return true; end -- まずは新規メール作成画面を取得する local url = write_item:get_text('new_mail_url'); if url==nil or url=="" then mz3.alert('メール作成画面のURLが取得できませんでした。再度メール一覧を取得して下さい。'); return true; end -- 通信開始 access_type = mz3.get_access_type_by_key("GMAIL_NEW1"); referer = ''; user_agent = nil; post = nil; mz3.open_url(mz3_write_view.get_wnd(), access_type, url, referer, "text", user_agent, post); return true; end end return false; end mz3.add_event_listener("click_write_view_send_button", "gmail.on_click_write_view_send_button"); --- 書き込み画面の書き込み完了イベント -- -- @param event_name 'get_end_write_view' -- @param write_view_type 書き込み種別 -- @param write_item [MZ3Data] 書き込み画面の要素 -- @param http_status HTTP Status Code (200, 404, etc...) -- @param filename レスポンスファイル -- @param access_type 通信のアクセス種別 -- -- function on_get_end_write_view(event_name, write_view_type, write_item, http_status, filename, access_type) -- GMail メール返信では投稿後にリダイレクトするため get_end になる。 -- CWriteView::OnPostEnd と同様の処理を行う。 write_item = MZ3Data:create(write_item); write_view_key = mz3.get_serialize_key_by_access_type(write_view_type); serialize_key = mz3.get_serialize_key_by_access_type(access_type); service_type = mz3.get_service_type(write_view_key); if service_type~='gmail' then return false; end -- 返信完了チェック if write_view_key == "GMAIL_REPLY" then if http_status==200 then -- 成功 -- メッセージ表示 mz3.alert('メールを返信しました'); -- 初期化 mz3_write_view.set_text('title_edit', ''); mz3_write_view.set_text('body_edit', ''); -- 前の画面に戻る mz3.change_view('main_view'); else -- 失敗 mz3.logger_error('失敗:' .. http_status); mz3.alert('投稿に失敗しました。'); -- TODO バックアップ end return true; end -- メール送信 if serialize_key == "GMAIL_NEW" then if http_status==200 then -- 成功 -- メッセージ表示 mz3.alert('メールを送信しました'); -- 初期化 mz3_write_view.set_text('title_edit', ''); mz3_write_view.set_text('body_edit', ''); -- 前の画面に戻る mz3.change_view('main_view'); else -- 失敗 mz3.logger_error('失敗:' .. http_status); mz3.alert('投稿に失敗しました。'); -- TODO バックアップ end return true; end -- メール作成画面:メール送信開始 if serialize_key == "GMAIL_NEW1" then if http_status==200 then -- 成功 -- 本文取得 local f = io.open(filename, 'r'); local file = f:read('*a'); f:close(); -- 送信用POST値(hidden)を含むformを取得する -- <base href="https://mail.google.com/mail/h/xxx/"> base_url = file:match('<base href="(.-)">'); -- フォーム取得(2つあるフォームをname="f"で識別) --[[ <form action="?v=b&fv=b&cpt=c&at=xxx&pv=tl&cs=c" name="f" enctype="multipart/form-data" method="POST"> ... </form> ]] send_form = file:match('<form action="[^"]+" name="f".-</form>'); -- mz3.alert(send_form); -- URL 取得 -- <form action="?v=b&fv=b&cpt=c&at=xxx&pv=tl&cs=c" name="f" enctype="multipart/form-data" method="POST"> local url = send_form:match('<form action="(.-)"'); if url==nil then mz3.alert('メール送信できません(送信先url取得失敗)'); return true; end url = base_url .. url; -- mz3.alert(url); -- ユーザ入力値取得 local title = mz3_write_view.get_text('title_edit'); local body = mz3_write_view.get_text('body_edit'); -- hidden 値の収集 local redir = send_form:match('<input type="hidden" name="redir" value="(.-)"'); redir = redir:gsub('&amp;', '&'); -- POSTパラメータ生成 post = MZ3PostData:create(); post:set_content_type('multipart/form-data; boundary=---------------------------7d62ee108071e' .. '\r\n'); -- nvp_bu_send post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="nvp_bu_send"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding('送信', 'sjis', 'utf8') .. '\r\n'); -- redir post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="redir"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding(redir, 'sjis', 'utf8') .. '\r\n'); -- to post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="to"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding(new_mail_info.to, 'sjis', 'utf8') .. '\r\n'); -- TODO cc post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="cc"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding("", 'sjis', 'utf8') .. '\r\n'); -- TODO bcc post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="bcc"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding("", 'sjis', 'utf8') .. '\r\n'); -- TODO file0 -- subject post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="subject"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding(title, 'sjis', 'utf8')); post:append_post_body('\r\n'); -- body post:append_post_body('-----------------------------7d62ee108071e' .. '\r\n'); post:append_post_body('Content-Disposition: form-data; name="body"' .. '\r\n'); post:append_post_body('\r\n'); post:append_post_body(mz3.convert_encoding(body, 'sjis', 'utf8')); post:append_post_body('\r\n'); -- end of post data post:append_post_body('-----------------------------7d62ee108071e--' .. '\r\n'); -- 通信開始 access_type = mz3.get_access_type_by_key("GMAIL_NEW"); referer = write_item:get_text('url'); user_agent = nil; mz3.open_url(mz3_write_view.get_wnd(), access_type, url, referer, "text", user_agent, post.post_data); return true; else -- 失敗 mz3.logger_error('失敗:' .. http_status); mz3.alert('メール作成画面の取得に失敗しました。再度リトライしてください。'); -- TODO バックアップ end return true; end return false; end mz3.add_event_listener("get_end_write_view", "gmail.on_get_end_write_view"); --- 書き込み画面のポップアップメニュー表示(他画面と違い追加形式となる点に注意) -- -- @param event_name 'popup_write_menu' -- @param serialize_key 書き込み種別のシリアライズキー -- @param write_item 書き込み画面のデータ -- @param menu メニュー -- function on_popup_write_menu(event_name, serialize_key, write_item, menu) service_type = mz3.get_service_type(serialize_key); if service_type~='gmail' then return false; end if serialize_key == "GMAIL_NEW" then -- メニュー変更 menu = MZ3Menu:create_popup_menu(menu); menu:append_menu("separator"); menu:append_menu("string", "送信先変更 (" .. new_mail_info.to .. ")", menu_items.change_to_address); end return true; end mz3.add_event_listener("popup_write_menu", "gmail.on_popup_write_menu"); --- TO アドレス変更 function on_change_to_address(serialize_key, event_name, data) mz3.logger_debug('on_change_to_address: (' .. serialize_key .. ', ' .. event_name .. ')'); -- 送信先アドレス取得 do_input_to_address(); return true; end mz3.logger_debug('gmail.lua end');
bsd-3-clause
fgenesis/Aquaria_experimental
game_scripts/scripts/entities/creatorform4.lua
6
13626
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end -- ================================================================================================ -- C R E A T O R , F O R M 4 (beta) -- ================================================================================================ -- ================================================================================================ -- L O C A L V A R I A B L E S -- ================================================================================================ v.n = 0 v.bone_body = 0 v.bone_darkLi = 0 v.hits1 = 4 v.hits2 = 2 v.lureNode = 1 v.lastNodeNum = 0 v.hideCount = v.hits1 v.maxSpeed = 505 v.chaseRange = 690 v.attackRange = 489 v.waitToAttack = 0 v.hitNaija = 0 -- ================================================================================================ -- S T A T E S -- ================================================================================================ local STATE_TRAP = 1000 local STATE_PAIN = 1001 local STATE_ATTACK = 1002 local STATE_LUREWAIT = 1003 local STATE_INTRO = 1004 local STATE_CHASE = 1005 local STATE_CREEP = 1006 -- ================================================================================================ -- P H A S E S -- ================================================================================================ v.phase = 0 local PHASE_LURE = 0 local PHASE_HIDE = 1 local PHASE_FINAL = 2 -- ================================================================================================ -- F U N C T I O N S -- ================================================================================================ function init(me) setupEntity(me) entity_setEntityType(me, ET_ENEMY) entity_initSkeletal(me, "CreatorForm4") v.bone_body = entity_getBoneByName(me, "Body") v.bone_darkLi = entity_getBoneByName(me, "DarkLi") v.bone_leftHand = entity_getBoneByName(me, "LeftHand") v.bone_rightHand = entity_getBoneByName(me, "RightHand") v.bone_leftLeg1 = entity_getBoneByName(me, "LeftLowerLeg1") v.bone_leftLeg2 = entity_getBoneByName(me, "LeftLowerLeg2") v.bone_rightLeg1 = entity_getBoneByName(me, "RightLowerLeg1") v.bone_rightLeg2 = entity_getBoneByName(me, "RightLowerLeg2") entity_generateCollisionMask(me) entity_setAllDamageTargets(me, true) entity_setBeautyFlip(me, false) esetv(me, EV_FLIPTOPATH, 0) entity_setCullRadius(me, 700) loadSound("CreatorForm4-Hit1") loadSound("CreatorForm4-Hit2") loadSound("CreatorForm4-Die") loadSound("creatorform4-bite") esetv(me, EV_MINIMAP, 1) entity_setDamageTarget(me, DT_AVATAR_PET, false) end function postInit(me) entity_setState(me, STATE_INTRO) v.n = getNaija() entity_setTarget(me, v.n) playSfx("CreatorForm4-Die") fadeOutMusic(6) end function update(me, dt) overrideZoom(0.60) entity_updateMovement(me, dt) if entity_isState(me, STATE_IDLE) then entity_setState(me, STATE_MOVE) end if entity_isState(me, STATE_MOVE) then entity_setAnimLayerTimeMult(me, 0, 1.89) end if entity_isState(me, STATE_MOVE) and not entity_isFollowingPath(me) then entity_setStateTime(me, 0.1) end if entity_isState(me, STATE_LUREWAIT) then entity_rotateToEntity(me, v.n, 0.1) if entity_isEntityInRange(me, v.n, 543) then entity_setState(me, STATE_MOVE) end end -- WAITING FOR NAIJA AT A NODE if entity_isState(me, STATE_TRAP) then -- FACE NAIJA if entity_isEntityInRange(me, v.n, 1234) then entity_rotateToEntity(me, v.n, 0.23) end -- ATTAAAACK if entity_isEntityInRange(me, v.n, 543) and v.waitToAttack == 1 then entity_setState(me, STATE_ATTACK) end if entity_isEntityInRange(me, v.n, v.attackRange) then entity_setState(me, STATE_ATTACK) -- CHASE elseif entity_isEntityInRange(me, v.n, v.chaseRange) and v.waitToAttack == 0 then entity_setState(me, STATE_CHASE) end end if entity_isState(me, STATE_ATTACK) then entity_rotateToEntity(me, v.n, 1) end if entity_isState(me, STATE_CHASE) then if entity_isEntityInRange(me, v.n, 210) then entity_setState(me, STATE_TRAP) end --overrideZoom(0.67) entity_setAnimLayerTimeMult(me, 0, 0.72) entity_moveTowards(me, entity_x(v.n), entity_y(v.n), dt, 432) entity_rotateToEntity(me, v.n, 0.21) elseif entity_isState(me, STATE_CREEP) then entity_setAnimLayerTimeMult(me, 0, 0.64) entity_moveTowards(me, entity_x(v.n), entity_y(v.n), dt, 323) entity_rotateToEntity(me, v.n, 0.34) else if entity_getVelLen(me) <= 234 then entity_clearVel(me) entity_setMaxSpeed(me, 0) end end -- AVOID WALLS entity_doCollisionAvoidance(me, dt, 8, 0.32) local vecX, vecY = entity_getPosition(me) local wallX, wallY = getWallNormal(entity_x(me), entity_y(me), 12) if wallX ~= 0 or wallY ~= 0 then vecX = vecX + wallX*256 vecY = vecY + wallY*256 entity_moveTowards(me, vecX, vecY, dt, 248) end entity_doFriction(me, dt, 234) -- COLLISIONS entity_handleShotCollisionsSkeletal(me) local bone = entity_collideSkeletalVsCircle(me, v.n) if bone ~= 0 then -- BITE NAIJA if entity_isState(me, STATE_ATTACK) then entity_touchAvatarDamage(me, 0, 1, 800) v.hitNaija = 1 --BUMP NAIJA else entity_touchAvatarDamage(me, 0, 0.1, 321) end end if not entity_isState(me, STATE_INTRO) then local r = entity_getDistanceToEntity(me, v.n) if r < 800 then musicVolume(1, 0.1) else r = 1 - ((r-800) / 1024) if r < 0.3 then r = 0.3 end if r > 1 then r = 1 end musicVolume(r) end end end function enterState(me) if entity_isState(me, STATE_IDLE) then entity_animate(me, "idle", LOOP_INF) entity_setAnimLayerTimeMult(me, 0, 1) elseif entity_isState(me, STATE_MOVE) then shakeCamera(3.4, 2.3) entity_animate(me, "crawl", LOOP_INF) local node = 0 local nodeName = "" -- MOVING BETWEEN NODES w/ PATHFINDING if v.phase == PHASE_LURE then nodeName = string.format("L%d", v.lureNode) elseif v.phase == PHASE_HIDE then local rnd = math.random(9) while rnd == v.lastNodeNum do -- While loops are scary rnd = math.random(9) end nodeName = string.format("W%d", rnd) v.lastNodeNum = rnd elseif v.phase == PHASE_FINAL then nodeName = "WFINAL" local door node = getNode("LIDOOR") door = node_getNearestEntity(node, "FinalDoor") entity_setState(door, STATE_OPENED, -1, 1) node = getNode("LIDOOR2") door = node_getNearestEntity(node, "FinalDoor") entity_setState(door, STATE_OPENED, -1, 1) playSfx("TentacleDoor") playSfx("CreatorForm4-hit1") end node = entity_getNearestNode(me, nodeName) entity_swimToNode(me, node, SPEED_FAST2) elseif entity_isState(me, STATE_TRAP) then entity_setMaxSpeed(me, v.maxSpeed/8) entity_animate(me, "idle", LOOP_INF) elseif entity_isState(me, STATE_ATTACK) then entity_setStateTime(me, entity_animate(me, "attack")) v.waitToAttack = 0 v.hitNaija = 0 elseif entity_isState(me, STATE_CHASE) then entity_setMaxSpeed(me, v.maxSpeed) local stateTime = 1.56 shakeCamera(2.3, stateTime) entity_animate(me, "crawl", LOOP_INF) entity_setStateTime(me, stateTime) elseif entity_isState(me, STATE_CREEP) then entity_setMaxSpeed(me, v.maxSpeed/2) local stateTime = 1.2 shakeCamera(2.1, stateTime) entity_animate(me, "crawl", LOOP_INF) entity_setStateTime(me, stateTime) elseif entity_isState(me, STATE_PAIN) then if chance(50) then playSfx("CreatorForm4-Hit1") else playSfx("CreatorForm4-Hit2") end entity_setStateTime(me, entity_animate(me, "pain")) elseif entity_isState(me, STATE_TRANSITION) then playSfx("CreatorForm4-Die") local lastNode = getNode("WFINAL") entity_stopInterpolating() entity_setPosition(me, node_x(lastNode), node_y(lastNode)) entity_setPosition(me, node_x(lastNode), node_y(lastNode), 1) entity_animate(me, "idle", LOOP_INF) entity_rotate(me, 0, 1,0,0,1) entity_setStateTime(me, 1) entity_idle(v.n) disableInput() cam_toEntity(me) elseif entity_isState(me, STATE_INTRO) then entity_scale(me, 0, 0) entity_scale(me, 1, 1, 3) entity_animate(me, "idle") entity_setStateTime(me, 3) playMusic("worship3") end end function exitState(me) if entity_isState(me, STATE_MOVE) then debugLog("move state ended") if v.phase == PHASE_LURE then v.lureNode = v.lureNode + 1 if v.lureNode > 7 then v.phase = PHASE_HIDE entity_setState(me, STATE_MOVE) else entity_setState(me, STATE_LUREWAIT) end elseif v.phase == PHASE_HIDE then if v.hideCount <= 0 then entity_setState(me, STATE_TRAP) v.waitToAttack = 1 v.hideCount = 0 else v.hideCount = v.hideCount - 1 entity_setState(me, STATE_MOVE) end elseif v.phase == PHASE_FINAL then entity_setState(me, STATE_TRAP) v.waitToAttack = 1 end elseif entity_isState(me, STATE_PAIN) then if v.phase == PHASE_HIDE then v.hideCount = 4 entity_setState(me, STATE_MOVE) else entity_setState(me, STATE_TRAP) end elseif entity_isState(me, STATE_IDLE) then entity_setState(me, STATE_MOVE) elseif entity_isState(me, STATE_ATTACK) then -- POST ATTACK, MOVE OR HANG BACK? if v.hitNaija == 0 and entity_isEntityInRange(me, v.n, v.attackRange) then entity_setState(me, STATE_CREEP) elseif v.hitNaija == 0 then entity_setState(me, STATE_CHASE) else entity_setState(me, STATE_TRAP) end elseif entity_isState(me, STATE_CHASE) then if entity_isEntityInRange(me, v.n, v.chaseRange) then entity_setState(me, STATE_ATTACK) else entity_setState(me, STATE_TRAP) end elseif entity_isState(me, STATE_CREEP) then entity_setState(me, STATE_ATTACK) elseif entity_isState(me, STATE_TRANSITION) then entity_idle(v.n) enableInput() cam_toEntity(v.n) local bx, by = bone_getWorldPosition(v.bone_darkLi) createEntity("CreatorForm5", "", bx, by) entity_alpha(me, 0.6, 3) entity_setState(me, STATE_WAIT, 6) elseif entity_isState(me, STATE_WAIT) then entity_delete(me, 1) elseif entity_isState(me, STATE_INTRO) then entity_setState(me, STATE_MOVE) end end function damage(me, attacker, bone, damageType, dmg) if v.phase == PHASE_LURE then return false end if entity_isState(me, STATE_PAIN) then return false end if bone == v.bone_body then bone_damageFlash(bone) if v.hits1 > 0 then v.hits1 = v.hits1 - 1 --dmg? if v.hits1 <= 0 then v.phase = PHASE_FINAL entity_setState(me, STATE_MOVE) else entity_setState(me, STATE_PAIN) end elseif v.hits2 > 0 then v.hits2 = v.hits2 - 1 --dmg? if v.hits2 <= 0 then entity_setState(me, STATE_TRANSITION) else entity_setState(me, STATE_PAIN) end end end return false end function animationKey(me, key) if entity_isState(me, STATE_MOVE) or entity_isState(me, STATE_CHASE) or entity_isState(me, STATE_CREEP) then if key == 1 then local hX, hY = bone_getWorldPosition(v.bone_rightHand) spawnParticleEffect("CreatorForm4HandDust", hX, hY) hX, hY = bone_getWorldPosition(v.bone_leftHand) spawnParticleEffect("CreatorForm4FootDust", hX, hY) hX, hY = bone_getWorldPosition(v.bone_leftLeg1) spawnParticleEffect("CreatorForm4FootDust", hX, hY) hX, hY = bone_getWorldPosition(v.bone_leftLeg2) spawnParticleEffect("CreatorForm4FootDust", hX, hY) entity_sound(me, "RockHit") elseif key == 3 then local hX, hY = bone_getWorldPosition(v.bone_leftHand) spawnParticleEffect("CreatorForm4HandDust", hX, hY) hX, hY = bone_getWorldPosition(v.bone_rightHand) spawnParticleEffect("CreatorForm4FootDust", hX, hY) hX, hY = bone_getWorldPosition(v.bone_rightLeg1) spawnParticleEffect("CreatorForm4FootDust", hX, hY) hX, hY = bone_getWorldPosition(v.bone_rightLeg2) spawnParticleEffect("CreatorForm4FootDust", hX, hY) entity_sound(me, "RockHit") end elseif entity_isState(me, STATE_ATTACK) then if key == 3 then local hX, hY = bone_getWorldPosition(v.bone_leftHand) spawnParticleEffect("CreatorForm4FootDust", hX, hY) hX, hY = bone_getWorldPosition(v.bone_rightHand) spawnParticleEffect("CreatorForm4FootDust", hX, hY) hX, hY = bone_getWorldPosition(v.bone_leftLeg1) spawnParticleEffect("CreatorForm4FootDust", hX, hY) hX, hY = bone_getWorldPosition(v.bone_leftLeg2) spawnParticleEffect("CreatorForm4FootDust", hX, hY) hX, hY = bone_getWorldPosition(v.bone_rightLeg1) spawnParticleEffect("CreatorForm4FootDust", hX, hY) hX, hY = bone_getWorldPosition(v.bone_rightLeg2) spawnParticleEffect("CreatorForm4FootDust", hX, hY) entity_sound(me, "creatorform4-bite") end end end function hitSurface(me) end function songNote(me, note) end function songNoteDone(me, note) end function song(me, song) end function activate(me) end
gpl-2.0
dickeyf/darkstar
scripts/zones/Ceizak_Battlegrounds/npcs/HomePoint#1.lua
27
1286
----------------------------------- -- Area: Ceizak Battlegrounds -- NPC: HomePoint#1 -- @pos -107 3.2 295 261 ----------------------------------- package.loaded["scripts/zones/Ceizak_Battlegrounds/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Ceizak_Battlegrounds/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 46); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
Turttle/darkstar
scripts/zones/Valkurm_Dunes/npcs/Stone_Monument.lua
32
1285
----------------------------------- -- Area: Valkurm Dunes -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos -311.299 -4.420 -138.878 103 ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Valkurm_Dunes/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x00008); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Turttle/darkstar
scripts/zones/Altar_Room/Zone.lua
28
1623
----------------------------------- -- -- Zone: Altar_Room (152) -- ----------------------------------- package.loaded["scripts/zones/Altar_Room/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Altar_Room/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-247.998,12.609,-100.008,128); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
dickeyf/darkstar
scripts/globals/items/pestle.lua
41
1123
----------------------------------------- -- ID: 18599 -- Item: Pestle -- Additional effect: MP Drain ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance or target:isUndead()) then return 0,0,0; else local drain = math.random(2,8); local params = {}; params.bonusmab = 0; params.includemab = false; -- drain = addBonusesAbility(player, ELE_DARK, target, drain, params); drain = drain * applyResistanceAddEffect(player,target,ELE_DARK,0); drain = adjustForTarget(target,drain,ELE_DARK); drain = finalMagicNonSpellAdjustments(player,target,ELE_DARK,drain); if (drain > target:getMP()) then drain = target:getMP(); end target:addMP(-drain); return SUBEFFECT_MP_DRAIN, MSGBASIC_ADD_EFFECT_MP_DRAIN, player:addMP(drain); end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c73752131.lua
3
2015
--熟練の黒魔術師 function c73752131.initial_effect(c) c:EnableCounterPermit(0x1) c:SetCounterLimit(0x1,3) --add counter local e0=Effect.CreateEffect(c) e0:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD) e0:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e0:SetCode(EVENT_CHAINING) e0:SetRange(LOCATION_MZONE) e0:SetOperation(aux.chainreg) c:RegisterEffect(e0) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD) e1:SetCode(EVENT_CHAIN_SOLVED) e1:SetRange(LOCATION_MZONE) e1:SetOperation(c73752131.acop) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(73752131,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCost(c73752131.spcost) e2:SetTarget(c73752131.sptg) e2:SetOperation(c73752131.spop) c:RegisterEffect(e2) end function c73752131.acop(e,tp,eg,ep,ev,re,r,rp) if re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:IsActiveType(TYPE_SPELL) and e:GetHandler():GetFlagEffect(1)>0 then e:GetHandler():AddCounter(0x1,1) end end function c73752131.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetCounter(0x1)==3 and e:GetHandler():IsReleasable() end Duel.Release(e:GetHandler(),REASON_COST) end function c73752131.filter(c,e,tp) return c:IsCode(46986414) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c73752131.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 and Duel.IsExistingMatchingCard(c73752131.filter,tp,0x13,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,0,tp,0x13) end function c73752131.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c73752131.filter),tp,0x13,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
dickeyf/darkstar
scripts/globals/items/bowl_of_ulbuconut_milk.lua
18
1192
----------------------------------------- -- ID: 5976 -- Item: Bowl of Ulbuconut Milk -- Food Effect: 3Min, All Races ----------------------------------------- -- Charisma +3 -- Vitality -2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,180,5976); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_CHR, 3); target:addMod(MOD_VIT, -2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_CHR, 3); target:delMod(MOD_VIT, -2); end;
gpl-3.0
JackS9/iot
lua_examples/thebutton/init.lua
1
10539
print("WIFI control") -- put module in AP mode wifi.setmode(wifi.SOFTAP) print("ESP8266 mode is: " .. wifi.getmode()) cfg={} -- Set the SSID of the module in AP mode and access password cfg.ssid="ESP_STATION" cfg.pwd="it" if ssid and password then print("ESP8266 SSID is: " .. cfg.ssid .. " and PASSWORD is: " .. cfg.password) end -- Now you should see an SSID wireless router named ESP_STATION when you scan for available WIFI networks -- Lets connect to the module from a computer of mobile device. So, find the SSID and connect using the password selected wifi.ap.config(cfg) ap_mac = wifi.ap.getmac() -- create a server on port 80 and wait for a connection, when a connection is coming in function c will be executed sv=net.createServer(net.TCP,30) sv:listen(80,function(c) c:on("receive", function(c, pl) -- print the payload pl received from the connection print(pl) print(string.len(pl)) -- wait until SSID comes back and parse the SSID and the password print(string.match(pl,"GET")) ssid_start,ssid_end=string.find(pl,"SSID=") if ssid_start and ssid_end then amper1_start, amper1_end =string.find(pl,"&", ssid_end+1) if amper1_start and amper1_end then http_start, http_end =string.find(pl,"HTTP/1.1", ssid_end+1) if http_start and http_end then ssid=string.sub(pl,ssid_end+1, amper1_start-1) password=string.sub(pl,amper1_end+10, http_start-2) print("ESP8266 connecting to SSID: " .. ssid .. " with PASSWORD: " .. password) if ssid and password then sv:close() -- close the server and set the module to STATION mode wifi.setmode(wifi.STATIONAP) print("ESP8266 mode now is: " .. wifi.getmode()) -- configure the module wso it can connect to the network using the received SSID and password wifi.sta.config(ssid,password) print("Setting up ESP8266 for station mode…Please wait.") tmr.delay(10000000) print("ESP8266 STATION IP now is: " .. wifi.sta.getip()) print("ESP8266 AP IP now is: " .. wifi.ap.getip()) -- now the module is configured and connected to the network so lets start setting things up for the control logic --gpio.mode(8,gpio.OUTPUT) gpio.mode(4,gpio.OUTPUT) gpio.write(4,gpio.HIGH) --tmr.delay(10) --gpio.write(8,gpio.HIGH) --tmr.delay(10) --gpio.write(8,gpio.LOW) sv=net.createServer(net.TCP, 30) sv:listen(9999,function(c) c:on("receive", function(c, pl) if tonumber(pl) ~= nil then if tonumber(pl) >= 1 and tonumber(pl) <= 16 then print(tonumber(pl)) --tmr.delay(10) --gpio.write(8,gpio.HIGH) --tmr.delay(10) --gpio.write(8,gpio.LOW) for count =1,tonumber(pl) do print(count) tmr.delay(10) gpio.write(4,gpio.LOW) tmr.delay(10) gpio.write(4,gpio.HIGH) c:send("Sequence finished") end end end print("ESP8266 STATION IP now is: " .. new_ip) c:send("ESP8266 STATION IP now is: " .. new_ip) c:send("Action completed") end) end) end end end end -- this is the web page that requests the SSID and password from the user c:send("<!DOCTYPE html> ") c:send("<html> ") c:send("<body> ") c:send("<h1>ESP8266 Wireless control setup</h1>") mac_mess1 = "The module MAC address is: " .. ap_mac mac_mess2 = "You will need this MAC address to find the IP address of the module, please take note of it." c:send("<h2>" .. mac_mess1 .. "</h2>") c:send("<h2>" .. mac_mess2 .. "</h2>") c:send("<h2>Enter SSID and Password for your WIFI router</h2>") c:send("</form> </html>") c:send("<form action='' method='get'>") c:send("SSID:") c:send("<input type='text' name='SSID' value='' maxlength='100'/>") c:send("<br/>") c:send("Password:") c:send("<input type='text' name='Password' value='' maxlength='100'/>") c:send("<input type='submit' value='Submit' />") end) end)
gpl-2.0
Turttle/darkstar
scripts/zones/Bastok_Mines/npcs/Abd-al-Raziq.lua
42
2636
----------------------------------- -- Area: Bastok Mines -- NPC: Abd-al-Raziq -- Type: Alchemy Guild Master -- @pos 126.768 1.017 -0.234 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILL_ALCHEMY); if (newRank ~= 0) then player:setSkillRank(SKILL_ALCHEMY,newRank); player:startEvent(0x0079,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILL_ALCHEMY); local testItem = getTestItem(player,npc,SKILL_ALCHEMY); local guildMember = isGuildMember(player,1); if (guildMember == 1) then guildMember = 150995375; end if (canGetNewRank(player,craftSkill,SKILL_ALCHEMY) == 1) then getNewRank = 100; end if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD and guildMember == 150995375 and getNewRank ~= 100) then local item = 0; local asaStatus = player:getVar("ASA_Status"); -- TODO: Other Enfeebling Kits if (asaStatus == 0) then item = 2779; else printf("Error: Unknown ASA Status Encountered <%u>", asaStatus); end -- The Parameters are Item IDs for the Recipe player:startEvent(0x024e, item, 2774, 929, 4103, 2777, 4103); else player:startEvent(0x0078,testItem,getNewRank,30,guildMember,44,0,0,0); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0078 and option == 1) then local crystal = math.random(4096,4101); if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal); else player:addItem(crystal); player:messageSpecial(ITEM_OBTAINED,crystal); signupGuild(player,SKILL_ALCHEMY); end end end;
gpl-3.0
erictheredsu/eric_git
MGCN/wow/WTF/Account/AAAA/SavedVariables/Blizzard_CombatLog.lua
2
23592
Blizzard_CombatLog_Filters = { ["filters"] = { { ["quickButtonName"] = "自己", ["onQuickBar"] = true, ["quickButtonDisplay"] = { ["party"] = true, ["solo"] = true, ["raid"] = true, }, ["tooltip"] = "显示你所进行的动作和你受到的动作的信息。", ["name"] = "自己", ["colors"] = { ["schoolColoring"] = { { ["a"] = 1, ["b"] = 0, ["g"] = 1, ["r"] = 1, }, -- [1] { ["a"] = 1, ["b"] = 0.5, ["g"] = 0.9, ["r"] = 1, }, -- [2] nil, -- [3] { ["a"] = 1, ["b"] = 0, ["g"] = 0.5, ["r"] = 1, }, -- [4] [16] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 0.5, }, [64] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.5, ["r"] = 1, }, [32] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.5, ["r"] = 0.5, }, [8] = { ["a"] = 1, ["b"] = 0.3, ["g"] = 1, ["r"] = 0.3, }, [0] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 1, }, }, ["eventColoring"] = { }, ["highlightedEvents"] = { ["PARTY_KILL"] = true, }, ["defaults"] = { ["damage"] = { ["a"] = 1, ["b"] = 0, ["g"] = 1, ["r"] = 1, }, ["spell"] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 1, }, }, ["unitColoring"] = { [17681] = { ["a"] = 1, ["b"] = 0.7, ["g"] = 0.7, ["r"] = 0.7, }, [32334] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [2147483648] = { ["a"] = 1, ["b"] = 0.75, ["g"] = 0.75, ["r"] = 0.75, }, [12561] = { ["a"] = 1, ["b"] = 0.7, ["g"] = 0.7, ["r"] = 0.7, }, [32078] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [32558] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [32542] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.64, ["r"] = 0.34, }, }, }, ["settings"] = { ["abilityHighlighting"] = true, ["lineColoring"] = true, ["spellBraces"] = false, ["sourceColoring"] = true, ["showHistory"] = true, ["destColoring"] = true, ["amountHighlighting"] = true, ["schoolNameColoring"] = false, ["abilitySchoolColoring"] = false, ["sourceBraces"] = true, ["missColoring"] = true, ["itemBraces"] = true, ["abilityColoring"] = false, ["amountActorColoring"] = false, ["textMode"] = "A", ["destBraces"] = true, ["timestamp"] = false, ["actionColoring"] = false, ["fullText"] = true, ["lineColorPriority"] = 1, ["lineHighlighting"] = true, ["abilityActorColoring"] = false, ["actionHighlighting"] = false, ["schoolNameActorColoring"] = false, ["schoolNameHighlighting"] = true, ["unitBraces"] = true, ["noMeleeSwingColoring"] = false, ["unitIcons"] = true, ["hideDebuffs"] = false, ["amountSchoolColoring"] = false, ["amountColoring"] = false, ["unitColoring"] = false, ["hideBuffs"] = false, ["timestampFormat"] = "%H:%M:%S", ["braces"] = false, ["actionActorColoring"] = false, }, ["hasQuickButton"] = true, ["filters"] = { { ["eventList"] = { ["SPELL_PERIODIC_MISSED"] = true, ["SPELL_INTERRUPT"] = true, ["UNIT_DESTROYED"] = true, ["SPELL_LEECH"] = true, ["SPELL_AURA_BROKEN"] = true, ["UNIT_DIED"] = true, ["SPELL_PERIODIC_ENERGIZE"] = true, ["SPELL_INSTAKILL"] = true, ["SPELL_PERIODIC_DAMAGE"] = true, ["SPELL_PERIODIC_HEAL"] = true, ["PARTY_KILL"] = true, ["SPELL_DAMAGE"] = true, ["RANGE_DAMAGE"] = true, ["ENVIRONMENTAL_DAMAGE"] = true, ["SPELL_DISPEL"] = true, ["SPELL_EXTRA_ATTACKS"] = true, ["SPELL_MISSED"] = true, ["SPELL_STOLEN"] = true, ["SPELL_ENERGIZE"] = true, ["SWING_MISSED"] = true, ["SPELL_AURA_REFRESH"] = true, ["SPELL_AURA_REMOVED_DOSE"] = true, ["SPELL_PERIODIC_LEECH"] = true, ["SPELL_AURA_APPLIED"] = true, ["ENCHANT_REMOVED"] = true, ["SPELL_AURA_APPLIED_DOSE"] = true, ["SWING_DAMAGE"] = true, ["SPELL_AURA_BROKEN_SPELL"] = true, ["SPELL_AURA_REMOVED"] = true, ["RANGE_MISSED"] = true, ["SPELL_HEAL"] = true, ["SPELL_DISPEL_FAILED"] = true, ["ENCHANT_APPLIED"] = true, ["SPELL_PERIODIC_DRAIN"] = true, ["SPELL_DRAIN"] = true, }, ["sourceFlags"] = { [17681] = true, [12561] = true, }, }, -- [1] { ["destFlags"] = { [17681] = true, [12561] = true, }, ["eventList"] = { ["SPELL_EXTRA_ATTACKS"] = true, ["SPELL_MISSED"] = true, ["SPELL_STOLEN"] = true, ["SPELL_ENERGIZE"] = true, ["SPELL_INTERRUPT"] = true, ["UNIT_DESTROYED"] = true, ["SPELL_LEECH"] = true, ["UNIT_DIED"] = true, ["ENCHANT_APPLIED"] = true, ["SPELL_DISPEL_FAILED"] = true, ["SPELL_INSTAKILL"] = true, ["SWING_MISSED"] = true, ["SWING_DAMAGE"] = true, ["PARTY_KILL"] = true, ["SPELL_DAMAGE"] = true, ["RANGE_MISSED"] = true, ["RANGE_DAMAGE"] = true, ["ENCHANT_REMOVED"] = true, ["SPELL_HEAL"] = true, ["SPELL_DISPEL"] = true, ["SPELL_DRAIN"] = true, }, }, -- [2] }, }, -- [1] { ["quickButtonName"] = "所有", ["onQuickBar"] = true, ["quickButtonDisplay"] = { ["party"] = true, ["solo"] = true, ["raid"] = true, }, ["tooltip"] = "显示所有战斗信息。", ["name"] = "所有", ["colors"] = { ["schoolColoring"] = { { ["a"] = 1, ["b"] = 0, ["g"] = 1, ["r"] = 1, }, -- [1] { ["a"] = 1, ["b"] = 0.5, ["g"] = 0.9, ["r"] = 1, }, -- [2] nil, -- [3] { ["a"] = 1, ["b"] = 0, ["g"] = 0.5, ["r"] = 1, }, -- [4] [16] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 0.5, }, [64] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.5, ["r"] = 1, }, [32] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.5, ["r"] = 0.5, }, [8] = { ["a"] = 1, ["b"] = 0.3, ["g"] = 1, ["r"] = 0.3, }, [0] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 1, }, }, ["eventColoring"] = { }, ["highlightedEvents"] = { ["PARTY_KILL"] = true, }, ["defaults"] = { ["damage"] = { ["a"] = 1, ["b"] = 0, ["g"] = 1, ["r"] = 1, }, ["spell"] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 1, }, }, ["unitColoring"] = { [17681] = { ["a"] = 1, ["b"] = 0.7, ["g"] = 0.7, ["r"] = 0.7, }, [32334] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [2147483648] = { ["a"] = 1, ["b"] = 0.75, ["g"] = 0.75, ["r"] = 0.75, }, [12561] = { ["a"] = 1, ["b"] = 0.7, ["g"] = 0.7, ["r"] = 0.7, }, [32078] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [32558] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [32542] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.64, ["r"] = 0.34, }, }, }, ["settings"] = { ["abilityHighlighting"] = true, ["lineColoring"] = true, ["spellBraces"] = false, ["sourceColoring"] = true, ["showHistory"] = true, ["destColoring"] = true, ["amountHighlighting"] = true, ["schoolNameColoring"] = false, ["abilitySchoolColoring"] = false, ["sourceBraces"] = true, ["missColoring"] = true, ["itemBraces"] = true, ["abilityColoring"] = false, ["amountActorColoring"] = false, ["textMode"] = "A", ["destBraces"] = true, ["timestamp"] = false, ["actionColoring"] = false, ["fullText"] = true, ["lineColorPriority"] = 1, ["lineHighlighting"] = true, ["abilityActorColoring"] = false, ["actionHighlighting"] = false, ["schoolNameActorColoring"] = false, ["schoolNameHighlighting"] = true, ["unitBraces"] = true, ["noMeleeSwingColoring"] = false, ["unitIcons"] = true, ["hideDebuffs"] = false, ["amountSchoolColoring"] = false, ["amountColoring"] = false, ["unitColoring"] = false, ["hideBuffs"] = false, ["timestampFormat"] = "%H:%M:%S", ["braces"] = false, ["actionActorColoring"] = false, }, ["hasQuickButton"] = true, ["filters"] = { { ["eventList"] = { ["SPELL_PERIODIC_MISSED"] = true, ["SPELL_SUMMON"] = true, ["SPELL_INTERRUPT"] = true, ["UNIT_DESTROYED"] = true, ["DAMAGE_SHIELD_MISSED"] = true, ["SPELL_LEECH"] = true, ["SPELL_AURA_BROKEN"] = true, ["UNIT_DIED"] = true, ["SPELL_PERIODIC_ENERGIZE"] = true, ["DAMAGE_SPLIT"] = true, ["SPELL_INSTAKILL"] = true, ["SPELL_PERIODIC_DAMAGE"] = true, ["SPELL_PERIODIC_HEAL"] = true, ["PARTY_KILL"] = true, ["SPELL_DAMAGE"] = true, ["RANGE_DAMAGE"] = true, ["ENVIRONMENTAL_DAMAGE"] = true, ["SPELL_DISPEL"] = true, ["SPELL_EXTRA_ATTACKS"] = true, ["SPELL_MISSED"] = true, ["SPELL_STOLEN"] = true, ["SPELL_ENERGIZE"] = true, ["SWING_MISSED"] = true, ["SPELL_AURA_APPLIED"] = true, ["ENCHANT_REMOVED"] = true, ["SPELL_DURABILITY_DAMAGE_ALL"] = true, ["SPELL_CAST_START"] = true, ["SPELL_AURA_REFRESH"] = true, ["SPELL_PERIODIC_LEECH"] = true, ["SPELL_DURABILITY_DAMAGE"] = true, ["SPELL_CAST_FAILED"] = true, ["SPELL_AURA_REMOVED_DOSE"] = true, ["SPELL_DISPEL_FAILED"] = true, ["RANGE_MISSED"] = true, ["SPELL_AURA_APPLIED_DOSE"] = true, ["SPELL_AURA_REMOVED"] = true, ["SWING_DAMAGE"] = true, ["SPELL_AURA_BROKEN_SPELL"] = true, ["SPELL_CREATE"] = true, ["SPELL_CAST_SUCCESS"] = true, ["SPELL_HEAL"] = true, ["ENCHANT_APPLIED"] = true, ["DAMAGE_SHIELD"] = true, ["SPELL_PERIODIC_DRAIN"] = true, ["SPELL_DRAIN"] = true, }, ["sourceFlags"] = { [17681] = true, [32334] = true, [2147483648] = true, [12561] = true, [32078] = true, [32558] = true, [32542] = true, }, }, -- [1] { ["destFlags"] = { [17681] = true, [32334] = true, [2147483648] = true, [12561] = true, [32078] = true, [32558] = true, [32542] = true, }, ["eventList"] = { ["SPELL_PERIODIC_MISSED"] = true, ["SPELL_SUMMON"] = true, ["SPELL_INTERRUPT"] = true, ["UNIT_DESTROYED"] = true, ["DAMAGE_SHIELD_MISSED"] = true, ["SPELL_LEECH"] = true, ["SPELL_AURA_BROKEN"] = true, ["UNIT_DIED"] = true, ["SPELL_PERIODIC_ENERGIZE"] = true, ["DAMAGE_SPLIT"] = true, ["SPELL_INSTAKILL"] = true, ["SPELL_PERIODIC_DAMAGE"] = true, ["SPELL_PERIODIC_HEAL"] = true, ["PARTY_KILL"] = true, ["SPELL_DAMAGE"] = true, ["RANGE_DAMAGE"] = true, ["ENVIRONMENTAL_DAMAGE"] = true, ["SPELL_DISPEL"] = true, ["SPELL_EXTRA_ATTACKS"] = true, ["SPELL_MISSED"] = true, ["SPELL_STOLEN"] = true, ["SPELL_ENERGIZE"] = true, ["SWING_MISSED"] = true, ["SPELL_AURA_APPLIED"] = true, ["ENCHANT_REMOVED"] = true, ["SPELL_DURABILITY_DAMAGE_ALL"] = true, ["SPELL_CAST_START"] = true, ["SPELL_AURA_REFRESH"] = true, ["SPELL_PERIODIC_LEECH"] = true, ["SPELL_DURABILITY_DAMAGE"] = true, ["SPELL_CAST_FAILED"] = true, ["SPELL_AURA_REMOVED_DOSE"] = true, ["SPELL_DISPEL_FAILED"] = true, ["RANGE_MISSED"] = true, ["SPELL_AURA_APPLIED_DOSE"] = true, ["SPELL_AURA_REMOVED"] = true, ["SWING_DAMAGE"] = true, ["SPELL_AURA_BROKEN_SPELL"] = true, ["SPELL_CREATE"] = true, ["SPELL_CAST_SUCCESS"] = true, ["SPELL_HEAL"] = true, ["ENCHANT_APPLIED"] = true, ["DAMAGE_SHIELD"] = true, ["SPELL_PERIODIC_DRAIN"] = true, ["SPELL_DRAIN"] = true, }, }, -- [2] }, }, -- [2] { ["quickButtonName"] = "我发生了什么?", ["onQuickBar"] = true, ["quickButtonDisplay"] = { ["party"] = true, ["solo"] = true, ["raid"] = true, }, ["tooltip"] = "显示我所接收的所有行为信息。", ["name"] = "我发生了什么?", ["colors"] = { ["schoolColoring"] = { { ["a"] = 1, ["b"] = 0, ["g"] = 1, ["r"] = 1, }, -- [1] { ["a"] = 1, ["b"] = 0.5, ["g"] = 0.9, ["r"] = 1, }, -- [2] nil, -- [3] { ["a"] = 1, ["b"] = 0, ["g"] = 0.5, ["r"] = 1, }, -- [4] [16] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 0.5, }, [64] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.5, ["r"] = 1, }, [32] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.5, ["r"] = 0.5, }, [8] = { ["a"] = 1, ["b"] = 0.3, ["g"] = 1, ["r"] = 0.3, }, [0] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 1, }, }, ["eventColoring"] = { }, ["highlightedEvents"] = { ["PARTY_KILL"] = true, }, ["defaults"] = { ["damage"] = { ["a"] = 1, ["b"] = 0, ["g"] = 1, ["r"] = 1, }, ["spell"] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 1, }, }, ["unitColoring"] = { [17681] = { ["a"] = 1, ["b"] = 0.7, ["g"] = 0.7, ["r"] = 0.7, }, [32334] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [2147483648] = { ["a"] = 1, ["b"] = 0.75, ["g"] = 0.75, ["r"] = 0.75, }, [12561] = { ["a"] = 1, ["b"] = 0.7, ["g"] = 0.7, ["r"] = 0.7, }, [32078] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [32558] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [32542] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.64, ["r"] = 0.34, }, }, }, ["settings"] = { ["abilityHighlighting"] = true, ["lineColoring"] = true, ["spellBraces"] = false, ["sourceColoring"] = true, ["showHistory"] = true, ["destColoring"] = true, ["amountHighlighting"] = true, ["schoolNameColoring"] = false, ["abilitySchoolColoring"] = false, ["sourceBraces"] = true, ["missColoring"] = true, ["itemBraces"] = true, ["abilityColoring"] = false, ["amountActorColoring"] = false, ["textMode"] = "A", ["destBraces"] = true, ["timestamp"] = false, ["actionColoring"] = false, ["fullText"] = true, ["lineColorPriority"] = 1, ["lineHighlighting"] = true, ["abilityActorColoring"] = false, ["actionHighlighting"] = false, ["schoolNameActorColoring"] = false, ["schoolNameHighlighting"] = true, ["unitBraces"] = true, ["noMeleeSwingColoring"] = false, ["unitIcons"] = true, ["hideDebuffs"] = false, ["amountSchoolColoring"] = false, ["amountColoring"] = false, ["unitColoring"] = false, ["hideBuffs"] = false, ["timestampFormat"] = "%H:%M:%S", ["braces"] = false, ["actionActorColoring"] = false, }, ["hasQuickButton"] = true, ["filters"] = { { ["eventList"] = { ["SPELL_PERIODIC_MISSED"] = true, ["SPELL_SUMMON"] = true, ["SPELL_INTERRUPT"] = true, ["UNIT_DESTROYED"] = true, ["DAMAGE_SHIELD_MISSED"] = true, ["SPELL_LEECH"] = true, ["SPELL_AURA_BROKEN"] = true, ["UNIT_DIED"] = true, ["SPELL_PERIODIC_ENERGIZE"] = true, ["DAMAGE_SPLIT"] = true, ["SPELL_INSTAKILL"] = true, ["SPELL_PERIODIC_DAMAGE"] = true, ["SPELL_PERIODIC_HEAL"] = true, ["PARTY_KILL"] = true, ["SPELL_DAMAGE"] = true, ["RANGE_DAMAGE"] = true, ["ENVIRONMENTAL_DAMAGE"] = true, ["SPELL_DISPEL"] = true, ["SPELL_EXTRA_ATTACKS"] = true, ["SPELL_MISSED"] = true, ["SPELL_STOLEN"] = true, ["SPELL_ENERGIZE"] = true, ["SWING_MISSED"] = true, ["SPELL_AURA_APPLIED"] = true, ["ENCHANT_REMOVED"] = true, ["SPELL_DURABILITY_DAMAGE_ALL"] = true, ["SPELL_CAST_START"] = true, ["SPELL_AURA_REFRESH"] = true, ["SPELL_PERIODIC_LEECH"] = true, ["SPELL_DURABILITY_DAMAGE"] = true, ["SPELL_CAST_FAILED"] = true, ["SPELL_AURA_REMOVED_DOSE"] = true, ["SPELL_DISPEL_FAILED"] = true, ["RANGE_MISSED"] = true, ["SPELL_AURA_APPLIED_DOSE"] = true, ["SPELL_AURA_REMOVED"] = true, ["SWING_DAMAGE"] = true, ["SPELL_AURA_BROKEN_SPELL"] = true, ["SPELL_CREATE"] = true, ["SPELL_CAST_SUCCESS"] = true, ["SPELL_HEAL"] = true, ["ENCHANT_APPLIED"] = true, ["DAMAGE_SHIELD"] = true, ["SPELL_PERIODIC_DRAIN"] = true, ["SPELL_DRAIN"] = true, }, ["sourceFlags"] = { [17681] = false, [32334] = false, [2147483648] = false, [12561] = false, [32078] = false, [32558] = false, [32542] = false, }, }, -- [1] { ["destFlags"] = { [17681] = true, [12561] = true, }, ["eventList"] = { ["SPELL_PERIODIC_MISSED"] = true, ["SPELL_SUMMON"] = true, ["SPELL_INTERRUPT"] = true, ["UNIT_DESTROYED"] = true, ["DAMAGE_SHIELD_MISSED"] = true, ["SPELL_LEECH"] = true, ["SPELL_AURA_BROKEN"] = true, ["UNIT_DIED"] = true, ["SPELL_PERIODIC_ENERGIZE"] = true, ["DAMAGE_SPLIT"] = true, ["SPELL_INSTAKILL"] = true, ["SPELL_PERIODIC_DAMAGE"] = true, ["SPELL_PERIODIC_HEAL"] = true, ["PARTY_KILL"] = true, ["SPELL_DAMAGE"] = true, ["RANGE_DAMAGE"] = true, ["ENVIRONMENTAL_DAMAGE"] = true, ["SPELL_DISPEL"] = true, ["SPELL_EXTRA_ATTACKS"] = true, ["SPELL_MISSED"] = true, ["SPELL_STOLEN"] = true, ["SPELL_ENERGIZE"] = true, ["SWING_MISSED"] = true, ["SPELL_AURA_APPLIED"] = true, ["ENCHANT_REMOVED"] = true, ["SPELL_DURABILITY_DAMAGE_ALL"] = true, ["SPELL_CAST_START"] = true, ["SPELL_AURA_REFRESH"] = true, ["SPELL_PERIODIC_LEECH"] = true, ["SPELL_DURABILITY_DAMAGE"] = true, ["SPELL_CAST_FAILED"] = true, ["SPELL_AURA_REMOVED_DOSE"] = true, ["SPELL_DISPEL_FAILED"] = true, ["RANGE_MISSED"] = true, ["SPELL_AURA_APPLIED_DOSE"] = true, ["SPELL_AURA_REMOVED"] = true, ["SWING_DAMAGE"] = true, ["SPELL_AURA_BROKEN_SPELL"] = true, ["SPELL_CREATE"] = true, ["SPELL_CAST_SUCCESS"] = true, ["SPELL_HEAL"] = true, ["ENCHANT_APPLIED"] = true, ["DAMAGE_SHIELD"] = true, ["SPELL_PERIODIC_DRAIN"] = true, ["SPELL_DRAIN"] = true, }, }, -- [2] }, }, -- [3] { ["quickButtonName"] = "杀敌", ["onQuickBar"] = false, ["quickButtonDisplay"] = { ["party"] = true, ["solo"] = true, ["raid"] = true, }, ["tooltip"] = "显示所有死亡和杀敌信息。", ["name"] = "杀敌", ["colors"] = { ["schoolColoring"] = { { ["a"] = 1, ["b"] = 0, ["g"] = 1, ["r"] = 1, }, -- [1] { ["a"] = 1, ["b"] = 0.5, ["g"] = 0.9, ["r"] = 1, }, -- [2] nil, -- [3] { ["a"] = 1, ["b"] = 0, ["g"] = 0.5, ["r"] = 1, }, -- [4] [16] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 0.5, }, [64] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.5, ["r"] = 1, }, [32] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.5, ["r"] = 0.5, }, [8] = { ["a"] = 1, ["b"] = 0.3, ["g"] = 1, ["r"] = 0.3, }, [0] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 1, }, }, ["eventColoring"] = { }, ["highlightedEvents"] = { ["PARTY_KILL"] = true, }, ["defaults"] = { ["damage"] = { ["a"] = 1, ["b"] = 0, ["g"] = 1, ["r"] = 1, }, ["spell"] = { ["a"] = 1, ["b"] = 1, ["g"] = 1, ["r"] = 1, }, }, ["unitColoring"] = { [17681] = { ["a"] = 1, ["b"] = 0.7, ["g"] = 0.7, ["r"] = 0.7, }, [32334] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [2147483648] = { ["a"] = 1, ["b"] = 0.75, ["g"] = 0.75, ["r"] = 0.75, }, [12561] = { ["a"] = 1, ["b"] = 0.7, ["g"] = 0.7, ["r"] = 0.7, }, [32078] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [32558] = { ["a"] = 1, ["b"] = 0.05, ["g"] = 0.05, ["r"] = 0.75, }, [32542] = { ["a"] = 1, ["b"] = 1, ["g"] = 0.64, ["r"] = 0.34, }, }, }, ["settings"] = { ["abilityHighlighting"] = true, ["lineColoring"] = true, ["spellBraces"] = false, ["sourceColoring"] = true, ["showHistory"] = true, ["destColoring"] = true, ["amountHighlighting"] = true, ["schoolNameColoring"] = false, ["abilitySchoolColoring"] = false, ["sourceBraces"] = true, ["missColoring"] = true, ["itemBraces"] = true, ["abilityColoring"] = false, ["amountActorColoring"] = false, ["textMode"] = "A", ["destBraces"] = true, ["timestamp"] = false, ["actionColoring"] = false, ["fullText"] = true, ["lineColorPriority"] = 1, ["lineHighlighting"] = true, ["abilityActorColoring"] = false, ["actionHighlighting"] = false, ["schoolNameActorColoring"] = false, ["schoolNameHighlighting"] = true, ["unitBraces"] = true, ["noMeleeSwingColoring"] = false, ["unitIcons"] = true, ["hideDebuffs"] = false, ["amountSchoolColoring"] = false, ["amountColoring"] = false, ["unitColoring"] = false, ["hideBuffs"] = false, ["timestampFormat"] = "%H:%M:%S", ["braces"] = false, ["actionActorColoring"] = false, }, ["hasQuickButton"] = false, ["filters"] = { { ["eventList"] = { ["PARTY_KILL"] = true, ["UNIT_DESTROYED"] = true, ["UNIT_DIED"] = true, }, ["sourceFlags"] = { [17681] = true, [32334] = true, [2147483648] = true, [12561] = true, [32078] = true, [32558] = true, [32542] = true, }, }, -- [1] { ["destFlags"] = { [17681] = true, [32334] = true, [2147483648] = true, [12561] = true, [32078] = true, [32558] = true, [32542] = true, }, ["eventList"] = { ["PARTY_KILL"] = true, ["UNIT_DESTROYED"] = true, ["UNIT_DIED"] = true, }, }, -- [2] }, }, -- [4] }, ["currentFilter"] = 1, } Blizzard_CombatLog_Filter_Version = 4.1
gpl-3.0
Turttle/darkstar
scripts/globals/items/spirit_sword.lua
16
1559
----------------------------------------- -- ID: 16613 -- Spirit Sword -- Additional effect: Light damage -- Enchantment: TP+100 ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(7,21); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0); dmg = adjustForTarget(target,dmg,ELE_LIGHT); dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_LIGHT_DAMAGE,message,dmg; end end; ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getFreeSlotsCount() == 0) then result = 308; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addTP(10); -- Core currently makes this *10 stated value, so its 100... end;
gpl-3.0
birdbrainswagtrain/GmodPillPack-TeamFortress
lua/autorun/include/pill_tf_fun.lua
1
3321
AddCSLuaFile() pk_pills.register("tf_conga",{ type="ply", printName="CONGA CONGA CONGA", options=function() return { {model="models/player/scout.mdl"}, {model="models/player/soldier.mdl"}, {model="models/player/pyro.mdl"}, {model="models/player/demo.mdl"}, {model="models/player/heavy.mdl"}, {model="models/player/engineer.mdl"}, {model="models/player/medic.mdl"}, {model="models/player/sniper.mdl"}, {model="models/player/spy.mdl"}, {model="models/player/scout.mdl",skin=1}, {model="models/player/soldier.mdl",skin=1}, {model="models/player/pyro.mdl",skin=1}, {model="models/player/demo.mdl",skin=1}, {model="models/player/heavy.mdl",skin=1}, {model="models/player/engineer.mdl",skin=1}, {model="models/player/medic.mdl",skin=1}, {model="models/player/sniper.mdl",skin=1}, {model="models/player/spy.mdl",skin=1} } end, default_rp_cost=1000, camera={ offset=Vector(0,0,70), dist=100 }, anims={ default={ idle="taunt_conga" } }, sounds={ loop_move="music/conga_sketch_167bpm_01-04.wav" }, autoRestartAnims=true, hull=Vector(30,30,80), moveSpeed={ walk=1 }, moveMod=function(ply,ent,mv,cmd) local angs = mv:GetAngles() local vz = mv:GetVelocity().z angs.pitch=0 mv:SetVelocity(angs:Forward()*50+Vector(0,0,vz)) end, health=500 }) pk_pills.register("tf_bumpercar",{ type="ply", printName="Bumper Car", options=function() return { {model="models/player/scout.mdl"}, {model="models/player/soldier.mdl"}, {model="models/player/pyro.mdl"}, {model="models/player/demo.mdl"}, {model="models/player/heavy.mdl"}, {model="models/player/engineer.mdl"}, {model="models/player/medic.mdl"}, {model="models/player/sniper.mdl"}, {model="models/player/spy.mdl"}, {model="models/player/scout.mdl",skin=1}, {model="models/player/soldier.mdl",skin=1}, {model="models/player/pyro.mdl",skin=1}, {model="models/player/demo.mdl",skin=1}, {model="models/player/heavy.mdl",skin=1}, {model="models/player/engineer.mdl",skin=1}, {model="models/player/medic.mdl",skin=1}, {model="models/player/sniper.mdl",skin=1}, {model="models/player/spy.mdl",skin=1} } end, default_rp_cost=10000, camera={ offset=Vector(0,0,25), dist=100 }, anims={ default={ idle="kart_idle" } }, hull=Vector(50,50,50), moveSpeed={ walk=400 }, jump=function(ply,ent) ent:PillSound("jump") end, sounds={ loop_move="weapons/bumper_car_go_loop.wav", jump="weapons/bumper_car_jump.wav" }, moveMod=function(ply,ent,mv,cmd) if !ent.driver_attachment then local a = ents.Create("pill_attachment") a:SetModel("models/player/items/taunts/bumpercar/parts/bumpercar_nolights.mdl") a:SetSkin(ent:GetPuppet():GetSkin()) a:SetParent(ent:GetPuppet()) a:Spawn() ent.driver_attachment=true end if !ply:IsOnGround() then return end local angs = mv:GetAngles() angs.pitch=0 local vel = mv:GetVelocity() if (cmd:KeyDown(IN_FORWARD)) then vel=vel+angs:Forward()*100*(ent.formTable.modelScale or 1) end mv:SetVelocity(vel) end, muteSteps=true, jumpPower=400, noFallDamage=true, health=500 }) pk_pills.register("tf_bumpercar_tiny",{ printName="Micro Car", parent="tf_bumpercar", boneMorphs = { ["bip_head"]={scale=Vector(3,3,3)} }, modelScale=.5, jumpPower=300, health=50, hull=Vector(25,25,25), })
mit
SalvationDevelopment/Salvation-Scripts-TCG
c46066477.lua
6
1299
--エンタメ・バンド・ハリケーン function c46066477.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TOHAND) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCountLimit(1,46066477+EFFECT_COUNT_CODE_OATH) e1:SetTarget(c46066477.target) e1:SetOperation(c46066477.activate) c:RegisterEffect(e1) end function c46066477.cfilter(c) return c:IsFaceup() and c:IsSetCard(0x9f) end function c46066477.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and chkc:IsAbleToHand() end if chk==0 then return Duel.IsExistingMatchingCard(c46066477.cfilter,tp,LOCATION_MZONE,0,1,nil) and Duel.IsExistingTarget(Card.IsAbleToHand,tp,0,LOCATION_ONFIELD,1,nil) end local ct=Duel.GetMatchingGroupCount(c46066477.cfilter,tp,LOCATION_MZONE,0,nil) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND) local g=Duel.SelectTarget(tp,Card.IsAbleToHand,tp,0,LOCATION_ONFIELD,1,ct,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,g:GetCount(),0,0) end function c46066477.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) end end
gpl-2.0
eugeneia/snabb
lib/pflua/src/pf/expand.lua
10
42633
module(...,package.seeall) local utils = require('pf.utils') local verbose = os.getenv("PF_VERBOSE"); local expand_arith, expand_relop, expand_bool local set, concat, pp = utils.set, utils.concat, utils.pp local uint16, uint32 = utils.uint16, utils.uint32 local ipv4_to_int, ipv6_as_4x32 = utils.ipv4_to_int, utils.ipv6_as_4x32 local filter_args = utils.filter_args local llc_types = set( 'i', 's', 'u', 'rr', 'rnr', 'rej', 'ui', 'ua', 'disc', 'sabme', 'test', 'xis', 'frmr' ) local pf_reasons = set( 'match', 'bad-offset', 'fragment', 'short', 'normalize', 'memory' ) local pf_actions = set( 'pass', 'block', 'nat', 'rdr', 'binat', 'scrub' ) local wlan_frame_types = set('mgt', 'ctl', 'data') local wlan_frame_mgt_subtypes = set( 'assoc-req', 'assoc-resp', 'reassoc-req', 'reassoc-resp', 'probe-req', 'probe-resp', 'beacon', 'atim', 'disassoc', 'auth', 'deauth' ) local wlan_frame_ctl_subtypes = set( 'ps-poll', 'rts', 'cts', 'ack', 'cf-end', 'cf-end-ack' ) local wlan_frame_data_subtypes = set( 'data', 'data-cf-ack', 'data-cf-poll', 'data-cf-ack-poll', 'null', 'cf-ack', 'cf-poll', 'cf-ack-poll', 'qos-data', 'qos-data-cf-ack', 'qos-data-cf-poll', 'qos-data-cf-ack-poll', 'qos', 'qos-cf-poll', 'quos-cf-ack-poll' ) local wlan_directions = set('nods', 'tods', 'fromds', 'dstods') local function unimplemented(expr, dlt) error("not implemented: "..expr[1]) end -- Ethernet protocols local PROTO_AARP = 33011 -- 0x80f3 local PROTO_ARP = 2054 -- 0x806 local PROTO_ATALK = 32923 -- 0x809b local PROTO_DECNET = 24579 -- 0x6003 local PROTO_IPV4 = 2048 -- 0x800 local PROTO_IPV6 = 34525 -- 0x86dd local PROTO_IPX = 33079 -- 0X8137 local PROTO_ISO = 65278 -- 0xfefe local PROTO_LAT = 24580 -- 0x6004 local PROTO_MOPDL = 24577 -- 0x6001 local PROTO_MOPRC = 24578 -- 0x6002 local PROTO_NETBEUI = 61680 -- 0xf0f0 local PROTO_RARP = 32821 -- 0x8035 local PROTO_SCA = 24583 -- 0x6007 local PROTO_STP = 66 -- 0x42 local ether_min_payloads = { [PROTO_IPV4] = 20, [PROTO_ARP] = 28, [PROTO_RARP] = 28, [PROTO_IPV6] = 40 } -- IP protocols local PROTO_AH = 51 -- 0x33 local PROTO_ESP = 50 -- 0x32 local PROTO_ICMP = 1 -- 0x1 local PROTO_ICMP6 = 58 -- 0x3a local PROTO_IGMP = 2 -- 0x2 local PROTO_IGRP = 9 -- 0x9 local PROTO_PIM = 103 -- 0x67 local PROTO_SCTP = 132 -- 0x84 local PROTO_TCP = 6 -- 0x6 local PROTO_UDP = 17 -- 0x11 local PROTO_VRRP = 112 -- 0x70 local ip_min_payloads = { [PROTO_ICMP] = 8, [PROTO_UDP] = 8, [PROTO_TCP] = 20, [PROTO_IGMP] = 8, [PROTO_IGRP] = 8, [PROTO_PIM] = 4, [PROTO_SCTP] = 12, [PROTO_VRRP] = 8 } -- ISO protocols local PROTO_CLNP = 129 -- 0x81 local PROTO_ESIS = 130 -- 0x82 local PROTO_ISIS = 131 -- 0x83 local ETHER_TYPE = 12 local ETHER_PAYLOAD = 14 local IP_FLAGS = 6 local IP_PROTOCOL = 9 -- Minimum payload checks insert a byte access to the last byte of the -- minimum payload size. Since the comparison should fold (because it -- will always be >= 0), we will be left with just an eager assertion on -- the minimum packet size, which should help elide future packet size -- assertions. local function has_proto_min_payload(min_payloads, proto, accessor) local min_payload = assert(min_payloads[proto]) return { '<=', 0, { accessor, min_payload - 1, 1 } } end -- When proto is greater than 1500 (0x5DC) , the frame is treated as an -- Ethernet frame and the Type/Length is interpreted as Type, storing the -- EtherType value. -- Otherwise, the frame is interpreted as an 802.3 frame and the -- Type/Length field is interpreted as Length. The Length cannot be greater -- than 1500. The first byte after the Type/Length field stores the Service -- Access Point of the 802.3 frame. It works as an EtherType at LLC level. -- -- See: https://tools.ietf.org/html/draft-ietf-isis-ext-eth-01 local ETHER_MAX_LEN = 1500 local function has_ether_protocol(proto) if proto > ETHER_MAX_LEN then return { '=', { '[ether]', ETHER_TYPE, 2 }, proto } end return { 'and', { '<=', {'[ether]', ETHER_TYPE, 2}, ETHER_MAX_LEN }, { '=', { '[ether]', ETHER_PAYLOAD, 1}, proto } } end local function has_ether_protocol_min_payload(proto) return has_proto_min_payload(ether_min_payloads, proto, '[ether*]') end local function has_ipv4_protocol(proto) return { '=', { '[ip]', IP_PROTOCOL, 1 }, proto } end local function has_ipv4_protocol_min_payload(proto) -- Since the [ip*] accessor asserts that is_first_ipv4_fragment(), -- and we don't want that, we use [ip] and assume the minimum IP -- header size. local min_payload = assert(ip_min_payloads[proto]) min_payload = min_payload + assert(ether_min_payloads[PROTO_IPV4]) return { '<=', 0, { '[ip]', min_payload - 1, 1 } } end local function is_first_ipv4_fragment() return { '=', { '&', { '[ip]', IP_FLAGS, 2 }, 0x1fff }, 0 } end local function has_ipv6_protocol(proto) local IPV6_NEXT_HEADER_1 = 6 local IPV6_NEXT_HEADER_2 = 40 local IPV6_FRAGMENTATION_EXTENSION_HEADER = 44 return { 'and', { 'ip6' }, { 'or', { '=', { '[ip6]', IPV6_NEXT_HEADER_1, 1 }, proto }, { 'and', { '=', { '[ip6]', IPV6_NEXT_HEADER_1, 1 }, IPV6_FRAGMENTATION_EXTENSION_HEADER }, { '=', { '[ip6]', IPV6_NEXT_HEADER_2, 1 }, proto } } } } end local function has_ipv6_protocol_min_payload(proto) -- Assume the minimum ipv6 header size. local min_payload = assert(ip_min_payloads[proto]) min_payload = min_payload + assert(ether_min_payloads[PROTO_IPV6]) return { '<=', 0, { '[ip6]', min_payload - 1, 1 } } end local function has_ip_protocol(proto) return { 'if', { 'ip' }, has_ipv4_protocol(proto), has_ipv6_protocol(proto) } end -- Port operations -- local SRC_PORT = 0 local DST_PORT = 2 local function has_ipv4_src_port(port) return { '=', { '[ip*]', SRC_PORT, 2 }, port } end local function has_ipv4_dst_port(port) return { '=', { '[ip*]', DST_PORT, 2 }, port } end local function has_ipv4_port(port) return { 'or', has_ipv4_src_port(port), has_ipv4_dst_port(port) } end local function has_ipv6_src_port(port) return { '=', { '[ip6*]', SRC_PORT, 2 }, port } end local function has_ipv6_dst_port(port) return { '=', { '[ip6*]', DST_PORT, 2 }, port } end local function has_ipv6_port(port) return { 'or', has_ipv6_src_port(port), has_ipv6_dst_port(port) } end local function expand_dir_port(expr, has_ipv4_port, has_ipv6_port) local port = expr[2] return { 'if', { 'ip' }, { 'and', { 'or', has_ipv4_protocol(PROTO_TCP), { 'or', has_ipv4_protocol(PROTO_UDP), has_ipv4_protocol(PROTO_SCTP) } }, has_ipv4_port(port) }, { 'and', { 'or', has_ipv6_protocol(PROTO_TCP), { 'or', has_ipv6_protocol(PROTO_UDP), has_ipv6_protocol(PROTO_SCTP) } }, has_ipv6_port(port) } } end local function expand_port(expr) return expand_dir_port(expr, has_ipv4_port, has_ipv6_port) end local function expand_src_port(expr) return expand_dir_port(expr, has_ipv4_src_port, has_ipv6_src_port) end local function expand_dst_port(expr) return expand_dir_port(expr, has_ipv4_dst_port, has_ipv6_dst_port) end local function expand_proto_port(expr, proto) local port = expr[2] return { 'if', { 'ip' }, { 'and', has_ipv4_protocol(proto), has_ipv4_port(port) }, { 'and', has_ipv6_protocol(proto), has_ipv6_port(port) } } end local function expand_tcp_port(expr) return expand_proto_port(expr, PROTO_TCP) end local function expand_udp_port(expr) return expand_proto_port(expr, PROTO_UDP) end local function expand_proto_src_port(expr, proto) local port = expr[2] return { 'if', { 'ip' }, { 'and', has_ipv4_protocol(proto), has_ipv4_src_port(port) }, { 'and', has_ipv6_protocol(proto), has_ipv6_src_port(port) } } end local function expand_tcp_src_port(expr) return expand_proto_src_port(expr, PROTO_TCP) end local function expand_udp_src_port(expr) return expand_proto_src_port(expr, PROTO_UDP) end local function expand_proto_dst_port(expr, proto) local port = expr[2] return { 'if', { 'ip' }, { 'and', has_ipv4_protocol(proto), has_ipv4_dst_port(port) }, { 'and', has_ipv6_protocol(proto), has_ipv6_dst_port(port) } } end local function expand_tcp_dst_port(expr) return expand_proto_dst_port(expr, PROTO_TCP) end local function expand_udp_dst_port(expr) return expand_proto_dst_port(expr, PROTO_UDP) end -- Portrange operations -- local function has_ipv4_src_portrange(lo, hi) return { 'and', { '<=', lo, { '[ip*]', SRC_PORT, 2 } }, { '<=', { '[ip*]', SRC_PORT, 2 }, hi } } end local function has_ipv4_dst_portrange(lo, hi) return { 'and', { '<=', lo, { '[ip*]', DST_PORT, 2 } }, { '<=', { '[ip*]', DST_PORT, 2 }, hi } } end local function has_ipv4_portrange(lo, hi) return { 'or', has_ipv4_src_portrange(lo, hi), has_ipv4_dst_portrange(lo, hi) } end local function has_ipv6_src_portrange(lo, hi) return { 'and', { '<=', lo, { '[ip6*]', SRC_PORT, 2 } }, { '<=', { '[ip6*]', SRC_PORT, 2 }, hi } } end local function has_ipv6_dst_portrange(lo, hi) return { 'and', { '<=', lo, { '[ip6*]', DST_PORT, 2 } }, { '<=', { '[ip6*]', DST_PORT, 2 }, hi } } end local function has_ipv6_portrange(lo, hi) return { 'or', has_ipv6_src_portrange(lo, hi), has_ipv6_dst_portrange(lo, hi) } end local function expand_dir_portrange(expr, has_ipv4_portrange, has_ipv6_portrange) local lo, hi = expr[2][1], expr[2][2] return { 'if', { 'ip' }, { 'and', { 'or', has_ipv4_protocol(PROTO_TCP), { 'or', has_ipv4_protocol(PROTO_UDP), has_ipv4_protocol(PROTO_SCTP) } }, has_ipv4_portrange(lo, hi) }, { 'and', { 'or', has_ipv6_protocol(PROTO_TCP), { 'or', has_ipv6_protocol(PROTO_UDP), has_ipv6_protocol(PROTO_SCTP) } }, has_ipv6_portrange(lo, hi) } } end local function expand_portrange(expr) return expand_dir_portrange(expr, has_ipv4_portrange, has_ipv6_portrange) end local function expand_src_portrange(expr) return expand_dir_portrange(expr, has_ipv4_src_portrange, has_ipv6_src_portrange) end local function expand_dst_portrange(expr) return expand_dir_portrange(expr, has_ipv4_dst_portrange, has_ipv6_dst_portrange) end local function expand_proto_portrange(expr, proto) local lo, hi = expr[2][1], expr[2][2] return { 'if', { 'ip' }, { 'and', has_ipv4_protocol(proto), has_ipv4_portrange(lo, hi) }, { 'and', has_ipv6_protocol(proto), has_ipv6_portrange(lo, hi) } } end local function expand_tcp_portrange(expr) return expand_proto_portrange(expr, PROTO_TCP) end local function expand_udp_portrange(expr) return expand_proto_portrange(expr, PROTO_UDP) end local function expand_proto_src_portrange(expr, proto) local lo, hi = expr[2][1], expr[2][2] return { 'if', { 'ip' }, { 'and', has_ipv4_protocol(proto), has_ipv4_src_portrange(lo, hi) }, { 'and', has_ipv6_protocol(proto), has_ipv6_src_portrange(lo, hi) } } end local function expand_tcp_src_portrange(expr) return expand_proto_src_portrange(expr, PROTO_TCP) end local function expand_udp_src_portrange(expr) return expand_proto_src_portrange(expr, PROTO_UDP) end local function expand_proto_dst_portrange(expr, proto) local lo, hi = expr[2][1], expr[2][2] return { 'if', { 'ip' }, { 'and', has_ipv4_protocol(proto), has_ipv4_dst_portrange(lo, hi) }, { 'and', has_ipv6_protocol(proto), has_ipv6_dst_portrange(lo, hi) } } end local function expand_tcp_dst_portrange(expr) return expand_proto_dst_portrange(expr, PROTO_TCP) end local function expand_udp_dst_portrange(expr) return expand_proto_dst_portrange(expr, PROTO_UDP) end -- IP protocol local proto_info = { ip = { id = PROTO_IPV4, access = "[ip]", src = 12, dst = 16 }, arp = { id = PROTO_ARP, access = "[arp]", src = 14, dst = 24 }, rarp = { id = PROTO_RARP, access = "[rarp]", src = 14, dst = 24 }, ip6 = { id = PROTO_IPV6, access = "[ip6]", src = 8, dst = 24 }, } local function has_proto_dir_host(proto, dir, addr, mask) local host = ipv4_to_int(addr) local val = { proto_info[proto].access, proto_info[proto][dir], 4 } if mask then mask = tonumber(mask) and 2^32 - 2^(32 - mask) or ipv4_to_int(mask) val = { '&', val, tonumber(mask) } end return { 'and', has_ether_protocol(proto_info[proto].id), { '=', val, host } } end local function expand_ip_src_host(expr) return has_proto_dir_host("ip", "src", expr[2], expr[3]) end local function expand_ip_dst_host(expr) return has_proto_dir_host("ip", "dst", expr[2], expr[3]) end local function expand_ip_host(expr) return { 'or', expand_ip_src_host(expr), expand_ip_dst_host(expr) } end local function expand_ip_broadcast(expr) error("netmask not known, so 'ip broadcast' not supported") end local function expand_ip6_broadcast(expr) error("only link-layer/IP broadcast filters supported") end local function expand_ip_multicast(expr) local IPV4_MULTICAST = 224 -- 0xe0 local IPV4_DEST_ADDRESS = 16 return { '=', { '[ip]', IPV4_DEST_ADDRESS, 1 }, IPV4_MULTICAST } end local function expand_ip6_multicast(expr) local IPV6_MULTICAST = 255 -- 0xff local IPV6_DEST_ADDRESS_OFFSET = 24 -- 14 + 24 = 38 (last two bytes of dest address) return { '=', { '[ip6]', IPV6_DEST_ADDRESS_OFFSET, 1 }, IPV6_MULTICAST } end local function expand_ip4_protochain(expr) -- FIXME: Not implemented yet. BPF code of ip protochain is rather complex. return unimplemented(expr) end local function expand_ip6_protochain(expr) -- FIXME: Not implemented yet. BPF code of ip6 protochain is rather complex. return unimplemented(expr) end local function expand_ip_protochain(expr) return { 'if', 'ip', expand_ip4_protochain(expr), expand_ip6_protochain(expr) } end local ip_protos = { icmp = PROTO_ICMP, icmp6 = PROTO_ICMP6, igmp = PROTO_IGMP, igrp = PROTO_IGRP, pim = PROTO_PIM, ah = PROTO_AH, esp = PROTO_ESP, vrrp = PROTO_VRRP, udp = PROTO_UDP, tcp = PROTO_TCP, sctp = PROTO_SCTP, } local function expand_ip4_proto(expr) local proto = expr[2] if type(proto) == 'string' then proto = ip_protos[proto] end return has_ipv4_protocol(assert(proto, "Invalid IP protocol")) end local function expand_ip6_proto(expr) local proto = expr[2] if type(proto) == 'string' then proto = ip_protos[proto] end return has_ipv6_protocol(assert(proto, "Invalid IP protocol")) end local function expand_ip_proto(expr) return { 'or', expand_ip4_proto(expr), expand_ip6_proto(expr) } end -- ISO local iso_protos = { clnp = PROTO_CLNP, esis = PROTO_ESIS, isis = PROTO_ISIS, } local function has_iso_protocol(proto) return { 'and', { '<=', { '[ether]', ETHER_TYPE, 2 }, ETHER_MAX_LEN }, { 'and', { '=', { '[ether]', ETHER_PAYLOAD, 2 }, PROTO_ISO }, { '=', { '[ether]', ETHER_PAYLOAD + 3, 1 }, proto } } } end local function expand_iso_proto(expr) local proto = expr[2] if type(proto) == 'string' then proto = iso_protos[proto] end return has_iso_protocol(assert(proto, "Invalid ISO protocol")) end -- ARP protocol local function expand_arp_src_host(expr) return has_proto_dir_host("arp", "src", expr[2], expr[3]) end local function expand_arp_dst_host(expr) return has_proto_dir_host("arp", "dst", expr[2], expr[3]) end local function expand_arp_host(expr) return { 'or', expand_arp_src_host(expr), expand_arp_dst_host(expr) } end -- RARP protocol local function expand_rarp_src_host(expr) return has_proto_dir_host("rarp", "src", expr[2], expr[3]) end local function expand_rarp_dst_host(expr) return has_proto_dir_host("rarp", "dst", expr[2], expr[3]) end local function expand_rarp_host(expr) return { 'or', expand_rarp_src_host(expr), expand_rarp_dst_host(expr) } end -- IPv6 local function ipv6_dir_host(proto, dir, addr, mask_len) mask_len = mask_len or 128 local offset = proto_info.ip6[dir] local ipv6 = ipv6_as_4x32(addr) local function match_ipv6_fragment(i) local fragment = ipv6[i] -- Calculate mask for fragment local mask = mask_len >= 32 and 0 or mask_len mask_len = mask_len >= 32 and mask_len - 32 or 0 -- Retrieve address current offset local val = { proto_info.ip6.access, offset, 4 } offset = offset + 4 if mask ~= 0 then val = { '&', val, 2^32 - 2^(32 - mask) } end return { '=', val, fragment } end -- Lowering of an IPv6 address does not require to go iterate through all -- IPv6 fragments (4x32). Once mask_len becomes 0 is possible to exit. local function match_ipv6(i) local i = i or 1 local expr = match_ipv6_fragment(i) if mask_len == 0 or i > 4 then return expr end return { 'and', expr, match_ipv6(i + 1) } end return { 'and', has_ether_protocol(PROTO_IPV6), match_ipv6() } end local function expand_src_ipv6_host(expr) return ipv6_dir_host('ip6', 'src', expr[2], expr[3]) end local function expand_dst_ipv6_host(expr) return ipv6_dir_host('ip6', 'dst', expr[2], expr[3]) end local function expand_ipv6_host(expr) return { 'or', ipv6_dir_host('ip6', 'src', expr[2], expr[3]), ipv6_dir_host('ip6', 'dst', expr[2], expr[3]) } end -- Host --[[ * Format IPv4 expr: { 'net', { 'ipv4', 127, 0, 0, 1 } } { 'ipv4/len', { 'ipv4', 127, 0, 0, 1 }, 24 } * Format IPv6 expr: { 'net', { 'ipv6', 0, 0, 0, 0, 0, 0, 0, 1 } } { 'ipv4/len', { 'ipv6', 0, 0, 0, 0, 0, 0, 0, 1 }, 24 } ]]-- local function is_ipv6_addr(expr) return expr[2][1] == 'ipv6' end local function expand_src_host(expr) if is_ipv6_addr(expr) then return expand_src_ipv6_host(expr) end return { 'if', { 'ip' }, expand_ip_src_host(expr), { 'if', { 'arp' }, expand_arp_src_host(expr), expand_rarp_src_host(expr) } } end local function expand_dst_host(expr) if is_ipv6_addr(expr) then return expand_dst_ipv6_host(expr) end return { 'if', { 'ip' }, expand_ip_dst_host(expr), { 'if', { 'arp' }, expand_arp_dst_host(expr), expand_rarp_dst_host(expr) } } end -- Format IPv4: { 'ipv4/len', { 'ipv4', 127, 0, 0, 1 }, 8 } -- Format IPv4: { 'ipv4/mask', { 'ipv4', 127, 0, 0, 1 }, { 'ipv4', 255, 0, 0, 0 } } -- Format IPv6: { 'ipv6/len', { 'ipv6', 0, 0, 0, 0, 0, 0, 0, 1 }, 128 } local function expand_host(expr) if is_ipv6_addr(expr) then return expand_ipv6_host(expr) end return { 'if', { 'ip' }, expand_ip_host(expr), { 'if', { 'arp' }, expand_arp_host(expr), expand_rarp_host(expr) } } end -- Ether local MAC_DST = 0 local MAC_SRC = 6 local function ehost_to_int(addr) assert(addr[1] == 'ehost', "Not a valid ehost address") return uint16(addr[2], addr[3]), uint32(addr[4], addr[5], addr[6], addr[7]) end local function expand_ether_src_host(expr) local hi, lo = ehost_to_int(expr[2]) return { 'and', { '=', { '[ether]', MAC_SRC, 2 }, hi }, { '=', { '[ether]', MAC_SRC + 2, 4 }, lo } } end local function expand_ether_dst_host(expr) local hi, lo = ehost_to_int(expr[2]) return { 'and', { '=', { '[ether]', MAC_DST, 2 }, hi }, { '=', { '[ether]', MAC_DST + 2, 4 }, lo } } end local function expand_ether_host(expr) return { 'or', expand_ether_src_host(expr), expand_ether_dst_host(expr) } end local function expand_ether_broadcast(expr) local broadcast = { 'ehost', 255, 255, 255, 255, 255, 255 } local hi, lo = ehost_to_int(broadcast) return { 'and', { '=', { '[ether]', MAC_DST, 2 }, hi }, { '=', { '[ether]', MAC_DST + 2, 4 }, lo } } end local function expand_ether_multicast(expr) return { '!=', { '&', { '[ether]', 0, 1 }, 1 }, 0 } end -- Ether protos local function expand_ip(expr) return has_ether_protocol(PROTO_IPV4) end local function expand_ip6(expr) return has_ether_protocol(PROTO_IPV6) end local function expand_arp(expr) return has_ether_protocol(PROTO_ARP) end local function expand_rarp(expr) return has_ether_protocol(PROTO_RARP) end local function expand_atalk(expr) local ATALK_ID_1 = 491675 -- 0x7809B local ATALK_ID_2 = 2863268616 -- 0xaaaa0308 return { 'or', has_ether_protocol(PROTO_ATALK), { 'if', { '>', { '[ether]', ETHER_TYPE, 2}, ETHER_MAX_LEN }, { 'false' }, { 'and', { '=', { '[ether]', ETHER_PAYLOAD + 4, 2 }, ATALK_ID_1 }, { '=', { '[ether]', ETHER_PAYLOAD, 4 }, ATALK_ID_2 } } } } end local function expand_aarp(expr) local AARP_ID = 2863268608 -- 0xaaaa0300 return { 'or', has_ether_protocol(PROTO_AARP), { 'if', { '>', { '[ether]', ETHER_TYPE, 2}, ETHER_MAX_LEN }, { 'false' }, { 'and', { '=', { '[ether]', ETHER_PAYLOAD + 4, 2 }, PROTO_AARP }, { '=', { '[ether]', ETHER_PAYLOAD, 4 }, AARP_ID } } } } end local function expand_decnet(expr) return has_ether_protocol(PROTO_DECNET) end local function expand_sca(expr) return has_ether_protocol(PROTO_SCA) end local function expand_lat(expr) return has_ether_protocol(PROTO_LAT) end local function expand_mopdl(expr) return has_ether_protocol(PROTO_MOPDL) end local function expand_moprc(expr) return has_ether_protocol(PROTO_MOPRC) end local function expand_iso(expr) return { 'and', { '<=', { '[ether]', ETHER_TYPE, 2 }, ETHER_MAX_LEN }, { '=', { '[ether]', ETHER_PAYLOAD, 2 }, PROTO_ISO } } end local function expand_stp(expr) return { 'and', { '<=', { '[ether]', ETHER_TYPE, 2 }, ETHER_MAX_LEN }, { '=', { '[ether]', ETHER_PAYLOAD, 1 }, PROTO_STP } } end local function expand_ipx(expr) local IPX_SAP = 224 -- 0xe0 local IPX_CHECKSUM = 65535 -- 0xffff local AARP_ID = 2863268608 -- 0xaaaa0300 return { 'or', has_ether_protocol(PROTO_IPX), { 'if', { '>', { '[ether]', ETHER_TYPE, 2}, ETHER_MAX_LEN }, { 'false' }, { 'or', { 'and', { '=', { '[ether]', ETHER_PAYLOAD + 4, 2 }, PROTO_IPX }, { '=', { '[ether]', ETHER_PAYLOAD, 4 }, AARP_ID } }, { 'or', { '=', { '[ether]', ETHER_PAYLOAD, 1 }, IPX_SAP }, { '=', { '[ether]', ETHER_PAYLOAD, 2 }, IPX_CHECKSUM } } } } } end local function expand_netbeui(expr) return { 'and', { '<=', { '[ether]', ETHER_TYPE, 2 }, ETHER_MAX_LEN }, { '=', { '[ether]', ETHER_PAYLOAD, 2 }, PROTO_NETBEUI } } end local ether_protos = { ip = expand_ip, ip6 = expand_ip6, arp = expand_arp, rarp = expand_rarp, atalk = expand_atalk, aarp = expand_aarp, decnet = expand_decnet, sca = expand_sca, lat = expand_lat, mopdl = expand_mopdl, moprc = expand_moprc, iso = expand_iso, stp = expand_stp, ipx = expand_ipx, netbeui = expand_netbeui, } local function expand_ether_proto(expr) local proto = expr[2] if type(proto) == 'string' then return ether_protos[proto](expr) end return has_ether_protocol(proto) end -- Net local function expand_src_net(expr) local addr = expr local proto = expr[2][1] if proto:match("/len$") or proto:match("/mask$") then addr = expr[2] end if is_ipv6_addr(addr) then return expand_src_ipv6_host(addr) end return expand_src_host(addr) end local function expand_dst_net(expr) local addr = expr local proto = expr[2][1] if proto:match("/len$") or proto:match("/mask$") then addr = expr[2] end if is_ipv6_addr(addr) then return expand_dst_ipv6_host(addr) end return expand_dst_host(addr) end -- Format IPv4 expr: { 'net', { 'ipv4/len', { 'ipv4', 127, 0, 0, 0 }, 8 } } -- Format IPV6 expr: { 'net', { 'ipv6/len', { 'ipv6', 0, 0, 0, 0, 0, 0, 0, 1 }, 128 } } local function expand_net(expr) local addr = expr local proto = expr[2][1] if proto:match("/len$") or proto:match("/mask$") then addr = expr[2] end if is_ipv6_addr(addr) then return expand_ipv6_host(addr) end return expand_host(addr) end -- Packet length local function expand_less(expr) return { '<=', 'len', expr[2] } end local function expand_greater(expr) return { '>=', 'len', expr[2] } end -- DECNET local function expand_decnet_src(expr) local addr = expr[2] local addr_int = uint16(addr[2], addr[3]) return { 'if', { '=', { '&', { '[ether]', ETHER_PAYLOAD + 2, 1}, 7 }, 2 }, { '=', { '[ether]', ETHER_PAYLOAD + 5, 2}, addr_int }, { 'if', { '=', { '&', { '[ether]', ETHER_PAYLOAD + 2, 2}, 65287 }, 33026 }, { '=', { '[ether]', ETHER_PAYLOAD + 6, 2}, addr_int }, { 'if', { '=', { '&', { '[ether]', ETHER_PAYLOAD + 2, 1}, 7 }, 6 }, { '=', { '[ether]', ETHER_PAYLOAD + 17, 2}, addr_int }, { 'if', { '=', { '&', { '[ether]', ETHER_PAYLOAD + 2, 2}, 65287 }, 33030 }, { '=', { '[ether]', ETHER_PAYLOAD + 18, 2}, addr_int }, { 'false' } } } } } end local function expand_decnet_dst(expr) local addr = expr[2] local addr_int = uint16(addr[2], addr[3]) return { 'if', { '=', { '&', { '[ether]', ETHER_PAYLOAD + 2, 1}, 7 }, 2 }, { '=', { '[ether]', ETHER_PAYLOAD + 3, 2}, addr_int }, { 'if', { '=', { '&', { '[ether]', ETHER_PAYLOAD + 2, 2}, 65287 }, 33026 }, { '=', { '[ether]', ETHER_PAYLOAD + 4, 2}, addr_int }, { 'if', { '=', { '&', { '[ether]', ETHER_PAYLOAD + 2, 1}, 7 }, 6 }, { '=', { '[ether]', ETHER_PAYLOAD + 9, 2}, addr_int }, { 'if', { '=', { '&', { '[ether]', ETHER_PAYLOAD + 2, 2}, 65287 }, 33030 }, { '=', { '[ether]', ETHER_PAYLOAD + 10, 2}, addr_int }, { 'false' } } } } } end local function expand_decnet_host(expr) return { 'or', expand_decnet_src(expr), expand_decnet_dst(expr) } end -- IS-IS local L1_IIH = 15 -- 0x0F local L2_IIH = 16 -- 0x10 local PTP_IIH = 17 -- 0x11 local L1_LSP = 18 -- 0x12 local L2_LSP = 20 -- 0x14 local L1_CSNP = 24 -- 0x18 local L2_CSNP = 25 -- 0x19 local L1_PSNP = 26 -- 0x1A local L2_PSNP = 27 -- 0x1B local function expand_isis_protocol(...) local function concat(lop, reg, values, i) i = i or 1 if i == #values then return { '=', reg, values[i] } end return { lop, { '=', reg, values[i] }, concat(lop, reg, values, i+1) } end return { 'if', has_iso_protocol(PROTO_ISIS), concat('or', { '[ether]', ETHER_PAYLOAD + 7, 1 }, {...} ), { 'false' } } end local function expand_l1(expr) return expand_isis_protocol(L1_IIH, L1_LSP, L1_CSNP, L1_PSNP, PTP_IIH) end local function expand_l2(expr) return expand_isis_protocol(L2_IIH, L2_LSP, L2_CSNP, L2_PSNP, PTP_IIH) end local function expand_iih(expr) return expand_isis_protocol(L1_IIH, L2_IIH, PTP_IIH) end local function expand_lsp(expr) return expand_isis_protocol(L1_LSP, L2_LSP) end local function expand_snp(expr) return expand_isis_protocol(L1_CSNP, L2_CSNP, L1_PSNP, L2_PSNP) end local function expand_csnp(expr) return expand_isis_protocol(L1_CSNP, L2_CSNP) end local function expand_psnp(expr) return expand_isis_protocol(L1_PSNP, L2_PSNP) end local primitive_expanders = { dst = expand_dst_host, dst_host = expand_dst_host, dst_net = expand_dst_net, dst_port = expand_dst_port, dst_portrange = expand_dst_portrange, src = expand_src_host, src_host = expand_src_host, src_net = expand_src_net, src_port = expand_src_port, src_portrange = expand_src_portrange, host = expand_host, ether_src = expand_ether_src_host, ether_src_host = expand_ether_src_host, ether_dst = expand_ether_dst_host, ether_dst_host = expand_ether_dst_host, ether_host = expand_ether_host, ether_broadcast = expand_ether_broadcast, fddi_src = expand_ether_src_host, fddi_src_host = expand_ether_src_host, fddi_dst = expand_ether_dst_host, fddi_dst_host = expand_ether_dst_host, fddi_host = expand_ether_host, fddi_broadcast = expand_ether_broadcast, tr_src = expand_ether_src_host, tr_src_host = expand_ether_src_host, tr_dst = expand_ether_dst_host, tr_dst_host = expand_ether_dst_host, tr_host = expand_ether_host, tr_broadcast = expand_ether_broadcast, wlan_src = expand_ether_src_host, wlan_src_host = expand_ether_src_host, wlan_dst = expand_ether_dst_host, wlan_dst_host = expand_ether_dst_host, wlan_host = expand_ether_host, wlan_broadcast = expand_ether_broadcast, broadcast = expand_ether_broadcast, ether_multicast = expand_ether_multicast, multicast = expand_ether_multicast, ether_proto = expand_ether_proto, gateway = unimplemented, net = expand_net, port = expand_port, portrange = expand_portrange, less = expand_less, greater = expand_greater, ip = expand_ip, ip_proto = expand_ip4_proto, ip_protochain = expand_ip4_protochain, ip_host = expand_ip_host, ip_src = expand_ip_src_host, ip_src_host = expand_ip_src_host, ip_dst = expand_ip_dst_host, ip_dst_host = expand_ip_dst_host, ip_broadcast = expand_ip_broadcast, ip_multicast = expand_ip_multicast, ip6 = expand_ip6, ip6_proto = expand_ip6_proto, ip6_protochain = expand_ip6_protochain, ip6_broadcast = expand_ip6_broadcast, ip6_multicast = expand_ip6_multicast, proto = expand_ip_proto, tcp = function(expr) return has_ip_protocol(PROTO_TCP) end, tcp_port = expand_tcp_port, tcp_src_port = expand_tcp_src_port, tcp_dst_port = expand_tcp_dst_port, tcp_portrange = expand_tcp_portrange, tcp_src_portrange = expand_tcp_src_portrange, tcp_dst_portrange = expand_tcp_dst_portrange, udp = function(expr) return has_ip_protocol(PROTO_UDP) end, udp_port = expand_udp_port, udp_src_port = expand_udp_src_port, udp_dst_port = expand_udp_dst_port, udp_portrange = expand_udp_portrange, udp_src_portrange = expand_udp_src_portrange, udp_dst_portrange = expand_udp_dst_portrange, icmp = function(expr) return has_ip_protocol(PROTO_ICMP) end, icmp6 = function(expr) return has_ipv6_protocol(PROTO_ICMP6) end, igmp = function(expr) return has_ip_protocol(PROTO_IGMP) end, igrp = function(expr) return has_ip_protocol(PROTO_IGRP) end, pim = function(expr) return has_ip_protocol(PROTO_PIM) end, ah = function(expr) return has_ip_protocol(PROTO_AH) end, esp = function(expr) return has_ip_protocol(PROTO_ESP) end, vrrp = function(expr) return has_ip_protocol(PROTO_VRRP) end, sctp = function(expr) return has_ip_protocol(PROTO_SCTP) end, protochain = expand_ip_protochain, arp = expand_arp, arp_host = expand_arp_host, arp_src = expand_arp_src_host, arp_src_host = expand_arp_src_host, arp_dst = expand_arp_dst_host, arp_dst_host = expand_arp_dst_host, rarp = expand_rarp, rarp_host = expand_rarp_host, rarp_src = expand_rarp_src_host, rarp_src_host = expand_rarp_src_host, rarp_dst = expand_rarp_dst_host, rarp_dst_host = expand_rarp_dst_host, atalk = expand_atalk, aarp = expand_aarp, decnet = expand_decnet, decnet_src = expand_decnet_src, decnet_src_host = expand_decnet_src, decnet_dst = expand_decnet_dst, decnet_dst_host = expand_decnet_dst, decnet_host = expand_decnet_host, iso = expand_iso, stp = expand_stp, ipx = expand_ipx, netbeui = expand_netbeui, sca = expand_sca, lat = expand_lat, moprc = expand_moprc, mopdl = expand_mopdl, llc = unimplemented, ifname = unimplemented, on = unimplemented, rnr = unimplemented, rulenum = unimplemented, reason = unimplemented, rset = unimplemented, ruleset = unimplemented, srnr = unimplemented, subrulenum = unimplemented, action = unimplemented, wlan_ra = unimplemented, wlan_ta = unimplemented, wlan_addr1 = unimplemented, wlan_addr2 = unimplemented, wlan_addr3 = unimplemented, wlan_addr4 = unimplemented, type = unimplemented, type_subtype = unimplemented, subtype = unimplemented, dir = unimplemented, vlan = unimplemented, mpls = unimplemented, pppoed = unimplemented, pppoes = unimplemented, iso_proto = expand_iso_proto, clnp = function(expr) return has_iso_protocol(PROTO_CLNP) end, esis = function(expr) return has_iso_protocol(PROTO_ESIS) end, isis = function(expr) return has_iso_protocol(PROTO_ISIS) end, l1 = expand_l1, l2 = expand_l2, iih = expand_iih, lsp = expand_lsp, snp = expand_snp, csnp = expand_csnp, psnp = expand_psnp, vpi = unimplemented, vci = unimplemented, lane = unimplemented, oamf4s = unimplemented, oamf4e = unimplemented, oamf4 = unimplemented, oam = unimplemented, metac = unimplemented, bcc = unimplemented, sc = unimplemented, ilmic = unimplemented, connectmsg = unimplemented, metaconnect = unimplemented } local relops = set('<', '<=', '=', '!=', '>=', '>') local addressables = set( 'arp', 'rarp', 'wlan', 'ether', 'fddi', 'tr', 'ppp', 'slip', 'link', 'radio', 'ip', 'ip6', 'tcp', 'udp', 'icmp' ) local binops = set( '+', '-', '*', '*64', '/', '&', '|', '^', '&&', '||', '<<', '>>' ) local associative_binops = set( '+', '*', '*64', '&', '|', '^' ) local bitops = set('&', '|', '^') local unops = set('ntohs', 'ntohl', 'uint32') local leaf_primitives = set( 'true', 'false', 'fail' ) local function expand_offset(level, dlt) assert(dlt == "EN10MB", "Encapsulation other than EN10MB unimplemented") local function guard_expr(expr) local test, guards = expand_relop(expr, dlt) return concat(guards, { { test, { 'false' } } }) end local function guard_ether_protocol(proto) return concat(guard_expr(has_ether_protocol(proto)), guard_expr(has_ether_protocol_min_payload(proto))) end function guard_ipv4_protocol(proto) return concat(guard_expr(has_ipv4_protocol(proto)), guard_expr(has_ipv4_protocol_min_payload(proto))) end function guard_ipv6_protocol(proto) return concat(guard_expr(has_ipv6_protocol(proto)), guard_expr(has_ipv6_protocol_min_payload(proto))) end function guard_first_ipv4_fragment() return guard_expr(is_first_ipv4_fragment()) end function ipv4_payload_offset(proto) local ip_offset, guards = expand_offset('ip', dlt) if proto then guards = concat(guards, guard_ipv4_protocol(proto)) end guards = concat(guards, guard_first_ipv4_fragment()) local res = { '+', { '<<', { '&', { '[]', ip_offset, 1 }, 0xf }, 2 }, ip_offset } return res, guards end function ipv6_payload_offset(proto) local ip_offset, guards = expand_offset('ip6', dlt) if proto then guards = concat(guards, guard_ipv6_protocol(proto)) end return { '+', ip_offset, 40 }, guards end -- Note that unlike their corresponding predicates which detect -- either IPv4 or IPv6 traffic, [icmp], [udp], and [tcp] only work -- for IPv4. if level == 'ether' then return 0, {} elseif level == 'ether*' then return ETHER_PAYLOAD, {} elseif level == 'arp' then return ETHER_PAYLOAD, guard_ether_protocol(PROTO_ARP) elseif level == 'rarp' then return ETHER_PAYLOAD, guard_ether_protocol(PROTO_RARP) elseif level == 'ip' then return ETHER_PAYLOAD, guard_ether_protocol(PROTO_IPV4) elseif level == 'ip6' then return ETHER_PAYLOAD, guard_ether_protocol(PROTO_IPV6) elseif level == 'ip*' then return ipv4_payload_offset() elseif level == 'ip6*' then return ipv6_payload_offset() elseif level == 'icmp' then return ipv4_payload_offset(PROTO_ICMP) elseif level == 'udp' then return ipv4_payload_offset(PROTO_UDP) elseif level == 'tcp' then return ipv4_payload_offset(PROTO_TCP) elseif level == 'igmp' then return ipv4_payload_offset(PROTO_IGMP) elseif level == 'igrp' then return ipv4_payload_offset(PROTO_IGRP) elseif level == 'pim' then return ipv4_payload_offset(PROTO_PIM) elseif level == 'sctp' then return ipv4_payload_offset(PROTO_SCTP) elseif level == 'vrrp' then return ipv4_payload_offset(PROTO_VRRP) end error('invalid level '..level) end -- Returns two values: the expanded arithmetic expression and an ordered -- list of guards. A guard is a two-element array whose first element -- is a test expression. If all test expressions of the guards are -- true, then it is valid to evaluate the arithmetic expression. The -- second element of the guard array is the expression to which the -- relop will evaluate if the guard expression fails: either { 'false' } -- or { 'fail' }. function expand_arith(expr, dlt) assert(expr) if type(expr) == 'number' or filter_args[expr] then return expr, {} end local op = expr[1] if binops[op] then -- Use 64-bit multiplication by default. The optimizer will -- reduce this back to Lua's normal float multiplication if it -- can. if op == '*' then op = '*64' end local lhs, lhs_guards = expand_arith(expr[2], dlt) local rhs, rhs_guards = expand_arith(expr[3], dlt) -- Mod 2^32 to preserve uint32 range. local ret = { 'uint32', { op, lhs, rhs } } local guards = concat(lhs_guards, rhs_guards) -- RHS of division can't be 0. if op == '/' then local div_guard = { { '!=', rhs, 0 }, { 'fail' } } guards = concat(guards, { div_guard }) end return ret, guards end local is_addr = false if op == 'addr' then is_addr = true expr = expr[2] op = expr[1] end assert(op ~= '[]', "expr has already been expanded?") local addressable = assert(op:match("^%[(.+)%]$"), "bad addressable") local offset, offset_guards = expand_offset(addressable, dlt) local lhs, lhs_guards = expand_arith(expr[2], dlt) local size = expr[3] local len_test = { '<=', { '+', { '+', offset, lhs }, size }, 'len' } -- ip[100000] will abort the whole matcher. &ip[100000] will just -- cause the clause to fail to match. local len_guard = { len_test, is_addr and { 'false' } or { 'fail' } } local guards = concat(concat(offset_guards, lhs_guards), { len_guard }) local addr = { '+', offset, lhs } if is_addr then return addr, guards end local ret = { '[]', addr, size } if size == 1 then return ret, guards end if size == 2 then return { 'ntohs', ret }, guards end if size == 4 then return { 'uint32', { 'ntohl', ret } }, guards end error('unreachable') end function expand_relop(expr, dlt) local lhs, lhs_guards = expand_arith(expr[2], dlt) local rhs, rhs_guards = expand_arith(expr[3], dlt) return { expr[1], lhs, rhs }, concat(lhs_guards, rhs_guards) end function expand_bool(expr, dlt) assert(type(expr) == 'table', 'logical expression must be a table') if expr[1] == 'not' or expr[1] == '!' then return { 'if', expand_bool(expr[2], dlt), { 'false' }, { 'true' } } elseif expr[1] == 'and' or expr[1] == '&&' then return { 'if', expand_bool(expr[2], dlt), expand_bool(expr[3], dlt), { 'false' } } elseif expr[1] == 'or' or expr[1] == '||' then return { 'if', expand_bool(expr[2], dlt), { 'true' }, expand_bool(expr[3], dlt) } elseif relops[expr[1]] then -- An arithmetic relop. local res, guards = expand_relop(expr, dlt) -- We remove guards in LIFO order, resulting in an expression -- whose first guard expression is the first one that was added. while #guards ~= 0 do local guard = table.remove(guards) assert(guard[2]) res = { 'if', guard[1], res, guard[2] } end return res elseif expr[1] == 'if' then return { 'if', expand_bool(expr[2], dlt), expand_bool(expr[3], dlt), expand_bool(expr[4], dlt) } elseif leaf_primitives[expr[1]] then return expr else -- A logical primitive. local expander = primitive_expanders[expr[1]] assert(expander, "unimplemented primitive: "..expr[1]) local expanded = expander(expr, dlt) return expand_bool(expanded, dlt) end end function expand(expr, dlt) dlt = dlt or 'RAW' expr = expand_bool(expr, dlt) if verbose then pp(expr) end return expr end function selftest () print("selftest: pf.expand") local parse = require('pf.parse').parse local equals, assert_equals = utils.equals, utils.assert_equals assert_equals({ '=', 1, 2 }, expand(parse("1 = 2"), 'EN10MB')) assert_equals({ '=', 1, "len" }, expand(parse("1 = len"), 'EN10MB')) assert_equals({ 'if', { '!=', 2, 0}, { '=', 1, { 'uint32', { '/', 2, 2} } }, { 'fail'} }, expand(parse("1 = 2/2"), 'EN10MB')) assert_equals({ 'if', { '<=', { '+', { '+', 0, 0 }, 1 }, 'len'}, { '=', { '[]', { '+', 0, 0 }, 1 }, 2 }, { 'fail' } }, expand(parse("ether[0] = 2"), 'EN10MB')) assert_equals(expand(parse("src 1::ff11"), 'EN10MB'), expand(parse("src host 1::ff11"), 'EN10MB')) assert_equals(expand(parse("proto \\sctp"), 'EN10MB'), expand(parse("ip proto \\sctp or ip6 proto \\sctp"), 'EN10MB')) assert_equals(expand(parse("proto \\tcp"), 'EN10MB'), expand(parse("ip proto \\tcp or ip6 proto \\tcp"), 'EN10MB')) -- Could check this, but it's very large expand(parse("tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)"), "EN10MB") print("OK") end
apache-2.0
FREEZX/CMYKEscape
lib/Quickie/mouse.lua
1
3077
--[[ Copyright (c) 2012 Matthias Richter 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. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. 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 _M -- holds the module. needed to make widgetHit overridable local x,y = 0,0 local down = false local hot, active = nil, nil local NO_WIDGET = {} local function widgetHit(mouse, pos, size) return mouse[1] >= pos[1] and mouse[1] <= pos[1] + size[1] and mouse[2] >= pos[2] and mouse[2] <= pos[2] + size[2] end local function setHot(id) hot = id end local function setActive(id) active = id end local function isHot(id) return id == hot end local function isActive(id) return id == active end local function getHot() return hot end local function updateWidget(id, pos, size, hit) hit = hit or _M.widgetHit if hit({x,y}, pos, size) then setHot(id) if not active and down then setActive(id) end end end local function releasedOn(id) return not down and isHot(id) and isActive(id) end local function beginFrame() hot = nil x,y = love.mouse.getPosition() down = love.mouse.isDown('l') end local function endFrame() if not down then -- released setActive(nil) elseif not active then -- clicked outside setActive(NO_WIDGET) end end local function disable() --_M.beginFrame = nothing --_M.endFrame = nothing --_M.isHot = isHot, --_M.isActive = isActive, _M.updateWidget = function() end end local function enable() _M.updateWidget = updateWidget end _M = { widgetHit = widgetHit, setHot = setHot, getHot = getHot, setActive = setActive, isHot = isHot, isActive = isActive, updateWidget = updateWidget, releasedOn = releasedOn, beginFrame = beginFrame, endFrame = endFrame, disable = disable, enable = enable, } -- metatable provides getters to x, y and down return setmetatable(_M, {__index = function(_,k) return ({x = x, y = y, down = down})[k] end})
bsd-3-clause
SalvationDevelopment/Salvation-Scripts-TCG
c100000166.lua
2
2841
--酸のラスト・マシン・ウィルス function c100000166.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,TIMING_TOHAND) e1:SetCost(c100000166.cost) e1:SetTarget(c100000166.target) e1:SetOperation(c100000166.activate) c:RegisterEffect(e1) end function c100000166.costfilter(c) return c:IsAttribute(ATTRIBUTE_WATER) end function c100000166.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckReleaseGroup(tp,c100000166.costfilter,1,nil) end local g=Duel.SelectReleaseGroup(tp,c100000166.costfilter,1,1,nil) Duel.Release(g,REASON_COST) end function c100000166.tgfilter(c) return c:IsFaceup() and c:IsRace(RACE_MACHINE) and c:IsDestructable() end function c100000166.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local g=Duel.GetMatchingGroup(c100000166.tgfilter,tp,0,LOCATION_MZONE,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) end function c100000166.filter(c) return c:IsRace(RACE_MACHINE) end function c100000166.activate(e,tp,eg,ep,ev,re,r,rp) local conf=Duel.GetFieldGroup(tp,0,LOCATION_MZONE+LOCATION_HAND) if conf:GetCount()>0 then Duel.ConfirmCards(tp,conf) local dg=conf:Filter(c100000166.filter,nil) Duel.Destroy(dg,REASON_EFFECT) Duel.Damage(1-tp,dg:GetCount()*500,REASON_EFFECT) Duel.ShuffleHand(1-tp) end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCode(EVENT_DRAW) e1:SetOperation(c100000166.desop) e1:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN,3) Duel.RegisterEffect(e1,tp) local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_PHASE+PHASE_END) e2:SetCountLimit(1) e2:SetCondition(c100000166.turncon) e2:SetOperation(c100000166.turnop) e2:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN,3) Duel.RegisterEffect(e2,tp) e2:SetLabelObject(e1) e:GetHandler():RegisterFlagEffect(1082946,RESET_PHASE+PHASE_END+RESET_OPPO_TURN,0,3) c100000166[e:GetHandler()]=e2 end function c100000166.desop(e,tp,eg,ep,ev,re,r,rp) if ep==e:GetOwnerPlayer() then return end local hg=eg:Filter(Card.IsLocation,nil,LOCATION_HAND) if hg:GetCount()==0 then return end Duel.ConfirmCards(1-ep,hg) local dg=hg:Filter(c100000166.filter,nil) Duel.Destroy(dg,REASON_EFFECT) Duel.Damage(ep,dg:GetCount()*500,REASON_EFFECT) Duel.ShuffleHand(ep) end function c100000166.turncon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()~=tp end function c100000166.turnop(e,tp,eg,ep,ev,re,r,rp) local ct=e:GetLabel() ct=ct+1 e:SetLabel(ct) e:GetHandler():SetTurnCounter(ct) if ct==3 then e:GetLabelObject():Reset() e:GetOwner():ResetFlagEffect(1082946) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c59048135.lua
4
2988
--昇華する紋章 function c59048135.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --search local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(59048135,0)) e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_FZONE) e2:SetCountLimit(1) e2:SetCost(c59048135.thcost) e2:SetTarget(c59048135.thtg) e2:SetOperation(c59048135.thop) c:RegisterEffect(e2) --cannot be target local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET) e3:SetRange(LOCATION_FZONE) e3:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE) e3:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE) e3:SetTarget(c59048135.etarget) e3:SetValue(c59048135.evalue) c:RegisterEffect(e3) Duel.AddCustomActivityCounter(59048135,ACTIVITY_SUMMON,c59048135.counterfilter) Duel.AddCustomActivityCounter(59048135,ACTIVITY_SPSUMMON,c59048135.counterfilter) end function c59048135.counterfilter(c) return c:IsRace(RACE_PSYCHO) and c:IsType(TYPE_XYZ) or c:IsSetCard(0x76) end function c59048135.etarget(e,c) return c:IsRace(RACE_PSYCHO) and c:IsType(TYPE_XYZ) end function c59048135.evalue(e,re,rp) return re:IsActiveType(TYPE_SPELL+TYPE_TRAP) end function c59048135.cfilter(c) return c:IsSetCard(0x76) and c:IsType(TYPE_MONSTER) and c:IsDiscardable() end function c59048135.thcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetCustomActivityCount(59048135,tp,ACTIVITY_SUMMON)==0 and Duel.GetCustomActivityCount(59048135,tp,ACTIVITY_SPSUMMON)==0 and Duel.IsExistingMatchingCard(c59048135.cfilter,tp,LOCATION_HAND,0,1,nil) end Duel.DiscardHand(tp,c59048135.cfilter,1,1,REASON_COST+REASON_DISCARD,nil) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH) e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetTargetRange(1,0) e1:SetTarget(c59048135.splimit) Duel.RegisterEffect(e1,tp) local e2=e1:Clone() e2:SetCode(EFFECT_CANNOT_SUMMON) Duel.RegisterEffect(e2,tp) end function c59048135.splimit(e,c) return not (c:IsRace(RACE_PSYCHO) and c:IsType(TYPE_XYZ)) and not c:IsSetCard(0x76) end function c59048135.filter(c) return c:IsSetCard(0x92) and c:IsType(TYPE_SPELL+TYPE_TRAP) and not c:IsCode(59048135) and c:IsAbleToHand() end function c59048135.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c59048135.filter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c59048135.thop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c59048135.filter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
gpl-2.0
Turttle/darkstar
scripts/zones/North_Gustaberg/npcs/Monument.lua
34
1448
----------------------------------- -- Area: North Gustaberg -- NPC: Monument -- Involved in Quest "Hearts of Mythril" -- @pos 300.000 -62.803 498.200 106 ----------------------------------- package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/North_Gustaberg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Hearts = player:getQuestStatus(BASTOK,HEARTS_OF_MYTHRIL); if (Hearts == QUEST_ACCEPTED) then player:startEvent(0x000b); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x000b and option == 0) then player:setVar("HeartsOfMythril",1); player:delKeyItem(BOUQUETS_FOR_THE_PIONEERS); end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c52786469.lua
9
1156
--ラヴァル・ウォリアー function c52786469.initial_effect(c) --damage local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(52786469,0)) e1:SetCategory(CATEGORY_DAMAGE) e1:SetCode(EVENT_BATTLE_DESTROYING) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetCondition(c52786469.condition) e1:SetTarget(c52786469.target) e1:SetOperation(c52786469.operation) c:RegisterEffect(e1) end function c52786469.condition(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local bc=c:GetBattleTarget() e:SetLabel(bc:GetAttack()) return c:IsRelateToBattle() and bc:IsType(TYPE_MONSTER) end function c52786469.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(e:GetLabel()) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,e:GetLabel()) end function c52786469.operation(e,tp,eg,ep,ev,re,r,rp) if Duel.GetMatchingGroup(Card.IsSetCard,tp,LOCATION_GRAVE,0,nil,0x39):GetClassCount(Card.GetCode)<4 then return end local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c83546647.lua
2
2801
--無抵抗の真相 function c83546647.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_BATTLE_DAMAGE) e1:SetCondition(c83546647.condition) e1:SetCost(c83546647.cost) e1:SetTarget(c83546647.target) e1:SetOperation(c83546647.activate) e1:SetLabel(1) c:RegisterEffect(e1) end function c83546647.condition(e,tp,eg,ep,ev,re,r,rp) return eg:GetFirst():IsControler(1-tp) and ep==tp and Duel.GetAttackTarget()==nil end function c83546647.spfilter(c,e,tp) return c:GetLevel()==1 and not c:IsPublic() and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.IsExistingMatchingCard(c83546647.spfilter2,tp,LOCATION_DECK,0,1,nil,e,tp,c:GetCode()) end function c83546647.spfilter2(c,e,tp,code) return c:IsCode(code) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c83546647.cost(e,tp,eg,ep,ev,re,r,rp,chk) e:SetLabel(0) return true end function c83546647.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then if e:GetLabel()~=0 then return false end e:SetLabel(1) return not Duel.IsPlayerAffectedByEffect(tp,59822133) and Duel.GetLocationCount(tp,LOCATION_MZONE)>1 and Duel.IsExistingMatchingCard(c83546647.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM) local g=Duel.SelectMatchingCard(tp,c83546647.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp) local tc=g:GetFirst() Duel.ConfirmCards(1-tp,g) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_PUBLIC) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_CHAIN) tc:RegisterEffect(e1) local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_CHAIN_SOLVED) e2:SetRange(LOCATION_HAND) e2:SetOperation(c83546647.clearop) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_CHAIN) e2:SetLabel(Duel.GetCurrentChain()) e2:SetLabelObject(e1) tc:RegisterEffect(e2) Duel.SetTargetCard(g) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_HAND+LOCATION_DECK) end function c83546647.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.IsPlayerAffectedByEffect(tp,59822133) then return end if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end local tc1=Duel.GetFirstTarget() if not tc1:IsRelateToEffect(e) or not tc1:IsCanBeSpecialSummoned(e,0,tp,false,false) then return end local tc2=Duel.GetFirstMatchingCard(c83546647.spfilter2,tp,LOCATION_DECK,0,nil,e,tp,tc1:GetCode()) if tc2 then Duel.SpecialSummonStep(tc1,0,tp,tp,false,false,POS_FACEUP) Duel.SpecialSummonStep(tc2,0,tp,tp,false,false,POS_FACEUP) Duel.SpecialSummonComplete() end end function c83546647.clearop(e,tp,eg,ep,ev,re,r,rp) if ev~=e:GetLabel() then return end e:GetLabelObject():Reset() e:Reset() end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c99946920.lua
2
3467
--魔竜星-トウテツ function c99946920.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(99946920,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e1:SetCode(EVENT_TO_GRAVE) e1:SetCountLimit(1,99946920) e1:SetCondition(c99946920.condition) e1:SetTarget(c99946920.target) e1:SetOperation(c99946920.operation) c:RegisterEffect(e1) --synchro effect local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetCode(EVENT_FREE_CHAIN) e2:SetRange(LOCATION_MZONE) e2:SetHintTiming(0,TIMING_BATTLE_START+TIMING_BATTLE_END) e2:SetCountLimit(1) e2:SetCondition(c99946920.sccon) e2:SetTarget(c99946920.sctg) e2:SetOperation(c99946920.scop) c:RegisterEffect(e2) -- local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e3:SetCode(EVENT_BE_MATERIAL) e3:SetCondition(c99946920.atkcon) e3:SetOperation(c99946920.atkop) c:RegisterEffect(e3) end function c99946920.condition(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsReason(REASON_DESTROY) and c:IsReason(REASON_BATTLE+REASON_EFFECT) and c:IsPreviousLocation(LOCATION_ONFIELD) and c:GetPreviousControler()==tp end function c99946920.filter(c,e,tp) return c:IsSetCard(0x9e) and not c:IsCode(99946920) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c99946920.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c99946920.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c99946920.operation(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c99946920.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp) Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP_DEFENSE) end function c99946920.sccon(e,tp,eg,ep,ev,re,r,rp) if Duel.GetTurnPlayer()==tp then return false end local ph=Duel.GetCurrentPhase() return ph==PHASE_MAIN1 or (ph>=PHASE_BATTLE_START and ph<=PHASE_BATTLE) or ph==PHASE_MAIN2 end function c99946920.mfilter(c) return c:IsSetCard(0x9e) end function c99946920.sctg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then local mg=Duel.GetMatchingGroup(c99946920.mfilter,tp,LOCATION_MZONE,0,nil) return Duel.IsExistingMatchingCard(Card.IsSynchroSummonable,tp,LOCATION_EXTRA,0,1,nil,nil,mg) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) end function c99946920.scop(e,tp,eg,ep,ev,re,r,rp) local mg=Duel.GetMatchingGroup(c99946920.mfilter,tp,LOCATION_MZONE,0,nil) local g=Duel.GetMatchingGroup(Card.IsSynchroSummonable,tp,LOCATION_EXTRA,0,nil,nil,mg) if g:GetCount()>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg=g:Select(tp,1,1,nil) Duel.SynchroSummon(tp,sg:GetFirst(),nil,mg) end end function c99946920.atkcon(e,tp,eg,ep,ev,re,r,rp) return r==REASON_SYNCHRO end function c99946920.atkop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local rc=c:GetReasonCard() local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(99946920,1)) e1:SetProperty(EFFECT_FLAG_CLIENT_HINT) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_CHANGE_CONTROL) e1:SetReset(RESET_EVENT+0x1fe0000) rc:RegisterEffect(e1) end
gpl-2.0
patrikrm13/bostg
plugins/Welcome.lua
114
3529
local add_user_cfg = load_from_file('data/add_user_cfg.lua') local function template_add_user(base, to_username, from_username, chat_name, chat_id) base = base or '' to_username = '@' .. (to_username or '') from_username = '@' .. (from_username or '') chat_name = string.gsub(chat_name, '_', ' ') or '' chat_id = "chat#id" .. (chat_id or '') if to_username == "@" then to_username = '' end if from_username == "@" then from_username = '' end base = string.gsub(base, "{to_username}", to_username) base = string.gsub(base, "{from_username}", from_username) base = string.gsub(base, "{chat_name}", chat_name) base = string.gsub(base, "{chat_id}", chat_id) return base end function chat_new_user_link(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.from.username local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')' local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end function chat_new_user(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.action.user.username local from_username = msg.from.username local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end local function description_rules(msg, nama) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then local about = "" local rules = "" if data[tostring(msg.to.id)]["description"] then about = data[tostring(msg.to.id)]["description"] about = "\nAbout :\n"..about.."\n" end if data[tostring(msg.to.id)]["rules"] then rules = data[tostring(msg.to.id)]["rules"] rules = "\nRules :\n"..rules.."\n" end local sambutan = "Hi "..nama.."\nWelcome to '"..string.gsub(msg.to.print_name, "_", " ").."'\nYou can use /help for see bot commands\n" local text = sambutan..about..rules.."\n" local receiver = get_receiver(msg) send_large_msg(receiver, text, ok_cb, false) end end local function run(msg, matches) if not msg.service then return "Are you trying to troll me?" end --vardump(msg) if matches[1] == "chat_add_user" then if not msg.action.user.username then nama = string.gsub(msg.action.user.print_name, "_", " ") else nama = "@"..msg.action.user.username end chat_new_user(msg) description_rules(msg, nama) elseif matches[1] == "chat_add_user_link" then if not msg.from.username then nama = string.gsub(msg.from.print_name, "_", " ") else nama = "@"..msg.from.username end chat_new_user_link(msg) description_rules(msg, nama) elseif matches[1] == "chat_del_user" then local bye_name = msg.action.user.first_name return 'Sikout '..bye_name end end return { description = "Welcoming Message", usage = "send message to new member", patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$", "^!!tgservice (chat_del_user)$", }, run = run }
gpl-2.0
dickeyf/darkstar
scripts/zones/Yughott_Grotto/npcs/HomePoint#1.lua
27
1271
----------------------------------- -- Area: Yughott_Grotto -- NPC: HomePoint#1 -- @pos 434 -40.299 171 142 ----------------------------------- package.loaded["scripts/zones/Yughott_Grotto/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Yughott_Grotto/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 52); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c1697104.lua
2
3566
--PSYフレームギア・ε function c1697104.initial_effect(c) c:EnableUnsummonable() --splimit local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetValue(c1697104.splimit) c:RegisterEffect(e1) --spsummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(1697104,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_NEGATE+CATEGORY_DESTROY) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetRange(LOCATION_HAND) e2:SetCode(EVENT_CHAINING) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL) e2:SetCondition(c1697104.condition) e2:SetTarget(c1697104.target) e2:SetOperation(c1697104.operation) c:RegisterEffect(e2) end function c1697104.splimit(e,se,sp,st) return se:IsHasType(EFFECT_TYPE_ACTIONS) end function c1697104.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)==0 and ep~=tp and re:IsActiveType(TYPE_TRAP) and re:IsHasType(EFFECT_TYPE_ACTIVATE) and Duel.IsChainNegatable(ev) end function c1697104.spfilter(c,e,tp) return c:IsCode(49036338) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c1697104.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return not e:GetHandler():IsStatus(STATUS_CHAINING) and not Duel.IsPlayerAffectedByEffect(tp,59822133) and Duel.GetLocationCount(tp,LOCATION_MZONE)>1 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.IsExistingMatchingCard(c1697104.spfilter,tp,LOCATION_HAND+LOCATION_DECK+LOCATION_GRAVE,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_HAND+LOCATION_DECK+LOCATION_GRAVE) Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0) if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0) end end function c1697104.operation(e,tp,eg,ep,ev,re,r,rp) if Duel.IsPlayerAffectedByEffect(tp,59822133) then return end if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 or not e:GetHandler():IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c1697104.spfilter),tp,LOCATION_HAND+LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil,e,tp) if g:GetCount()==0 then return end local tc=g:GetFirst() local c=e:GetHandler() local fid=c:GetFieldID() Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) Duel.SpecialSummonStep(c,0,tp,tp,false,false,POS_FACEUP) tc:RegisterFlagEffect(1697104,RESET_EVENT+0x1fe0000,0,1,fid) c:RegisterFlagEffect(1697104,RESET_EVENT+0x1fe0000,0,1,fid) Duel.SpecialSummonComplete() g:AddCard(c) g:KeepAlive() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetCountLimit(1) e1:SetLabel(fid) e1:SetLabelObject(g) e1:SetCondition(c1697104.rmcon) e1:SetOperation(c1697104.rmop) Duel.RegisterEffect(e1,tp) if Duel.NegateActivation(ev) and re:GetHandler():IsRelateToEffect(re) then Duel.Destroy(eg,REASON_EFFECT) end end function c1697104.rmfilter(c,fid) return c:GetFlagEffectLabel(1697104)==fid end function c1697104.rmcon(e,tp,eg,ep,ev,re,r,rp) local g=e:GetLabelObject() if not g:IsExists(c1697104.rmfilter,1,nil,e:GetLabel()) then g:DeleteGroup() e:Reset() return false else return true end end function c1697104.rmop(e,tp,eg,ep,ev,re,r,rp) local g=e:GetLabelObject() local tg=g:Filter(c1697104.rmfilter,nil,e:GetLabel()) Duel.Remove(tg,POS_FACEUP,REASON_EFFECT) end
gpl-2.0
Turttle/darkstar
scripts/zones/Beadeaux_[S]/Zone.lua
28
1315
----------------------------------- -- -- Zone: Beadeaux_[S] (92) -- ----------------------------------- package.loaded["scripts/zones/Beadeaux_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Beadeaux_[S]/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-297.109,0.008,96.002,252); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Nak2/StormFox
lua/stormfox/cami/sh_cami.lua
1
13676
--[[ CAMI - Common Admin Mod Interface. Makes admin mods intercompatible and provides an abstract privilege interface for third party addons. IMPORTANT: This is a draft script. It is very much WIP. Follows the specification on this page: https://docs.google.com/document/d/1QIRVcAgZfAYf1aBl_dNV_ewR6P25wze2KmUVzlbFgMI Structures: CAMI_USERGROUP, defines the charactaristics of a usergroup: { Name string The name of the usergroup Inherits string The name of the usergroup this usergroup inherits from } CAMI_PRIVILEGE, defines the charactaristics of a privilege: { Name string The name of the privilege MinAccess string One of the following three: user/admin/superadmin Description string optional A text describing the purpose of the privilege HasAccess function( privilege :: CAMI_PRIVILEGE, actor :: Player, target :: Player ) :: bool optional Function that decides whether a player can execute this privilege, optionally on another player (target). } ]] -- Version number in YearMonthDay format. local version = 20150902.1 if CAMI and CAMI.Version >= version then return end CAMI = CAMI or {} CAMI.Version = version --[[ usergroups Contains the registered CAMI_USERGROUP usergroup structures. Indexed by usergroup name. ]] local usergroups = CAMI.GetUsergroups and CAMI.GetUsergroups() or { user = { Name = "user", Inherits = "user" }, admin = { Name = "admin", Inherits = "user" }, superadmin = { Name = "superadmin", Inherits = "admin" } } --[[ privileges Contains the registered CAMI_PRIVILEGE privilege structures. Indexed by privilege name. ]] local privileges = CAMI.GetPrivileges and CAMI.GetPrivileges() or {} --[[ CAMI.RegisterUsergroup Registers a usergroup with CAMI. Parameters: usergroup CAMI_USERGROUP (see CAMI_USERGROUP structure) source any Identifier for your own admin mod. Can be anything. Use this to make sure CAMI.RegisterUsergroup function and the CAMI.OnUsergroupRegistered hook don't cause an infinite loop Return value: CAMI_USERGROUP The usergroup given as argument. ]] function CAMI.RegisterUsergroup(usergroup, source) usergroups[usergroup.Name] = usergroup hook.Call("CAMI.OnUsergroupRegistered", nil, usergroup, source) return usergroup end --[[ CAMI.UnregisterUsergroup Unregisters a usergroup from CAMI. This will call a hook that will notify all other admin mods of the removal. Call only when the usergroup is to be permanently removed. Parameters: usergroupName string The name of the usergroup. source any Identifier for your own admin mod. Can be anything. Use this to make sure CAMI.UnregisterUsergroup function and the CAMI.OnUsergroupUnregistered hook don't cause an infinite loop Return value: bool Whether the unregistering succeeded. ]] function CAMI.UnregisterUsergroup(usergroupName, source) if not usergroups[usergroupName] then return false end local usergroup = usergroups[usergroupName] usergroups[usergroupName] = nil hook.Call("CAMI.OnUsergroupUnregistered", nil, usergroup, source) return true end --[[ CAMI.GetUsergroups Retrieves all registered usergroups. Return value: Table of CAMI_USERGROUP, indexed by their names. ]] function CAMI.GetUsergroups() return usergroups end --[[ CAMI.GetUsergroup Receives information about a usergroup. Return value: CAMI_USERGROUP Returns nil when the usergroup does not exist. ]] function CAMI.GetUsergroup(usergroupName) return usergroups[usergroupName] end --[[ CAMI.UsergroupInherits Returns true when usergroupName1 inherits usergroupName2. Note that usergroupName1 does not need to be a direct child. Every usergroup trivially inherits itself. Parameters: usergroupName1 string The name of the usergroup that is queried. usergroupName2 string The name of the usergroup of which is queried whether usergroupName1 inherits from. Return value: bool Whether usergroupName1 inherits usergroupName2. ]] function CAMI.UsergroupInherits(usergroupName1, usergroupName2) repeat if usergroupName1 == usergroupName2 then return true end usergroupName1 = usergroups[usergroupName1] and usergroups[usergroupName1].Inherits or usergroupName1 until not usergroups[usergroupName1] or usergroups[usergroupName1].Inherits == usergroupName1 -- One can only be sure the usergroup inherits from user if the -- usergroup isn't registered. return usergroupName1 == usergroupName2 or usergroupName2 == "user" end --[[ CAMI.InheritanceRoot All usergroups must eventually inherit either user, admin or superadmin. Regardless of what inheritance mechism an admin may or may not have, this always applies. This method always returns either user, admin or superadmin, based on what usergroups eventually inherit. Parameters: usergroupName string The name of the usergroup of which the root of inheritance is requested Return value: string The name of the root usergroup (either user, admin or superadmin) ]] function CAMI.InheritanceRoot(usergroupName) if not usergroups[usergroupName] then return end local inherits = usergroups[usergroupName].Inherits while inherits ~= usergroups[usergroupName].Inherits do usergroupName = usergroups[usergroupName].Inherits end return usergroupName end --[[ CAMI.RegisterPrivilege Registers a privilege with CAMI. Note: do NOT register all your admin mod's privileges with this function! This function is for third party addons to register privileges with admin mods, not for admin mods sharing the privileges amongst one another. Parameters: privilege CAMI_PRIVILEGE See CAMI_PRIVILEGE structure. Return value: CAMI_PRIVILEGE The privilege given as argument. ]] function CAMI.RegisterPrivilege(privilege) privileges[privilege.Name] = privilege hook.Call("CAMI.OnPrivilegeRegistered", nil, privilege) return privilege end --[[ CAMI.UnregisterPrivilege Unregisters a privilege from CAMI. This will call a hook that will notify all other admin mods of the removal. Call only when the privilege is to be permanently removed. Parameters: privilegeName string The name of the privilege. Return value: bool Whether the unregistering succeeded. ]] function CAMI.UnregisterPrivilege(privilegeName) if not privileges[privilegeName] then return false end local privilege = privileges[privilegeName] privileges[privilegeName] = nil hook.Call("CAMI.OnPrivilegeUnregistered", nil, privilege) return true end --[[ CAMI.GetPrivileges Retrieves all registered privileges. Return value: Table of CAMI_PRIVILEGE, indexed by their names. ]] function CAMI.GetPrivileges() return privileges end --[[ CAMI.GetPrivilege Receives information about a privilege. Return value: CAMI_PRIVILEGE when the privilege exists. nil when the privilege does not exist. ]] function CAMI.GetPrivilege(privilegeName) return privileges[privilegeName] end --[[ CAMI.PlayerHasAccess Queries whether a certain player has the right to perform a certain action. Note: this function does NOT return an immediate result! The result is in the callback! Parameters: actorPly Player The player of which is requested whether they have the privilege. privilegeName string The name of the privilege. callback function(bool, string) This function will be called with the answer. The bool signifies the yes or no answer as to whether the player is allowed. The string will optionally give a reason. targetPly Optional. The player on which the privilege is executed. extraInfoTbl Optional. Table containing extra information. Officially supported members: Fallback string Either of user/admin/superadmin. When no admin mod replies, the decision is based on the admin status of the user. Defaults to admin if not given. IgnoreImmunity bool Ignore any immunity mechanisms an admin mod might have. CommandArguments table Extra arguments that were given to the privilege command. Return value: None, the answer is given in the callback function in order to allow for the admin mod to perform e.g. a database lookup. ]] -- Default access handler local defaultAccessHandler = {["CAMI.PlayerHasAccess"] = function(_, actorPly, privilegeName, callback, _, extraInfoTbl) -- The server always has access in the fallback if not IsValid(actorPly) then return callback(true, "Fallback.") end local priv = privileges[privilegeName] local fallback = extraInfoTbl and ( not extraInfoTbl.Fallback and actorPly:IsAdmin() or extraInfoTbl.Fallback == "user" and true or extraInfoTbl.Fallback == "admin" and actorPly:IsAdmin() or extraInfoTbl.Fallback == "superadmin" and actorPly:IsSuperAdmin()) if not priv then return callback(fallback, "Fallback.") end callback( priv.MinAccess == "user" or priv.MinAccess == "admin" and actorPly:IsAdmin() or priv.MinAccess == "superadmin" and actorPly:IsSuperAdmin() , "Fallback.") end, ["CAMI.SteamIDHasAccess"] = function(_, _, _, callback) callback(false, "No information available.") end } function CAMI.PlayerHasAccess(actorPly, privilegeName, callback, targetPly, extraInfoTbl) hook.Call("CAMI.PlayerHasAccess", defaultAccessHandler, actorPly, privilegeName, callback, targetPly, extraInfoTbl) end --[[ CAMI.GetPlayersWithAccess Finds the list of currently joined players who have the right to perform a certain action. NOTE: this function will NOT return an immediate result! The result is in the callback! Parameters: privilegeName string The name of the privilege. callback function(players) This function will be called with the list of players with access. targetPly Optional. The player on which the privilege is executed. extraInfoTbl Optional. Table containing extra information. Officially supported members: Fallback string Either of user/admin/superadmin. When no admin mod replies, the decision is based on the admin status of the user. Defaults to admin if not given. IgnoreImmunity bool Ignore any immunity mechanisms an admin mod might have. CommandArguments table Extra arguments that were given to the privilege command. ]] function CAMI.GetPlayersWithAccess(privilegeName, callback, targetPly, extraInfoTbl) local allowedPlys = {} local allPlys = player.GetAll() local countdown = #allPlys local function onResult(ply, hasAccess, _) countdown = countdown - 1 if hasAccess then table.insert(allowedPlys, ply) end if countdown == 0 then callback(allowedPlys) end end for _, ply in pairs(allPlys) do CAMI.PlayerHasAccess(ply, privilegeName, function(...) onResult(ply, ...) end, targetPly, extraInfoTbl) end end --[[ CAMI.SteamIDHasAccess Queries whether a player with a steam ID has the right to perform a certain action. Note: the player does not need to be in the server for this to work. Note: this function does NOT return an immediate result! The result is in the callback! Parameters: actorSteam Player The SteamID of the player of which is requested whether they have the privilege. privilegeName string The name of the privilege. callback function(bool, string) This function will be called with the answer. The bool signifies the yes or no answer as to whether the player is allowed. The string will optionally give a reason. targetSteam Optional. The SteamID of the player on which the privilege is executed. extraInfoTbl Optional. Table containing extra information. Officially supported members: IgnoreImmunity bool Ignore any immunity mechanisms an admin mod might have. CommandArguments table Extra arguments that were given to the privilege command. Return value: None, the answer is given in the callback function in order to allow for the admin mod to perform e.g. a database lookup. ]] function CAMI.SteamIDHasAccess(actorSteam, privilegeName, callback, targetSteam, extraInfoTbl) hook.Call("CAMI.SteamIDHasAccess", defaultAccessHandler, actorSteam, privilegeName, callback, targetSteam, extraInfoTbl) end --[[ CAMI.SignalUserGroupChanged Signify that your admin mod has changed the usergroup of a player. This function communicates to other admin mods what it thinks the usergroup of a player should be. Listen to the hook to receive the usergroup changes of other admin mods. Parameters: ply Player The player for which the usergroup is changed old string The previous usergroup of the player. new string The new usergroup of the player. source any Identifier for your own admin mod. Can be anything. ]] function CAMI.SignalUserGroupChanged(ply, old, new, source) hook.Call("CAMI.PlayerUsergroupChanged", nil, ply, old, new, source) end --[[ CAMI.SignalSteamIDUserGroupChanged Signify that your admin mod has changed the usergroup of a disconnected player. This communicates to other admin mods what it thinks the usergroup of a player should be. Listen to the hook to receive the usergroup changes of other admin mods. Parameters: ply string The steam ID of the player for which the usergroup is changed old string The previous usergroup of the player. new string The new usergroup of the player. source any Identifier for your own admin mod. Can be anything. ]] function CAMI.SignalSteamIDUserGroupChanged(steamId, old, new, source) hook.Call("CAMI.SteamIDUsergroupChanged", nil, steamId, old, new, source) end
apache-2.0
mimetic/DIG-corona-library
examples/textrender/main.lua
1
10052
-- TextRender example -- -- Shows use of the textrender widget -- -- Sample code is MIT licensed, the same license which covers Lua itself -- http://en.wikipedia.org/wiki/MIT_License -- Copyright (C) 2015 David Gross. -- Copyright (C) 2014 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. --]] --[[ Demonstration of textrender.lua, a module for rendering styled text. textrender parameters: text = text to render font = font name, e.g. "AvenirNext-DemiBoldItalic" size = font size in pixels lineHeight = line height in pixels color = text color in an RGBa color table, e.g. {250, 0, 0, 255} width = Width of the text column, alignment = text alignment: "Left", "Right", "Center" opacity = text opacity (between 0 and 1, or as a percent, e.g. "50%" or 0.5 minCharCount = Minimum number of characters per line. Estimate low, e.g. 5 targetDeviceScreenSize = String of target screen size, in the form, "width,height", e.g. e.g. "1024,768". May be different from current screen size. letterspacing = (unused) maxHeight = Maximum height of the text column. Extra text will be hidden. minWordLen = Minimum length of a word shown at the end of a line. In good typesetting, we don't end our lines with single letter words like "a", so normally this value is 2. textstyles = A table of text styles, loaded using funx.loadTextStyles() defaultStyle = The name of the default text style for the text block cacheDir = the name of the cache folder to use inside system.CachesDirectory, e.g. "text_render_cache" --]] -- Run test for cache speed by drawing/redrawing local testCacheSpeed = false -- My useful function collection local funx = require("scripts.funx") local textrender = require("scripts.textrender.textrender") -- Make a local copy of the application settings global local screenW, screenH = display.contentWidth, display.contentHeight local viewableScreenW, viewableScreenH = display.viewableContentWidth, display.viewableContentHeight local screenOffsetW, screenOffsetH = display.contentWidth - display.viewableContentWidth, display.contentHeight - display.viewableContentHeight local midscreenX = screenW*(0.5) local midscreenY = screenH*(0.5) local textStyles = funx.loadTextStyles("assets/textstyles.txt", system.ResourceDirectory) local mytext = funx.readFile("assets/text-render-sample.html") -- To cache using files, set the cache directory -- Not recommended, as it is slower than using SQLite local cacheDir = "textrender_cache" funx.mkdir (cacheDir, "",false, system.CachesDirectory) local navbarHeight = 50 --===================================================================-- -- Page background --===================================================================-- local bkgd = display.newRect(0,0,screenW, screenH) bkgd:setFillColor(.9,.9,.9) funx.anchor(bkgd,"TopLeftReferencePoint") bkgd.x = 0 bkgd.y = 0 bkgd.strokeWidth = 0 bkgd:setStrokeColor(.2, .2, .2, 1) --===================================================================-- -- Build a scrolling text field. --===================================================================-- local width, height = display.contentWidth * .8, (display.contentHeight * .8) - 40 local x,y = 20, (display.contentHeight - height)/2 --===================================================================-- -- Background Rectangle local strokeWidth = 1 local padding = 0 local textblockBkgd = display.newRect(x - strokeWidth - padding , y - strokeWidth - padding, width + strokeWidth + 2*padding, height + strokeWidth + 2*padding) textblockBkgd:setFillColor( 1,1,1 ) funx.anchor(textblockBkgd,"TopLeftReferencePoint") textblockBkgd.x = x - padding textblockBkgd.y = y - padding textblockBkgd.strokeWidth = strokeWidth textblockBkgd:setStrokeColor( 0,0,0,0.3) --===================================================================-- textrender.clearAllCaches(cacheDir) local msgblock = display.newGroup() msgblock.x = x - padding msgblock.y = y - 40 local function removeMsgBlock() if (msgblock) then msgblock:removeSelf() msgblock = nil end end local function hyperlinkdemo( e ) local mytext = "<p style='font:Avenir;size:18px;'><i>A <u>hyperlink</u> was tapped! The text is <i><b>“" .. e.target._attr.text .. "”</b></p>" local params = { text = mytext, --loaded above width = width, maxHeight = 0, -- Set to zero, otherwise rendering STOPS after this amount! isHTML = true, } -- Clear existing message block removeMsgBlock() -- Create the message msgblock = textrender.autoWrappedText(params) msgblock.x = x - padding msgblock.y = y - 40 timer.performWithDelay( 3000, removeMsgBlock ) end --===================================================================-- -- Text Field local params = { text = mytext, --loaded above width = width, maxHeight = 0, -- Set to zero, otherwise rendering STOPS after this amount! isHTML = true, useHTMLSpacing = true, textstyles = textStyles, -- Not needed, but defaults font = "AvenirNext-Regular", size = "12", lineHeight = "16", color = {0, 0, 0, 255}, alignment = "Left", opacity = "100%", letterspacing = 0, defaultStyle = "Normal", -- The higher these are, the faster a row is wrapped minCharCount = 10, -- Minimum number of characters per line. Start low. Default is 5 minWordLen = 2, -- not necessary, might not even work targetDeviceScreenSize = screenW..","..screenH, -- Target screen size, may be different from current screen size -- The handler is the function executed when a hyperlink is tapped. -- It will get the HREF from the <a> tag. handler = hyperlinkdemo, -- cacheDir is empty so we do not use caching with files, instead we use the SQLite database -- which is faster. cacheDir = nil, cacheToDB = true, -- true is default, for fast caches using sql database } local textblock = textrender.autoWrappedText(params) --===================================================================-- -- Make the textblock a scrolling text block local options = { maxVisibleHeight = height, parentTouchObject = nil, hideBackground = true, backgroundColor = {1,1,1}, -- hidden by the above line -- Show an icon over scrolling fields: values are "over", "bottom", anything else otherwise defaults to top+bottom scrollingFieldIndicatorActive = true, -- "over", "bottom", else top and bottom scrollingFieldIndicatorLocation = "", -- image files scrollingFieldIndicatorIconOver = "scripts/textrender/assets/scrolling-indicator-1024.png", scrollingFieldIndicatorIconDown = "scripts/textrender/assets/scrollingfieldindicatoricon-down.png", scrollingFieldIndicatorIconUp = "scripts/textrender/assets/scrollingfieldindicatoricon-up.png", pageItemsFadeOutOpeningTime = 300, pageItemsFadeInOpeningTime = 500, pageItemsPrefadeOnOpeningTime = 500, } local textblock = textblock:fitBlockToHeight( options ) local yAdjustment = textblock.yAdjustment textblock.x = x textblock.y = y if (testCacheSpeed) then -- Remove for testing below, but now it is cached textblock:removeSelf() local startTime = system.getTimer() local doCache = true local n = 10 print ("Repeat textrender for "..n.." times.") if (doCache) then print ("( using Caching )") end for i = 1, n do print ("textrender #"..i ) -- Build params.cacheToDB = doCache textblock = textrender.autoWrappedText(params) local textblock = textblock:fitBlockToHeight( options ) local yAdjustment = textblock.yAdjustment textblock.x = x textblock.y = y -- Remove textblock:removeSelf() if (not doCache) then print ("Clear caches.") textrender.clearAllCaches(cacheDir) end end local totalTime = math.floor((system.getTimer() - startTime) * 100) / 100 print ("Time for "..n.." repetitions: ".. totalTime .. " milliseconds, average speed is " .. totalTime/n .. " milliseconds") textblock = textrender.autoWrappedText(params) local textblock = textblock:fitBlockToHeight( options ) local yAdjustment = textblock.yAdjustment textblock.x = x textblock.y = y end -- test cache speed --===================================================================-- -- Testing buttons local buttonX = screenW - 120 local buttonY = 60 local wf = false local function toggleWireframe() wf = not wf display.setDrawMode( "wireframe", wf ) if (not wf) then display.setDrawMode( "forceRender" ) end print ("WF = ",wf) end local widget = require ("widget") local wfb = widget.newButton{ label = "Wireframe", labelColor = { default={ 0,0,0 }, over={ 1, 0, 0, 0.5 } }, fontSize = 20, x =buttonX, y=buttonY, shape = "roundedRect", fillColor = { default={ .7,.7,.7 }, over={ .2, .2, .2 } }, onRelease = toggleWireframe, } wfb:toFront()
mit
dickeyf/darkstar
scripts/globals/spells/poisonga_iii.lua
27
1133
----------------------------------------- -- Spell: Poisonga III ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_POISON; local duration = 180; local pINT = caster:getStat(MOD_INT); local mINT = target:getStat(MOD_INT); local dINT = (pINT - mINT); local power = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 10 + 1; if power > 25 then power = 25; end local resist = applyResistanceEffect(caster,spell,target,dINT,ENFEEBLING_MAGIC_SKILL,0,effect); if (resist == 1 or resist == 0.5) then -- effect taken duration = duration * resist; if (target:addStatusEffect(effect,power,3,duration)) then spell:setMsg(236); else spell:setMsg(75); end else -- resist entirely. spell:setMsg(85); end return effect; end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c81992475.lua
3
2934
--彼岸の悪鬼 バルバリッチャ function c81992475.initial_effect(c) --self destroy local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_SELF_DESTROY) e1:SetCondition(c81992475.sdcon) c:RegisterEffect(e1) --Special Summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(81992475,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_HAND) e2:SetCountLimit(1,81992475) e2:SetCondition(c81992475.sscon) e2:SetTarget(c81992475.sstg) e2:SetOperation(c81992475.ssop) c:RegisterEffect(e2) --remove local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(81992475,1)) e3:SetCategory(CATEGORY_REMOVE+CATEGORY_DAMAGE) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY) e3:SetCode(EVENT_TO_GRAVE) e3:SetCountLimit(1,81992475) e3:SetTarget(c81992475.rmtg) e3:SetOperation(c81992475.rmop) c:RegisterEffect(e3) end function c81992475.sdfilter(c) return not c:IsFaceup() or not c:IsSetCard(0xb1) end function c81992475.sdcon(e) return Duel.IsExistingMatchingCard(c81992475.sdfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) end function c81992475.filter(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) end function c81992475.sscon(e,tp,eg,ep,ev,re,r,rp) return not Duel.IsExistingMatchingCard(c81992475.filter,tp,LOCATION_ONFIELD,0,1,nil) end function c81992475.sstg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c81992475.ssop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end function c81992475.rmfilter(c) return c:IsSetCard(0xb1) and not c:IsCode(81992475) and c:IsAbleToRemove() end function c81992475.rmtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c81992475.rmfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c81992475.rmfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectTarget(tp,c81992475.rmfilter,tp,LOCATION_GRAVE,0,1,3,nil) Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),0,0) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,g:GetCount()*300) end function c81992475.rmop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e) if g:GetCount()>0 and Duel.Remove(g,POS_FACEUP,REASON_EFFECT)~=0 then local rg=Duel.GetOperatedGroup() local ct=rg:FilterCount(Card.IsLocation,nil,LOCATION_REMOVED) if ct>0 then Duel.Damage(1-tp,ct*300,REASON_EFFECT) end end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c1248895.lua
9
1261
--連鎖破壊 function c1248895.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetTarget(c1248895.target) e1:SetOperation(c1248895.activate) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e2) local e3=e1:Clone() e3:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e3) end function c1248895.filter(c,e) return c:IsFaceup() and c:IsAttackBelow(2000) and c:IsCanBeEffectTarget(e) end function c1248895.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return eg:IsContains(chkc) end if chk==0 then return eg:IsExists(c1248895.filter,1,nil,e) end if eg:GetCount()==1 then Duel.SetTargetCard(eg) else Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET) local g=eg:FilterSelect(tp,c1248895.filter,1,1,nil,e) Duel.SetTargetCard(g) end end function c1248895.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() local tpe=tc:GetType() if bit.band(tpe,TYPE_TOKEN)~=0 then return end local dg=Duel.GetMatchingGroup(Card.IsCode,tc:GetControler(),LOCATION_DECK+LOCATION_HAND,0,nil,tc:GetCode()) Duel.Destroy(dg,REASON_EFFECT) end
gpl-2.0
walid55/all_wazer2
libs/dateparser.lua
114
6213
local difftime, time, date = os.difftime, os.time, os.date local format = string.format local tremove, tinsert = table.remove, table.insert local pcall, pairs, ipairs, tostring, tonumber, type, setmetatable = pcall, pairs, ipairs, tostring, tonumber, type, setmetatable local dateparser={} --we shall use the host OS's time conversion facilities. Dealing with all those leap seconds by hand can be such a bore. local unix_timestamp do local now = time() local local_UTC_offset_sec = difftime(time(date("!*t", now)), time(date("*t", now))) unix_timestamp = function(t, offset_sec) local success, improper_time = pcall(time, t) if not success or not improper_time then return nil, "invalid date. os.time says: " .. (improper_time or "nothing") end return improper_time - local_UTC_offset_sec - offset_sec end end local formats = {} -- format names local format_func = setmetatable({}, {__mode='v'}) --format functions ---register a date format parsing function function dateparser.register_format(format_name, format_function) if type(format_name)~="string" or type(format_function)~='function' then return nil, "improper arguments, can't register format handler" end local found for i, f in ipairs(format_func) do --for ordering if f==format_function then found=true break end end if not found then tinsert(format_func, format_function) end formats[format_name] = format_function return true end ---register a date format parsing function function dateparser.unregister_format(format_name) if type(format_name)~="string" then return nil, "format name must be a string" end formats[format_name]=nil end ---return the function responsible for handling format_name date strings function dateparser.get_format_function(format_name) return formats[format_name] or nil, ("format %s not registered"):format(format_name) end ---try to parse date string --@param str date string --@param date_format optional date format name, if known --@return unix timestamp if str can be parsed; nil, error otherwise. function dateparser.parse(str, date_format) local success, res, err if date_format then if not formats[date_format] then return 'unknown date format: ' .. tostring(date_format) end success, res = pcall(formats[date_format], str) else for i, func in ipairs(format_func) do success, res = pcall(func, str) if success and res then return res end end end return success and res end dateparser.register_format('W3CDTF', function(rest) local year, day_of_year, month, day, week local hour, minute, second, second_fraction, offset_hours local alt_rest year, rest = rest:match("^(%d%d%d%d)%-?(.*)$") day_of_year, alt_rest = rest:match("^(%d%d%d)%-?(.*)$") if day_of_year then rest=alt_rest end month, rest = rest:match("^(%d%d)%-?(.*)$") day, rest = rest:match("^(%d%d)(.*)$") if #rest>0 then rest = rest:match("^T(.*)$") hour, rest = rest:match("^([0-2][0-9]):?(.*)$") minute, rest = rest:match("^([0-6][0-9]):?(.*)$") second, rest = rest:match("^([0-6][0-9])(.*)$") second_fraction, alt_rest = rest:match("^%.(%d+)(.*)$") if second_fraction then rest=alt_rest end if rest=="Z" then rest="" offset_hours=0 else local sign, offset_h, offset_m sign, offset_h, rest = rest:match("^([+-])(%d%d)%:?(.*)$") local offset_m, alt_rest = rest:match("^(%d%d)(.*)$") if offset_m then rest=alt_rest end offset_hours = tonumber(sign .. offset_h) + (tonumber(offset_m) or 0)/60 end if #rest>0 then return nil end end year = tonumber(year) local d = { year = year and (year > 100 and year or (year < 50 and (year + 2000) or (year + 1900))), month = tonumber(month) or 1, day = tonumber(day) or 1, hour = tonumber(hour) or 0, min = tonumber(minute) or 0, sec = tonumber(second) or 0, isdst = false } local t = unix_timestamp(d, (offset_hours or 0) * 3600) if second_fraction then return t + tonumber("0."..second_fraction) else return t end end) do local tz_table = { --taken from http://www.timeanddate.com/library/abbreviations/timezones/ A = 1, B = 2, C = 3, D = 4, E=5, F = 6, G = 7, H = 8, I = 9, K = 10, L = 11, M = 12, N = -1, O = -2, P = -3, Q = -4, R = -5, S = -6, T = -7, U = -8, V = -9, W = -10, X = -11, Y = -12, Z = 0, EST = -5, EDT = -4, CST = -6, CDT = -5, MST = -7, MDT = -6, PST = -8, PDT = -7, GMT = 0, UT = 0, UTC = 0 } local month_val = {Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12} dateparser.register_format('RFC2822', function(rest) local year, month, day, day_of_year, week_of_year, weekday local hour, minute, second, second_fraction, offset_hours local alt_rest weekday, alt_rest = rest:match("^(%w%w%w),%s+(.*)$") if weekday then rest=alt_rest end day, rest=rest:match("^(%d%d?)%s+(.*)$") month, rest=rest:match("^(%w%w%w)%s+(.*)$") month = month_val[month] year, rest = rest:match("^(%d%d%d?%d?)%s+(.*)$") hour, rest = rest:match("^(%d%d?):(.*)$") minute, rest = rest:match("^(%d%d?)(.*)$") second, alt_rest = rest:match("^:(%d%d)(.*)$") if second then rest = alt_rest end local tz, offset_sign, offset_h, offset_m tz, alt_rest = rest:match("^%s+(%u+)(.*)$") if tz then rest = alt_rest offset_hours = tz_table[tz] else offset_sign, offset_h, offset_m, rest = rest:match("^%s+([+-])(%d%d)(%d%d)%s*(.*)$") offset_hours = tonumber(offset_sign .. offset_h) + (tonumber(offset_m) or 0)/60 end if #rest>0 or not (year and day and month and hour and minute) then return nil end year = tonumber(year) local d = { year = year and ((year > 100) and year or (year < 50 and (year + 2000) or (year + 1900))), month = month, day = tonumber(day), hour= tonumber(hour) or 0, min = tonumber(minute) or 0, sec = tonumber(second) or 0, isdst = false } return unix_timestamp(d, offset_hours * 3600) end) end dateparser.register_format('RFC822', formats.RFC2822) --2822 supercedes 822, but is not a strict superset. For our intents and purposes though, it's perfectly good enough dateparser.register_format('RFC3339', formats.W3CDTF) --RFC3339 is a subset of W3CDTF return dateparser
gpl-2.0
fgenesis/Aquaria_experimental
game_scripts/scripts/entities/guardian.lua
6
4894
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.n = 0 v.attackDelay = 2 local STATE_GETREADY = 1000 local STATE_FIRING = 1001 v.body = 0 function init(me) setupEntity(me) entity_setEntityType(me, ET_ENEMY) entity_initSkeletal(me, "Guardian") entity_generateCollisionMask(me) entity_setHealth(me, 64) entity_setDeathScene(me, true) entity_setState(me, STATE_WAIT) entity_setCullRadius(me, 2000) entity_scale(me, 2, 2) entity_setDeathScene(me, true) v.body = entity_getBoneByName(me, "Body") entity_setTargetRange(me, 2024) entity_setUpdateCull(me, 3000) loadSound("Guardian-Die") loadSound("Guardian-Attack") end function postInit(me) v.n = getNaija() entity_setTarget(me, v.n) local node = entity_getNearestNode(me, "FLIP") if node ~= 0 and node_isEntityIn(node, me) then entity_fh(me) end end function update(me, dt) --entity_updateMovement(me, dt) if entity_isState(me, STATE_WAIT) then if entity_isEntityInRange(me, v.n, 600) then entity_setState(me, STATE_GETREADY) end end if entity_isState(me, STATE_IDLE) then v.attackDelay = v.attackDelay - dt if v.attackDelay <= 0 then if not entity_isEntityInRange(me, v.n, 1024) or chance(10) then entity_setState(me, STATE_FIRING) else entity_setState(me, STATE_ATTACK) end end end if not entity_isState(me, STATE_WAIT) then overrideZoom(0.6, 1) end entity_handleShotCollisionsSkeletal(me) local bone = entity_collideSkeletalVsCircle(me, v.n) if bone ~= 0 then if entity_isfh(me) then entity_addVel(v.n, 2000, 0) else entity_addVel(v.n, -2000, 0) end entity_damage(v.n, me, 1) end if entity_isfh(me) then if entity_x(v.n) > entity_x(me) then entity_addVel(v.n, 1000, 0) end else if entity_x(v.n) > entity_x(me) then entity_addVel(v.n, -1000, 0) end end entity_clearTargetPoints(me) entity_addTargetPoint(me, bone_getWorldPosition(v.body)) end function enterState(me) if entity_isState(me, STATE_IDLE) then entity_animate(me, "ready", -1) elseif entity_isState(me, STATE_WAIT) then entity_animate(me, "wait", -1) elseif entity_isState(me, STATE_GETREADY) then entity_setStateTime(me, entity_animate(me, "getReady")) elseif entity_isState(me, STATE_ATTACK) then playSfx("Guardian-Attack") if entity_y(v.n) < entity_y(me) then entity_setStateTime(me, entity_animate(me, "attack")) else entity_setStateTime(me, entity_animate(me, "attack2")) end elseif entity_isState(me, STATE_DEATHSCENE) then playSfx("Guardian-Die") shakeCamera(4, 4) overrideZoom(0.5, 0.5) entity_setStateTime(me, 99) cam_toEntity(me) entity_setInvincible(v.n, true) watch(entity_animate(me, "die")) entity_color(me, 0, 0, 0, 1) watch(1) entity_setStateTime(me, 0.01) entity_setInvincible(v.n, false) cam_toEntity(v.n) elseif entity_isState(me, STATE_FIRING) then entity_setStateTime(me, entity_animate(me, "firing")) end end function exitState(me) if entity_isState(me, STATE_ATTACK) then v.attackDelay = 3 entity_setState(me, STATE_IDLE) elseif entity_isState(me, STATE_GETREADY) then entity_setState(me, STATE_IDLE) elseif entity_isState(me, STATE_DEATHSCENE) then overrideZoom(0, 0.5) elseif entity_isState(me, STATE_FIRING) then entity_setState(me, STATE_IDLE) end end function damage(me, attacker, bone, damageType, dmg) if entity_isState(me, STATE_WAIT) then entity_setState(me, STATE_GETREADY) return false end if bone == v.body then return true end return false end function animationKey(me, key) if entity_isState(me, STATE_FIRING) then if key == 2 or key == 4 or key == 6 then local s = createShot("Guardian", me, v.n, entity_getPosition(me)) if key == 2 then shot_setAimVector(s, -400, -100) elseif key == 4 then shot_setAimVector(s, -400, 0) elseif key == 6 then shot_setAimVector(s, -400, 100) end end end end function hitSurface(me) end function songNote(me, note) end function songNoteDone(me, note) end function song(me, song) end function activate(me) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c94940436.lua
9
1065
--磁力の召喚円 LV2 function c94940436.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c94940436.target) e1:SetOperation(c94940436.activate) c:RegisterEffect(e1) end function c94940436.filter(c,e,tp) return c:IsLevelBelow(2) and c:IsRace(RACE_MACHINE) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c94940436.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c94940436.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND) end function c94940436.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c94940436.filter,tp,LOCATION_HAND,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c111280.lua
2
3318
--黒魔導強化 function c111280.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e1:SetHintTiming(TIMING_DAMAGE_STEP) e1:SetCondition(c111280.condition) e1:SetTarget(c111280.target) e1:SetOperation(c111280.activate) c:RegisterEffect(e1) end c111280.card_code_list={46986414,38033121} function c111280.cfilter(c) return c:IsFaceup() and c:IsCode(46986414,38033121) end function c111280.condition(e,tp,eg,ep,ev,re,r,rp) local ct=Duel.GetMatchingGroupCount(c111280.cfilter,tp,LOCATION_ONFIELD+LOCATION_GRAVE,LOCATION_ONFIELD+LOCATION_GRAVE,nil) return ct>0 and (Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated()) end function c111280.filter(c) return c:IsFaceup() and c:IsRace(RACE_SPELLCASTER) and c:IsAttribute(ATTRIBUTE_DARK) end function c111280.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then local ct=Duel.GetMatchingGroupCount(c111280.cfilter,tp,LOCATION_ONFIELD+LOCATION_GRAVE,LOCATION_ONFIELD+LOCATION_GRAVE,nil) if ct<=1 then return Duel.IsExistingMatchingCard(c111280.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end return true end end function c111280.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(c111280.cfilter,tp,LOCATION_ONFIELD+LOCATION_GRAVE,LOCATION_ONFIELD+LOCATION_GRAVE,nil) local ct=g:GetCount() if ct>=1 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) local g=Duel.SelectMatchingCard(tp,c111280.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) local tc=g:GetFirst() if tc then Duel.HintSelection(g) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e1:SetValue(1000) tc:RegisterEffect(e1) end end if ct>=2 then local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_CHAINING) e2:SetOperation(c111280.chainop) e2:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e2,tp) local e3=Effect.CreateEffect(e:GetHandler()) e3:SetType(EFFECT_TYPE_FIELD) e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) e3:SetProperty(EFFECT_FLAG_SET_AVAILABLE) e3:SetTargetRange(LOCATION_ONFIELD,0) e3:SetTarget(c111280.indtg) e3:SetValue(c111280.indval) e3:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e3,tp) end if ct>=3 then local g=Duel.GetMatchingGroup(c111280.filter,tp,LOCATION_MZONE,0,nil) local tc=g:GetFirst() while tc do local e4=Effect.CreateEffect(e:GetHandler()) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_IMMUNE_EFFECT) e4:SetValue(c111280.efilter) e4:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e4:SetOwnerPlayer(tp) tc:RegisterEffect(e4) tc=g:GetNext() end end end function c111280.chainop(e,tp,eg,ep,ev,re,r,rp) if re:IsActiveType(TYPE_SPELL+TYPE_TRAP) and ep==tp then Duel.SetChainLimit(c111280.chainlm) end end function c111280.chainlm(e,rp,tp) return tp==rp end function c111280.indtg(e,c) return c:IsType(TYPE_SPELL+TYPE_TRAP) end function c111280.indval(e,re,rp) return rp~=e:GetHandlerPlayer() end function c111280.efilter(e,re) return e:GetOwnerPlayer()~=re:GetOwnerPlayer() end
gpl-2.0
dickeyf/darkstar
scripts/globals/items/nopales_salad_+1.lua
18
1170
----------------------------------------- -- ID: 5702 -- Item: Nopales Salad +1 -- Food Effect: 3Hrs, All Races ----------------------------------------- -- Strength 2 -- Agility 7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5702); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 2); target:addMod(MOD_AGI, 7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 2); target:delMod(MOD_AGI, 7); end;
gpl-3.0
Turttle/darkstar
scripts/zones/Riverne-Site_B01/mobs/Nimbus_Hippogryph.lua
23
1357
----------------------------------- -- Area: Riverne - Site B01 -- MOB: Nimbus Hippogryph -- Note: Place holder Imdugud ----------------------------------- require("scripts/zones/Riverne-Site_B01/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) -- Get Nimbus Hippogryph ID and check if it is a PH of Imdugud local mob = mob:getID(); -- Check if Nimbus Hippogryph is within the Imdugud_PH table if (Imdugud_PH[mob] ~= nil) then -- printf("%u is a PH",mob); -- Get Imdugud previous ToD local Imdugud_ToD = GetServerVariable("[POP]Imdugud"); -- Check if Imdugud window is open, and there is not an Imdugud popped already(ACTION_NONE = 0) if (Imdugud_ToD <= os.time(t) and GetMobAction(Imdugud) == 0) then -- printf("Imdugud window open"); -- Give Nimbus Hippogryph 10 percent chance to pop Imdugud if (math.random(1,10) == 5) then -- printf("Imdugud will pop"); UpdateNMSpawnPoint(Imdugud); GetMobByID(Imdugud):setRespawnTime(GetMobRespawnTime(mob)); SetServerVariable("[PH]Imdugud", mob); DeterMob(mob, true); end end end end;
gpl-3.0
dickeyf/darkstar
scripts/zones/Altar_Room/npcs/Hooknox.lua
13
1048
----------------------------------- -- Area: Altar Room -- NPC: Hooknox -- Type: Standard NPC -- @zone: 152 -- @pos -265.248 11.693 -102.547 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Altar_Room/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x002e); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
mika6020/powerbot
libs/lua-redis.lua
580
35599
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
agpl-3.0
TeleDALAD/TeleDALAD
bot/seedbot.lua
1
10200
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '1.0' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "all", "leave_ban", "admin" }, sudo_users = {139274725,tonumber(our_id)},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[Teleseed v2 - Open Source An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Admins @iwals [Founder] @imandaneshi [Developer] @Rondoozle [Developer] @seyedan25 [Manager] Special thanks to awkward_potato Siyanew topkecleon Vamptacus Our channels @teleseedch [English] @iranseed [persian] ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Grt a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] **U can use both "/" and "!" *Only admins and sudo can add bots in group *Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only admins and sudo can use res, setowner, commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id return group id or user id !help !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules <text> Set <text> as rules !set about <text> Set <text> as about !settings Returns group settings !newlink create/revoke your group link !link returns group link !owner returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] <text> Save <text> as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] returns user id "!res @username" !log will return group logs !banlist will return group ban list **U can use both "/" and "!" *Only owner and mods can add bots in group *Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c38777931.lua
6
1166
--リリース・リバース・バースト function c38777931.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,TIMING_END_PHASE) e1:SetCost(c38777931.cost) e1:SetTarget(c38777931.target) e1:SetOperation(c38777931.activate) c:RegisterEffect(e1) end function c38777931.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckReleaseGroup(tp,Card.IsSetCard,1,nil,0x107f) end local g=Duel.SelectReleaseGroup(tp,Card.IsSetCard,1,1,nil,0x107f) Duel.Release(g,REASON_COST) end function c38777931.filter(c) return c:IsFacedown() and c:IsType(TYPE_SPELL+TYPE_TRAP) end function c38777931.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c38777931.filter,tp,0,LOCATION_ONFIELD,1,nil) end local g=Duel.GetMatchingGroup(c38777931.filter,tp,0,LOCATION_ONFIELD,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) end function c38777931.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(c38777931.filter,tp,0,LOCATION_ONFIELD,nil) Duel.Destroy(g,REASON_EFFECT) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c29343734.lua
2
2026
--E・HERO エリクシーラー function c29343734.initial_effect(c) --fusion material c:EnableReviveLimit() aux.AddFusionProcCode4(c,21844576,58932615,84327329,79979666,true,true) --spsummon condition local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e2:SetCode(EFFECT_SPSUMMON_CONDITION) e2:SetValue(aux.fuslimit) c:RegisterEffect(e2) --attribute local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e3:SetRange(LOCATION_MZONE) e3:SetCode(EFFECT_ADD_ATTRIBUTE) e3:SetValue(0xf) c:RegisterEffect(e3) --return local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(29343734,0)) e4:SetCategory(CATEGORY_TODECK) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e4:SetCode(EVENT_SPSUMMON_SUCCESS) e4:SetCondition(c29343734.retcon) e4:SetTarget(c29343734.rettg) e4:SetOperation(c29343734.retop) c:RegisterEffect(e4) --atk local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_SINGLE) e5:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e5:SetRange(LOCATION_MZONE) e5:SetCode(EFFECT_UPDATE_ATTACK) e5:SetValue(c29343734.val) c:RegisterEffect(e5) end c29343734.material_setcode=0x8 function c29343734.retcon(e,tp,eg,ep,ev,re,r,rp) return bit.band(e:GetHandler():GetSummonType(),SUMMON_TYPE_FUSION)==SUMMON_TYPE_FUSION end function c29343734.rettg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local g=Duel.GetMatchingGroup(Card.IsAbleToDeck,tp,LOCATION_REMOVED,LOCATION_REMOVED,nil) Duel.SetOperationInfo(0,CATEGORY_TODECK,g,g:GetCount(),0,0) end function c29343734.retop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(nil,tp,LOCATION_REMOVED,LOCATION_REMOVED,nil) Duel.SendtoDeck(g,nil,2,REASON_EFFECT) end function c29343734.atkfilter(c,att) return c:IsFaceup() and c:IsAttribute(att) end function c29343734.val(e,c) return Duel.GetMatchingGroupCount(c29343734.atkfilter,c:GetControler(),0,LOCATION_MZONE,nil,c:GetAttribute())*300 end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c20644748.lua
3
3215
--宇宙の収縮 function c20644748.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCondition(c20644748.condition) c:RegisterEffect(e1) --adjust local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE) e2:SetCode(EVENT_ADJUST) e2:SetRange(LOCATION_SZONE) e2:SetOperation(c20644748.adjustop) c:RegisterEffect(e2) -- local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetRange(LOCATION_SZONE) e3:SetCode(EFFECT_MAX_MZONE) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetTargetRange(1,1) e3:SetValue(c20644748.mvalue) c:RegisterEffect(e3) local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_FIELD) e4:SetRange(LOCATION_SZONE) e4:SetCode(EFFECT_MAX_SZONE) e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e4:SetTargetRange(1,1) e4:SetValue(c20644748.svalue) c:RegisterEffect(e4) local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_FIELD) e5:SetRange(LOCATION_SZONE) e5:SetCode(EFFECT_CANNOT_ACTIVATE) e5:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e5:SetTargetRange(1,1) e5:SetValue(c20644748.aclimit) c:RegisterEffect(e5) local e6=Effect.CreateEffect(c) e6:SetType(EFFECT_TYPE_FIELD) e6:SetRange(LOCATION_SZONE) e6:SetCode(EFFECT_CANNOT_SSET) e6:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e6:SetTargetRange(1,1) e6:SetTarget(c20644748.setlimit) c:RegisterEffect(e6) end function c20644748.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0)<=5 and Duel.GetFieldGroupCount(tp,0,LOCATION_ONFIELD)<=5 end function c20644748.adjustop(e,tp,eg,ep,ev,re,r,rp) local phase=Duel.GetCurrentPhase() if (phase==PHASE_DAMAGE and not Duel.IsDamageCalculated()) or phase==PHASE_DAMAGE_CAL then return end local c1=Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0) local c2=Duel.GetFieldGroupCount(tp,0,LOCATION_ONFIELD) if c1>5 or c2>5 then local g=Group.CreateGroup() if c1>5 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g1=Duel.SelectMatchingCard(tp,nil,tp,LOCATION_ONFIELD,0,c1-5,c1-5,nil) g:Merge(g1) end if c2>5 then Duel.Hint(HINT_SELECTMSG,1-tp,HINTMSG_TOGRAVE) local g2=Duel.SelectMatchingCard(1-tp,nil,1-tp,LOCATION_ONFIELD,0,c2-5,c2-5,nil) g:Merge(g2) end Duel.SendtoGrave(g,REASON_EFFECT) Duel.Readjust() end end function c20644748.mvalue(e,fp,rp,r) return 5-Duel.GetFieldGroupCount(fp,LOCATION_SZONE,0) end function c20644748.svalue(e,fp,rp,r) local ct=5 for i=5,7 do if Duel.GetFieldCard(fp,LOCATION_SZONE,i) then ct=ct-1 end end return ct-Duel.GetFieldGroupCount(fp,LOCATION_MZONE,0) end function c20644748.aclimit(e,re,tp) if not re:IsHasType(EFFECT_TYPE_ACTIVATE) then return false end if re:IsActiveType(TYPE_FIELD) then return not Duel.GetFieldCard(tp,LOCATION_SZONE,5) and Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0)>4 elseif re:IsActiveType(TYPE_PENDULUM) then return Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0)>4 end return false end function c20644748.setlimit(e,c,tp) return c:IsType(TYPE_FIELD) and not Duel.GetFieldCard(tp,LOCATION_SZONE,5) and Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0)>4 end
gpl-2.0
mimetic/DIG-corona-library
examples/slideviewer+textrender+accordion/scripts/dmc/dmc_corona/dmc_wamp/protocol.lua
1
26967
--====================================================================-- -- dmc_wamp/protocol.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-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. --]] --[[ Wamp support adapted from: * AutobahnPython (https://github.com/tavendo/AutobahnPython/) --]] --====================================================================-- --== DMC Corona Library : DMC WAMP Protocol --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "1.0.0" --====================================================================-- --== Imports local json = require 'json' local Objects = require 'lib.dmc_lua.lua_objects' local Patch = require 'lib.dmc_lua.lua_patch' local LuaEventsMixin = require 'lib.dmc_lua.lua_events_mix' local Utils = require 'lib.dmc_lua.lua_utils' local WError = require 'dmc_wamp.exception' local WFutureMixin = require 'dmc_wamp.future_mix' local WMessageFactory = require 'dmc_wamp.message' local WRole = require 'dmc_wamp.role' local WTypes = require 'dmc_wamp.types' local WUtils = require 'dmc_wamp.utils' --====================================================================-- --== Setup, Constants Patch.addPatch( 'table-pop' ) local EventsMix = LuaEventsMixin.EventsMix local FutureMix = WFutureMixin.FutureMix -- setup some aliases to make code cleaner local newClass = Objects.newClass local Class = Objects.Class local tpop = table.pop --====================================================================-- --== Endpoint Class --====================================================================-- --[[ --]] local Endpoint = newClass( nil, {name="Endpoint"} ) function Endpoint:__new__( params ) params = params or {} self:superCall( '__new__', params ) --==-- assert( params.obj ) assert( params.fn ) assert( params.procedure ) self.obj = params.obj self.fn = params.fn self.procedure = params.procedure self.options = params.options end --====================================================================-- --== Handler Class --====================================================================-- --[[ --]] local Handler = newClass( nil, {name="Handler"} ) function Handler:__new__( params ) params = params or {} self:superCall( '__new__', params ) --==-- assert( params.fn ) assert( params.topic ) self.obj = params.obj self.fn = params.fn self.topic = params.topic self.details_arg = params.details_arg -- this addition is for more Corona-ism -- used in added unsubscribe() method to Session self.subscription = params.subscription end --====================================================================-- --== Publication Class --====================================================================-- --[[ Object representing a publication. This class implements :class:`autobahn.wamp.interfaces.IPublication`. --]] local Publication = newClass( nil, {name="Publication"} ) function Publication:__new__( params ) params = params or {} self:superCall( '__new__', params ) --==-- assert( params.publication_id ) self.id = params.publication_id end --====================================================================-- --== Subscription Class --====================================================================-- --[[ Object representing a subscription. This class implements :class:`autobahn.wamp.interfaces.ISubscription`. --]] local Subscription = newClass( nil, {name="Subscription"} ) function Subscription:__new__( params ) params = params or {} self:superCall( '__new__', params ) --==-- assert( params.session ) assert( params.subscription_id ) self._session = params.session self.id = params.subscription_id self.active = true end -- Implements :func:`autobahn.wamp.interfaces.ISubscription.unsubscribe` -- function Subscription:unsubscribe() -- print( "Subscription:unsubscribe" ) return self._session:_unsubscribe( self ) end --====================================================================-- --== Registration Class --====================================================================-- --[[ Object representing a registration. This class implements :class:`autobahn.wamp.interfaces.IRegistration`. --]] local Registration = newClass( nil, {name="Registration"} ) function Registration:__new__( params ) params = params or {} self:superCall( '__new__', params ) --==-- assert( params.session ) assert( params.registration_id ) self._session = params.session self.id = params.registration_id self.active = true -- this is a shortcut i put in the code -- autobahn handles it another way self.endpoint = params.endpoint end -- Implements :func:`autobahn.wamp.interfaces.IRegistration.unregister` -- function Registration:unregister() -- print( "Registration:unregister" ) return self._session:_unregister( self ) end --====================================================================-- --== Base Session Class --====================================================================-- --[[ WAMP session base class. This class implements: :class:`autobahn.wamp.interfaces.ISession` --]] local BaseSession = newClass( { Class, EventsMix }, {name="Base Session"} ) function BaseSession:__new__( params ) params = params or {} Class.__new__( self, params ) EventsMix.__init__( self, params ) --==-- --== Create Properties ==-- -- for library-level debugging self.debug = false -- this is for app level debugging. exceptions raised in user code -- will get logged (that is, when invoking remoted procedures or -- when invoking event handlers) self.debug_app = false -- this is for marshalling traceback from exceptions thrown in user -- code within WAMP error messages (that is, when invoking remoted -- procedures) self.traceback_app = false -- mapping of exception classes to WAMP error URIs self._ecls_to_uri_pat = {} -- mapping of WAMP error URIs to exception classes self._uri_to_ecls = {} -- session authentication information self._authid = None self._authrole = None self._authmethod = None self._authprovider = None end -- Implements :func:`autobahn.wamp.interfaces.ISession.onConnect` -- function BaseSession:onConnect() -- print( "BaseSession:onConnect" ) --==-- end -- Implements :func:`autobahn.wamp.interfaces.ISession.onJoin` -- function BaseSession:onJoin( params ) -- print( "BaseSession:onJoin" ) --==-- end -- Implements :func:`autobahn.wamp.interfaces.ISession.onLeave` -- function BaseSession:onLeave( params ) -- print( "BaseSession:onLeave" ) --==-- end -- Implements :func:`autobahn.wamp.interfaces.ISession.onDisconnect` -- function BaseSession:onDisconnect() -- print( "BaseSession:onDisconnect" ) --==-- end -- Implements :func:`autobahn.wamp.interfaces.ISession.define` -- function BaseSession:define( params ) -- print( "BaseSession:define" ) --==-- -- TODO: fill this out end -- Create a WAMP error message from an exception -- function BaseSession:_message_from_exception( params ) -- print( "BaseSession:_message_from_exception" ) --==-- -- TODO: fill this out end -- Create a user (or generic) exception from a WAMP error message -- function BaseSession:_exception_from_message( params ) -- print( "BaseSession:_exception_from_message" ) --==-- -- TODO: fill this out end --====================================================================-- --== Application Session Class --====================================================================-- --[[ WAMP endpoint session. This class implements: * :class:`autobahn.wamp.interfaces.IPublisher` * :class:`autobahn.wamp.interfaces.ISubscriber` * :class:`autobahn.wamp.interfaces.ICaller` * :class:`autobahn.wamp.interfaces.ICallee` ?? * :class:`autobahn.wamp.interfaces.ITransportHandler` --]] local Session = newClass( { BaseSession, FutureMix }, { name="WAMP Session" } ) --== Event Constants ==-- Session.EVENT = 'wamp_session_event' Session.ONJOIN = 'on_join_wamp_event' Session.ONCHALLENGE = 'on_challenge_wamp_event' --======================================================-- -- Start: Setup DMC Objects function Session:__new__( params ) -- print( "Session:__new__" ) params = params or {} BaseSession.__new__( self, params ) FutureMix.__init__( self, params ) --==-- --== Create Properties ==-- -- realm, authid, authmethods self.config = params.config or WTypes.ComponentConfig{ realm='default' } self._transport = nil self._session_id = nil self._realm = nil self._session_id = nil self._goodbye_sent = nil self._transport_is_closing = nil -- outstanding requests self._publish_reqs = {} self._subscribe_reqs = {} self._unsubscribe_reqs = {} self._call_reqs = {} self._register_reqs = {} self._unregister_reqs = {} -- subscriptions in place self._subscriptions = {} -- registrations in place self._registrations = {} -- incoming invocations self._invocations = {} end -- END: Setup DMC Objects --======================================================-- --====================================================================-- --== Public Methods -- Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onOpen` -- function Session:onOpen( params ) -- print( "Session:onOpen" ) params = params or {} --==-- assert( params.transport ) self._transport = params.transport self:onConnect() end -- Implements :func:`autobahn.wamp.interfaces.ISession.onConnect` -- function Session:onConnect() -- print( "Session:onConnect" ) self:join{ realm=self.config.realm, authid=self.config.authid, authmethods=self.config.authmethods } end -- Implements :func:`autobahn.wamp.interfaces.ISession.join` -- :params: -- realm -- authmethods -- authid -- function Session:join( params ) -- print( "Session:join", params, params.authid ) params = params or {} --==-- assert( type( params.realm ) == 'string' ) assert( params.authid == nil or type( params.authid ) == 'string' ) assert( params.authmethods == nil or type( params.authmethods ) == 'table' ) if self._session_id then error( "Session:join :: already joined" ) end local roles, msg self._goodbye_sent = false roles = { WRole.RolePublisherFeatures(), WRole.RoleSubscriberFeatures({publication_trustlevels=true}), WRole.RoleCallerFeatures(), WRole.RoleCalleeFeatures() } msg = WMessageFactory.Hello{ realm=params.realm, roles=roles, authmethods=params.authmethods, authid=params.authid } self._realm = params.realm self._transport:send( msg ) end -- Implements :func:`autobahn.wamp.interfaces.ISession.disconnect` -- function Session:disconnect( details ) -- print( "Session:disconnect" ) if self._transport then self._transport:close( details.reason, details.message ) else -- transport not available error( "Session:disconnect :: transport not available" ) end end -- Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onMessage` -- function Session:onMessage( msg ) -- print( "Session:onMessage", msg ) if self._session_id == nil then -- the first message must be WELCOME, ABORT or CHALLENGE .. -- if msg:isa( WMessageFactory.Welcome ) then self._session_id = msg.session local details details = WTypes.SessionDetails{ realm=self._realm, session=self._session_id, authid=msg.authid, authrole=msg.authrole, authmethod=msg.authmethod, authprovider=msg.authprovider -- this is missing from autobahn } -- don't know why Autobahn has this as a future -- self:_as_future( self.onJoin, { details } ) -- changing to regular method call (like was in earlier release) self:onJoin( details ) elseif msg:isa( WMessageFactory.Abort ) then self:onLeave( WTypes.CloseDetails{ reason=msg.reason, message=msg.message } ) elseif msg:isa( WMessageFactory.Challenge ) then local challenge, def local success_f, failure_f local onChallenge_f = self.config.onchallenge if type( onChallenge_f ) ~= 'function' then error( WError.ProtocolError( "Received %s incorrect onChallenge" % 'fdsf' ) ) end challenge = WTypes.Challenge{ method=msg.method, extra=msg.extra } def = self:_as_future( onChallenge_f, { challenge } ) success_f = function( signature ) -- print( "Challenge: success callback", signature ) local reply = WMessageFactory.Authenticate{ signature = signature, } self._transport:send( reply ) end failure_f = function( err ) -- print( "Challenge: failure callback" ) end self:_add_future_callbacks( def, success_f, failure_f ) else error( WError.ProtocolError( "Received %s message, and session is not yet established" % msg.NAME ) ) end return end --== Goodbye Message if msg:isa( WMessageFactory.Goodbye ) then if not self._goodbye_sent then local reply = WMessageFactory.Goodbye:new() self._transport:send( reply ) end self._session_id = nil self:onLeave( WTypes.CloseDetails( { reason=msg.reason, message=msg.message } )) --== Event Message elseif msg:isa( WMessageFactory.Event ) then if not self._subscriptions[ msg.subscription ] then error( WError.ProtocolError( "EVENT received for non-subscribed subscription ID" ) ) end local handler = self._subscriptions[ msg.subscription ] -- TODO: event details local evt = { args=msg.args, kwargs=msg.kwargs } if handler.obj then handler.fn( handler.obj, evt ) else handler.fn( evt ) end -- TODO: exception handling --== Published Message elseif msg:isa( WMessageFactory.Published ) then if not self._publish_reqs[ msg.request ] then error( WError.ProtocolError( "PUBLISHED received for non-pending request ID" ) ) return end local pub_req = tpop( self._publish_reqs, msg.request ) local def, opts = unpack( pub_req ) local pub = Publication:new{ publication=msg.publication } self:_resolve_future( def, pub ) --== Subscribed Message elseif msg:isa( WMessageFactory.Subscribed ) then -- print("onMessage:Subscribed") if not self._subscribe_reqs[ msg.request ] then error( WError.ProtocolError( "SUBSCRIBED received for non-pending request ID" ) ) return end local sub_req = tpop( self._subscribe_reqs, msg.request ) local def, obj, func, topic, options = unpack( sub_req ) local sub = Subscription:new{ session=self, subscription_id=msg.subscription } self._subscriptions[ msg.subscription ] = Handler:new{ obj=obj, fn=func, topic=topic, details_arg=options.details_arg, subscription=sub } self:_resolve_future( def, sub ) --== Unsubscribed Message elseif msg:isa( WMessageFactory.Unsubscribed ) then if not self._unsubscribe_reqs[ msg.request ] then error( WError.ProtocolError( "UNSUBSCRIBED received for non-pending request ID" ) ) return end local unsub_req = tpop( self._unsubscribe_reqs, msg.request ) local def, sub = unpack( unsub_req ) self._subscriptions[sub.id] = nil sub.active = false self:_resolve_future( def ) --== Result Message elseif msg:isa( WMessageFactory.Result ) then if not self._call_reqs[ msg.request ] then error( WError.ProtocolError( "RESULT received for non-pending request ID" ) ) return end -- Progress -- if msg.progress then local _, opts = self._call_reqs[ msg.request ] if opts.onProgress then opts.onProgress( msg.args, msg.kwargs ) end -- Result -- else local call_req = tpop( self._call_reqs, msg.request ) local def, opts = unpack( call_req ) if not msg.args and not msg.kwargs then self:_resolve_future( def, nil ) else local res = WTypes.CallResult:new{ results=msg.args, kwresults=msg.kwargs } self:_resolve_future( def, res ) end end --== Invocation Message elseif msg:isa( WMessageFactory.Invocation ) then if self._invocations[ msg.request ] then error( WError.ProtocolError( "Invocation: already received request for this id" ) ) return end if not self._registrations[ msg.registration ] then error( WError.ProtocolError( "Invocation: don't have this registration ID" ) ) return end local registration = self._registrations[ msg.registration ] local endpoint = registration.endpoint -- TODO: implement Call Details -- if endpoint.options and endpoint.options.details_arg then -- msg.kwargs = msg.kwargs or {} -- if msg.receive_progress then -- else -- end -- end local def_params, def, def_func local success_f, failure_f if not endpoint.obj then def_func = endpoint.fn else def_func = function( ... ) endpoint.fn( endpoint.obj, ... ) end end def = self:_as_future( def_func, msg.args, msg.kwargs ) success_f = function( res ) -- print("Invocation: success callback") self._invocations[ msg.request ] = nil local reply = WMessageFactory.Yield:new{ request = msg.request, args = res.results, kwargs = res.kwresults } self._transport:send( reply ) end failure_f = function( err ) -- print("Invocation: failure callback") self._invocations[ msg.request ] = nil end self._invocations[ msg.request ] = def self:_add_future_callbacks( def, success_f, failure_f ) --== Interrupt Message elseif msg:isa( WMessageFactory.Interrupt ) then error( "not implemented" ) --== Registered Message elseif msg:isa( WMessageFactory.Registered ) then if not self._register_reqs[ msg.request ] then error( WError.ProtocolError( "REGISTERED received for non-pending request ID" ) ) end local reg_req = tpop( self._register_reqs, msg.request ) local obj, fn, procedure, options = unpack( reg_req ) local endpoint = Endpoint:new{ obj=obj, fn=fn, procedure=procedure, options=options } self._registrations[ msg.registration ] = Registration:new{ session=self, registration_id=msg.registration, endpoint=endpoint } --== Unregistered Message elseif msg:isa( WMessageFactory.Unregistered ) then if not self._unregister_reqs[ msg.request ] then error( WError.ProtocolError( "UNREGISTERED received for non-pending request ID" ) ) end local unreg_req = tpop( self._unregister_reqs, msg.request ) local def, registration = unpack( unreg_req ) self._registrations[ registration.id ] = nil registration.active = false self:_resolve_future( def, nil ) --== Unregistered Message elseif msg:isa( WMessageFactory.Error ) then --== Unregistered Message elseif msg:isa( WMessageFactory.Heartbeat ) then else if onError then onError( "unknown message class", msg:class().NAME ) end end end -- Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onClose` -- function Session:onClose( msg, onError ) -- print( "Session:onClose" ) self._transport = nil if self._session_id then self:onLeave() self._session_id = nil end self:onDisconnect() end -- Implements :func:`autobahn.wamp.interfaces.ISession.onChallenge` --[[ https://github.com/crossbario/crossbar/wiki/WAMP%20CRA%20Authentication this page has a totally different way of dealing with onChallenge the JavaScript frontend example shows onChallenge being passed in from there as a function --]] -- -- function Session:onChallenge( challenge ) -- print( "Session:onChallenge", challenge, self ) -- end -- Implements :func:`autobahn.wamp.interfaces.ISession.onJoin` -- function Session:onJoin( details ) -- print( "Session:onJoin", details ) self:dispatchEvent( self.ONJOIN, {details=details} ) end -- Implements :func:`autobahn.wamp.interfaces.ISession.onLeave` -- @param details type.SessionDetails function Session:onLeave( details ) -- print( "Session:onLeave" ) self:disconnect( details ) end -- Implements :func:`autobahn.wamp.interfaces.ISession.leave` -- function Session:leave( params ) -- print( "Session:leave" ) params = params or {} params.reason = params.reason or 'wamp.close.normal' --==-- if not self._session_id then error( "not joined" ); return end if self._goodbye_sent then error( "Already requested to close the session" ) else local msg = WMessageFactory.Goodbye:new( params ) self._transport:send( msg ) self._goodbye_sent = true end end -- Implements :func:`autobahn.wamp.interfaces.IPublisher.publish` -- function Session:publish( topic, params ) -- print( "Session:publish" ) params = params or {} --==-- assert( topic ) if not self._transport then error( WError.TransportError() ) end local opts = params.options or {} local request = WUtils.id() local msg, p p = { request=request, topic=topic, args=params.args, kwargs=params.kwargs } -- layer in Publish message options if opts.options then p = Utils.extend( opts.options, p ) end msg = WMessageFactory.Publish:new( p ) if opts.acknowledge == true then local def = self:_create_future() self._publish_reqs[ request ] = { def, opts } self._transport:send( msg ) return def else self._transport:send( msg ) return end end -- Implements :func:`autobahn.wamp.interfaces.ISubscriber.subscribe` -- function Session:subscribe( topic, handler, params ) -- print( "Session:subscribe", topic, handler, params ) params = params or {} --==-- assert( topic ) if not self._transport then error( WError.TransportLostError() ) end -- TODO: register on object -- TODO: change onEvent, onSubscribe ? add params to array local function _subscribe(obj, handler, topic, prms) local request, def, msg request = WUtils.id() def = self:_create_future() self._subscribe_reqs[ request ] = { def, obj, handler, topic, prms } msg = WMessageFactory.Subscribe:new{ request=request, topic=topic, options=prms.options } self._transport:send( msg ) return def end if type(handler)=='function' then return _subscribe( nil, handler, topic, params ) else error( "to be implemented" ) end end --[[ This is an addition specifically for Corona SDK it's more of a Corona-ism --]] function Session:unsubscribe( topic, callback ) -- print( "Session:unsubscribe", topic, callback ) for _, handler in pairs( self._subscriptions ) do if handler.topic == topic and handler.fn == callback then handler.subscription:unsubscribe() break end end end -- Called from :meth:`autobahn.wamp.protocol.Subscription.unsubscribe` -- function Session:_unsubscribe( subscription ) -- print( "Session:_unsubscribe", subscription ) --==-- assert( subscription:isa( Subscription ) ) assert( subscription.active ) assert( self._subscriptions[subscription.id]~=nil ) if not self._transport then error( WError.TransportLostError() ) end local def, request, msg request = WUtils.id() def = self:_create_future() self._unsubscribe_reqs[request] = { def, subscription } msg = WMessageFactory.Unsubscribe:new{ request=request, subscription=subscription.id } self._transport:send( msg ) return def end function Session:call( procedure, params ) -- print( "Session:call", procedure ) params = params or {} --==-- assert( type(procedure)=='string' ) if not self._transport then error( WError.TransportLostError() ) end local opts = params.options or {} local def, request, msg, p def = self:_create_future() request = WUtils.id() p = { request = request, procedure = procedure, args = params.args, kwargs = params.kwargs, } -- layer in Call message options if opts.options then p = Utils.extend( opts.options, p ) end msg = WMessageFactory.Call:new( p ) self._call_reqs[ request ] = { def, opts } self._transport:send( msg ) return def end -- Implements :func:`autobahn.wamp.interfaces.ICallee.register` -- function Session:register( endpoint, params ) -- print( "Session:register", endpoint ) params = params or {} params.options = params.options or {} --==-- if not self._transport then error( WError.TransportLostError() ) end local function _register( obj, endpoint, procedure, options ) -- print( "_register" ) local request, msg request = WUtils.id() self._register_reqs[ request ] = { obj, endpoint, procedure, options } msg = WMessageFactory.Register:new{ request = request, procedure = procedure, pkeys = options.pkeys, disclose_caller = options.disclose_caller, } self._transport:send( msg ) end if type( endpoint ) == 'function' then -- register single callable _register( nil, endpoint, params.procedure, params.options ) elseif type( endpoint ) == 'table' then -- register all methods of "wamp_procedure" -- TODO error( "WAMP:register(): object endpoint not implemented" ) else error( "WAMP:register(): not a proper endpoint type" ) end end function Session:unregister( handler, params ) -- print( "Session:unregister", handler, params ) for i, reg in pairs( self._registrations ) do local endpoint = reg.endpoint if type( handler ) == 'function' and endpoint.fn == handler then reg:unsubscribe() else -- TODO: unregister an object handler end end end -- Called from :meth:`autobahn.wamp.protocol.Registration.unregister` -- function Session:_unregister( registration ) -- print( "Session:_unregister", registration ) assert( registration:isa( Registration ) ) assert( registration.active ) assert( self._registrations[ registration.id ] ) if not self._transport then error( WError.TransportLostError() ) end local request, def, msg request = WUtils.id() def = self._create_future() self._unregister_reqs[ request ] = { def, registration } msg = WMessageFactory.Unregister:new{ request=request, registration=registration.id } self._transport:send(msg) end --====================================================================-- --== Protocol Facade --====================================================================-- return { Session=Session }
mit
dickeyf/darkstar
scripts/zones/Mount_Zhayolm/npcs/Runic_Portal.lua
3
1938
----------------------------------- -- Area: Mount Zhayolm -- NPC: Runic Portal -- Mount Zhayolm Teleporter Back to Aht Urgan Whitegate -- @pos 688 -23 349 61 ----------------------------------- package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil; ----------------------------------- require("scripts/globals/besieged"); require("scripts/globals/teleports"); require("scripts/globals/missions"); require("scripts/zones/Mount_Zhayolm/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(TOAU)== IMMORTAL_SENTRIES) then if (player:getVar("TOAUM2") == 1) then player:startEvent(0x006F); else player:startEvent(0x006D); end elseif (player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then if (hasRunicPortal(player,4) == 1) then player:startEvent(0x006D); else player:startEvent(0x006F); end else player:messageSpecial(RESPONSE); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x006F and option == 1) then if (player:getVar("TOAUM2") == 1) then player:setVar("TOAUM2",2); end player:addNationTeleport(AHTURHGAN,16); toChamberOfPassage(player); elseif (csid == 0x006D and option == 1) then toChamberOfPassage(player); end end;
gpl-3.0
MOSAVI17/FLOGBOT
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0