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
Arcscion/Shadowlyre
scripts/zones/Arrapago_Reef/mobs/Medusa.lua
3
1467
----------------------------------- -- Area: Arrapago Reef -- MOB: Medusa -- !pos -458 -20 458 -- TODO: resists, attack/def boosts ----------------------------------- require("scripts/globals/titles"); require("scripts/zones/Arrapago_Reef/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("eeshpp", math.random(5,99)); -- Uses EES randomly during the fight end; ----------------------------------- -- onMobEngaged Action ----------------------------------- function onMobEngaged(mob, target) local mobID = mob:getID(); target:showText(mob, MEDUSA_ENGAGE); SpawnMob(mobID+1, 180):updateEnmity(target); SpawnMob(mobID+2, 180):updateEnmity(target); SpawnMob(mobID+3, 180):updateEnmity(target); SpawnMob(mobID+4, 180):updateEnmity(target); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local HPP = mob:getHPP(); if (mob:getLocalVar("usedees") == 0) then if (HPP <= mob:getLocalVar("eeshpp")) then mob:useMobAbility(1931); -- Eagle Eye Shot mob:setLocalVar("usedees", 1); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:showText(mob, MEDUSA_DEATH); player:addTitle(GORGONSTONE_SUNDERER); end;
gpl-3.0
sbodenstein/nn
SelectTable.lua
7
1367
local SelectTable, parent = torch.class('nn.SelectTable', 'nn.Module') function SelectTable:__init(index) parent.__init(self) self.index = index self.gradInput = {} end function SelectTable:updateOutput(input) assert(math.abs(self.index) <= #input, "arg 1 table idx out of range") if self.index < 0 then self.output = input[#input + self.index + 1] else self.output = input[self.index] end return self.output end local function zeroTableCopy(t1, t2) for k, v in pairs(t2) do if (torch.type(v) == "table") then t1[k] = zeroTableCopy(t1[k] or {}, t2[k]) else if not t1[k] then t1[k] = v:clone():zero() else local tensor = t1[k] if not tensor:isSameSizeAs(v) then t1[k]:resizeAs(v) t1[k]:zero() end end end end return t1 end function SelectTable:updateGradInput(input, gradOutput) if self.index < 0 then self.gradInput[#input + self.index + 1] = gradOutput else self.gradInput[self.index] = gradOutput end zeroTableCopy(self.gradInput, input) for i=#input+1, #self.gradInput do self.gradInput[i] = nil end return self.gradInput end function SelectTable:type(type) self.gradInput = {} self.output = {} return parent.type(self, type) end
bsd-3-clause
jono659/enko
scripts/globals/weaponskills/piercing_arrow.lua
30
1643
----------------------------------- -- Piercing Arrow -- Archery weapon skill -- Skill level: 40 -- Ignores enemy's defense. Amount ignored varies with TP. -- The amount of defense ignored is 0% with 100TP, 35% with 200TP and 50% with 300TP. -- Typically does less damage than Flaming Arrow. -- Aligned with the Snow Gorget & Light Gorget. -- Aligned with the Snow Belt & Light Belt. -- Element: None -- Modifiers: STR:20% ; AGI:50% -- 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.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; 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%, 35%, 50% as per wiki.bluegartr.com params.ignoresDef = true; params.ignored100 = 0; params.ignored200 = 0.35; params.ignored300 = 0.5; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.2; params.agi_wsc = 0.5; end local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/The_Celestial_Nexus/mobs/Eald_narche.lua
23
2908
----------------------------------- -- Area: The Celestial Nexus -- MOB: Eald'Narche - Phase 1 -- Zilart Mission 16 BCNM Fight ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) --50% fast cast, no standback mob:addMod(MOD_UFASTCAST, 50); mob:setMobMod(MOBMOD_HP_STANDBACK,-1); end ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:SetAutoAttackEnabled(false); mob:setMobMod(MOBMOD_GA_CHANCE,25); mob:addStatusEffectEx(EFFECT_PHYSICAL_SHIELD, 0, 1, 0, 0); mob:addStatusEffectEx(EFFECT_ARROW_SHIELD, 0, 1, 0, 0); mob:addStatusEffectEx(EFFECT_MAGIC_SHIELD, 0, 1, 0, 0); end; ----------------------------------- -- onMobEngaged Action ----------------------------------- function onMobEngaged(mob, target) mob:addStatusEffectEx(EFFECT_SILENCE, 0, 1, 0, 5); GetMobByID(mob:getID() + 1):updateEnmity(target); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) if (mob:getBattleTime() % 9 <= 2) then local orbital1 = mob:getID()+3; local orbital2 = mob:getID()+4; if (GetMobAction(orbital1) == ACTION_NONE) then GetMobByID(orbital1):setPos(mob:getPos()); SpawnMob(orbital1):updateEnmity(target); elseif (GetMobAction(orbital2) == ACTION_NONE) then GetMobByID(orbital2):setPos(mob:getPos()); SpawnMob(orbital2):updateEnmity(target); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) DespawnMob(mob:getID()+1); DespawnMob(mob:getID()+3); DespawnMob(mob:getID()+4); local battlefield = player:getBattlefield(); player:startEvent(0x7d04, battlefield:getBattlefieldNumber()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("updateCSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) -- printf("finishCSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x7d04) then DespawnMob(target:getID()); mob = SpawnMob(target:getID()+2); mob:updateEnmity(player); --the "30 seconds of rest" you get before he attacks you, and making sure he teleports first in range mob:addStatusEffectEx(EFFECT_BIND, 0, 1, 0, 30); mob:addStatusEffectEx(EFFECT_SILENCE, 0, 1, 0, 40); end end;
gpl-3.0
jono659/enko
scripts/zones/Inner_Horutoto_Ruins/npcs/_5cs.lua
17
2436
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: _5cs (Magical Gizmo) #4 -- Involved In Mission: The Horutoto Ruins Experiment ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- The Magical Gizmo Number, this number will be compared to the random -- value created by the mission The Horutoto Ruins Experiment, when you -- reach the Gizmo Door and have the cutscene local magical_gizmo_no = 4; -- of the 6 -- Check if we are on Windurst Mission 1-1 if(player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 2) then -- Check if we found the correct Magical Gizmo or not if(player:getVar("MissionStatus_rv") == magical_gizmo_no) then player:startEvent(0x0036); else if(player:getVar("MissionStatus_op4") == 2) then -- We've already examined this player:messageSpecial(EXAMINED_RECEPTACLE); else -- Opened the wrong one player:startEvent(0x0037); end end end return 1; 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 we just finished the cutscene for Windurst Mission 1-1 -- The cutscene that we opened the correct Magical Gizmo if(csid == 0x0036) then player:setVar("MissionStatus",3); player:setVar("MissionStatus_rv", 0); player:addKeyItem(CRACKED_MANA_ORBS); player:messageSpecial(KEYITEM_OBTAINED,CRACKED_MANA_ORBS); elseif(csid == 0x0037) then -- Opened the wrong one player:setVar("MissionStatus_op4", 2); -- Give the message that thsi orb is not broken player:messageSpecial(NOT_BROKEN_ORB); end end;
gpl-3.0
jono659/enko
scripts/globals/items/blackened_frog.lua
35
1741
----------------------------------------- -- ID: 4536 -- Item: Blackened Frog -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 2 -- Agility 2 -- Mind -2 -- Attack % 14 -- Attack Cap 60 -- Ranged ATT % 14 -- Ranged ATT Cap 60 -- Enmity -5 ----------------------------------------- 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,4536); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_AGI, 2); target:addMod(MOD_MND, -2); target:addMod(MOD_FOOD_ATTP, 14); target:addMod(MOD_FOOD_ATT_CAP, 60); target:addMod(MOD_FOOD_RATTP, 14); target:addMod(MOD_FOOD_RATT_CAP, 60); target:addMod(MOD_ENMITY, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_AGI, 2); target:delMod(MOD_MND, -2); target:delMod(MOD_FOOD_ATTP, 14); target:delMod(MOD_FOOD_ATT_CAP, 60); target:delMod(MOD_FOOD_RATTP, 14); target:delMod(MOD_FOOD_RATT_CAP, 60); target:delMod(MOD_ENMITY, -5); end;
gpl-3.0
MrClash/M0nster
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
jono659/enko
scripts/globals/items/coeurl_sub.lua
35
1832
----------------------------------------- -- ID: 5166 -- Item: coeurl_sub -- Food Effect: 30Min, All Races ----------------------------------------- -- Magic 10 -- Strength 5 -- Agility 1 -- Intelligence -2 -- Health Regen While Healing 1 -- Attack % 20 -- Attack Cap 75 -- Ranged ATT % 20 -- Ranged ATT Cap 75 ----------------------------------------- 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,5166); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 10); target:addMod(MOD_STR, 5); target:addMod(MOD_AGI, 1); target:addMod(MOD_INT, -2); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 75); target:addMod(MOD_FOOD_RATTP, 20); target:addMod(MOD_FOOD_RATT_CAP, 75); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 10); target:delMod(MOD_STR, 5); target:delMod(MOD_AGI, 1); target:delMod(MOD_INT, -2); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 75); target:delMod(MOD_FOOD_RATTP, 20); target:delMod(MOD_FOOD_RATT_CAP, 75); end;
gpl-3.0
jono659/enko
scripts/zones/Northern_San_dOria/npcs/Taulenne.lua
34
4855
----------------------------------- -- Area: Northern San d'Oria -- NPC: Taulenne -- Armor Storage NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; package.loaded["scripts/globals/armorstorage"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/armorstorage"); require("scripts/zones/Northern_San_dOria/TextIDs"); Deposit = 0x0304; Withdrawl = 0x0305; ArraySize = table.getn(StorageArray); G1 = 0; G2 = 0; G3 = 0; G4 = 0; G5 = 0; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) 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; for SetId = 1,ArraySize,11 do TradeCount = trade:getItemCount(); T1 = trade:hasItemQty(StorageArray[SetId + 5],1); if (T1 == true) then if (player:hasKeyItem(StorageArray[SetId + 10]) == false) then if (TradeCount == StorageArray[SetId + 3]) then T2 = trade:hasItemQty(StorageArray[SetId + 4],1); T3 = trade:hasItemQty(StorageArray[SetId + 6],1); T4 = trade:hasItemQty(StorageArray[SetId + 7],1); T5 = trade:hasItemQty(StorageArray[SetId + 8],1); if (StorageArray[SetId + 4] == 0) then T2 = true; end; if (StorageArray[SetId + 6] == 0) then T3 = true; end; if (StorageArray[SetId + 7] == 0) then T4 = true; end; if (StorageArray[SetId + 8] == 0) then T5 = true; end; if (T2 == true and T3 == true and T4 == true and T5 == true) then player:startEvent(Deposit,0,0,0,0,0,StorageArray[SetId + 9]); player:addKeyItem(StorageArray[SetId + 10]); player:messageSpecial(KEYITEM_OBTAINED,StorageArray[SetId + 10]); break; end; end; end; end; end; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) CurrGil = player:getGil(); for KeyItem = 11,ArraySize,11 do if player:hasKeyItem(StorageArray[KeyItem]) then if StorageArray[KeyItem - 9] == 1 then G1 = G1 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 2 then G2 = G2 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 3 then G3 = G3 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 4 then G4 = G4 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 6 then G5 = G5 + StorageArray[KeyItem - 8]; end; end; end; player:startEvent(Withdrawl,G1,G2,G3,G4,CurrGil,G5); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) if (csid == Withdrawl) then player:updateEvent(StorageArray[option * 11 - 6], StorageArray[option * 11 - 5], StorageArray[option * 11 - 4], StorageArray[option * 11 - 3], StorageArray[option * 11 - 2], StorageArray[option * 11 - 1]); end; end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == Withdrawl) then if (option > 0 and option <= StorageArray[ArraySize] - 10) then if (player:getFreeSlotsCount() >= StorageArray[option * 11 - 7]) then for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:addItem(StorageArray[option * 11 - Item],1); player:messageSpecial(ITEM_OBTAINED,StorageArray[option * 11 - Item]); end; end; player:delKeyItem(StorageArray[option * 11]); player:setGil(player:getGil() - StorageArray[option * 11 - 1]); else for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,StorageArray[option * 11 - Item]); end; end; end; end; end; if (csid == Deposit) then player:tradeComplete(); end; end;
gpl-3.0
N0U/Zero-K
LuaRules/Gadgets/CustomUnitShaders/UnitMaterials/0_customskins.lua
12
1960
-- $Id$ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local materials = { altSkinS3o = { shaderDefinitions = { }, shader = include(GADGET_DIR .. "UnitMaterials/Shaders/default.lua"), force = true, usecamera = false, culling = GL.BACK, texunits = { [0] = '%ALTSKIN', [1] = '%ALTSKIN2', [2] = '$shadow', [3] = '$specular', [4] = '$reflection', [5] = '%NORMALTEX', }, }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local unitMaterials = {} for i=1,#UnitDefs do local udef = UnitDefs[i] if (udef.customParams.altskin and VFS.FileExists(udef.customParams.altskin)) then local tex2 = "%%"..i..":1" unitMaterials[udef.name] = {"altSkinS3o", ALTSKIN = udef.customParams.altskin, ALTSKIN2 = udef.customParams.altskin2 or tex2} end --if end --for -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local skinDefs = include("LuaRules/Configs/dynamic_comm_skins.lua") for name, data in pairs(skinDefs) do local altskin2 = data.altskin2 if not altskin2 then altskin2 = "%%" .. UnitDefNames["dyn" .. data.chassis .. "0"].id .. ":1" end unitMaterials[name] = {"altSkinS3o", ALTSKIN = data.altskin, ALTSKIN2 = altskin2} end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- return materials, unitMaterials -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
Arcscion/Shadowlyre
scripts/zones/Metalworks/npcs/Naji.lua
3
5236
----------------------------------- -- Area: Metalworks -- NPC: Naji -- Involved in Quests: The doorman (finish), Riding on the Clouds -- Involved in Mission: Bastok 6-2 -- !pos 64 -14 -4 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 6) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_2",0); player:tradeComplete(); player:addKeyItem(SMILING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(YASINS_SWORD)) then -- The Doorman, WAR AF1 player:startEvent(0x02ee); elseif (player:getCurrentMission(BASTOK) ~= 255) then local currentMission = player:getCurrentMission(BASTOK); if (currentMission == THE_ZERUHN_REPORT and player:hasKeyItem(ZERUHN_REPORT)) then if (player:seenKeyItem(ZERUHN_REPORT)) then player:startEvent(0x02C6,0); else player:startEvent(0x02C6,1); end elseif (currentMission == THE_CRYSTAL_LINE and player:hasKeyItem(C_L_REPORTS)) then player:startEvent(0x02c7); elseif (currentMission == THE_EMISSARY and player:hasKeyItem(KINDRED_REPORT)) then player:startEvent(0x02ca); elseif (currentMission == THE_EMISSARY) then if (player:hasKeyItem(LETTER_TO_THE_CONSULS_BASTOK) == false and player:getVar("MissionStatus") == 0) then player:startEvent(0x02c9); else player:showText(npc,GOOD_LUCK); end elseif (player:hasKeyItem(MESSAGE_TO_JEUNO_BASTOK) and player:getVar("MissionStatus") == 0) then player:startEvent(0x02d0); elseif (currentMission == DARKNESS_RISING and player:getVar("MissionStatus") == 1) then player:startEvent(0x02d1); elseif (player:hasKeyItem(BURNT_SEAL)) then player:startEvent(0x02d2); elseif (currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 0) then player:startEvent(0x02f9); elseif (currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 3) then player:startEvent(0x02fa); else player:startEvent(0x02bc); end elseif (player:hasKeyItem(YASINS_SWORD)) then -- The Doorman player:startEvent(0x02ee); else player:startEvent(0x02bc); end end; -- 0x02c6 0x02c7 0x02bc 0x02c9 0x02ca 0x02cb 0x02cd 0x02d0 0x02d1 0x02ee 0x03f0 0x03f1 0x02f9 -- 0x02fa 0x030e 0x0325 0x034d 0x036d 0x03aa 0x03ab 0x03ac 0x03ad 0x03ae 0x03cb 0x03c9 0x03ca ----------------------------------- -- 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 == 0x02ee) then if (player:getFreeSlotsCount(0) >= 1) then player:addItem(16678); player:messageSpecial(ITEM_OBTAINED, 16678); -- Razor Axe player:delKeyItem(YASINS_SWORD); player:setVar("theDoormanCS",0); player:addFame(BASTOK,30); player:completeQuest(BASTOK,THE_DOORMAN); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 16678); -- Razor Axe end elseif (csid == 0x02C6) then player:delKeyItem(ZERUHN_REPORT); player:completeMission(BASTOK,THE_ZERUHN_REPORT); elseif (csid == 0x02c9) then player:addKeyItem(LETTER_TO_THE_CONSULS_BASTOK); player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_CONSULS_BASTOK); player:setVar("MissionStatus",1); elseif (csid == 0x02d0 and option == 0 or csid == 0x02d1) then player:delKeyItem(MESSAGE_TO_JEUNO_BASTOK); player:addKeyItem(NEW_FEIYIN_SEAL); player:messageSpecial(KEYITEM_OBTAINED,NEW_FEIYIN_SEAL); player:setVar("MissionStatus",10); elseif (csid == 0x02d0 and option == 1) then player:delKeyItem(MESSAGE_TO_JEUNO_BASTOK); player:setVar("MissionStatus",1); elseif (csid == 0x02f9) then player:setVar("MissionStatus",1); elseif (csid == 0x02ca or csid == 0x02d2 or csid == 0x02fa) then finishMissionTimeline(player,1,csid,option); end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/abilities/sublimation.lua
4
2112
----------------------------------- -- Ability: Sublimation -- Gradually creates a storage of MP while reducing your HP. The effect ends once an MP limit is reached, or your HP has gone too low. The stored MP is then transferred to your MP pool by using the ability a second time. -- Obtained: Scholar Level 35 -- Recast Time: 30 seconds after the ability is reactivated -- Duration (Charging): Until MP stored is 25% of Max HP or until HP = 50% -- Duration (Charged): 2 hours ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------- function onAbilityCheck(player,target,ability) return 0,0; end; function onUseAbility(player,target,ability) local sublimationComplete = player:getStatusEffect(EFFECT_SUBLIMATION_COMPLETE); local sublimationCharging = player:getStatusEffect(EFFECT_SUBLIMATION_ACTIVATED); local mp = 0; if sublimationComplete ~= nil then mp = sublimationComplete:getPower(); local maxmp = player:getMaxMP(); local currmp = player:getMP(); if ( mp + currmp > maxmp ) then mp = maxmp - currmp; end player:addMP(mp); player:delStatusEffectSilent(EFFECT_SUBLIMATION_COMPLETE); ability:setMsg(msgBasic.JA_RECOVERS_MP); elseif sublimationCharging ~= nil then mp = sublimationCharging:getPower(); local maxmp = player:getMaxMP(); local currmp = player:getMP(); if ( mp + currmp > maxmp ) then mp = maxmp - currmp; end player:addMP(mp); player:delStatusEffectSilent(EFFECT_SUBLIMATION_ACTIVATED); ability:setMsg(msgBasic.JA_RECOVERS_MP); else local refresh = player:getStatusEffect(EFFECT_REFRESH); if refresh == nil or refresh:getSubPower() < 3 then player:delStatusEffect(EFFECT_REFRESH); player:addStatusEffect(EFFECT_SUBLIMATION_ACTIVATED,0,3,7200); else ability:setMsg(msgBasic.JA_NO_EFFECT_2); end end return mp; end;
gpl-3.0
MRunFoss/skynet
lualib/skynet/coroutine.lua
24
3131
-- You should use this module (skynet.coroutine) instead of origin lua coroutine in skynet framework local coroutine = coroutine -- origin lua coroutine module local coroutine_resume = coroutine.resume local coroutine_yield = coroutine.yield local coroutine_status = coroutine.status local coroutine_running = coroutine.running local select = select local skynetco = {} skynetco.isyieldable = coroutine.isyieldable skynetco.running = coroutine.running skynetco.status = coroutine.status local skynet_coroutines = setmetatable({}, { __mode = "kv" }) function skynetco.create(f) local co = coroutine.create(f) -- mark co as a skynet coroutine skynet_coroutines[co] = true return co end do -- begin skynetco.resume local profile = require "profile" -- skynet use profile.resume_co/yield_co instead of coroutine.resume/yield local skynet_resume = profile.resume_co local skynet_yield = profile.yield_co local function unlock(co, ...) skynet_coroutines[co] = true return ... end local function skynet_yielding(co, from, ...) skynet_coroutines[co] = false return unlock(co, skynet_resume(co, from, skynet_yield(from, ...))) end local function resume(co, from, ok, ...) if not ok then return ok, ... elseif coroutine_status(co) == "dead" then -- the main function exit skynet_coroutines[co] = nil return true, ... elseif (...) == "USER" then return true, select(2, ...) else -- blocked in skynet framework, so raise the yielding message return resume(co, from, skynet_yielding(co, from, ...)) end end -- record the root of coroutine caller (It should be a skynet thread) local coroutine_caller = setmetatable({} , { __mode = "kv" }) function skynetco.resume(co, ...) local co_status = skynet_coroutines[co] if not co_status then if co_status == false then -- is running return false, "cannot resume a skynet coroutine suspend by skynet framework" end if coroutine_status(co) == "dead" then -- always return false, "cannot resume dead coroutine" return coroutine_resume(co, ...) else return false, "cannot resume none skynet coroutine" end end local from = coroutine_running() local caller = coroutine_caller[from] or from coroutine_caller[co] = caller return resume(co, caller, coroutine_resume(co, ...)) end function skynetco.thread(co) co = co or coroutine_running() if skynet_coroutines[co] ~= nil then return coroutine_caller[co] , false else return co, true end end end -- end of skynetco.resume function skynetco.status(co) local status = coroutine.status(co) if status == "suspended" then if skynet_coroutines[co] == false then return "blocked" else return "suspended" end else return status end end function skynetco.yield(...) return coroutine_yield("USER", ...) end do -- begin skynetco.wrap local function wrap_co(ok, ...) if ok then return ... else error(...) end end function skynetco.wrap(f) local co = skynetco.create(function(...) return f(...) end) return function(...) return wrap_co(skynetco.resume(co, ...)) end end end -- end of skynetco.wrap return skynetco
mit
Arcscion/Shadowlyre
scripts/globals/weaponskills/black_halo.lua
25
1568
----------------------------------- -- Black Halo -- Club weapon skill -- Skill level: 230 -- In order to obtain Black Halo, the quest Orastery Woes must be completed. -- Delivers a two-hit attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Shadow Gorget, Thunder Gorget & Breeze Gorget. -- Aligned with the Shadow Belt, Thunder Belt & Breeze Belt. -- Element: None -- Modifiers: STR:30% ; MND:50% -- 100%TP 200%TP 300%TP -- 1.50 2.50 3.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 2; params.ftp100 = 1.5; params.ftp200 = 2.5; params.ftp300 = 3; 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.5; 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.ftp100 = 3.0; params.ftp200 = 7.25; params.ftp300 = 9.75; params.mnd_wsc = 0.7; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
jono659/enko
scripts/zones/Aht_Urhgan_Whitegate/npcs/Teteroon.lua
34
1033
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Teteroon -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x029F); 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
jono659/enko
scripts/zones/Abyssea-Grauberg/npcs/Cavernous_Maw.lua
29
1242
----------------------------------- -- Area: Abyssea - Grauberg -- NPC: Cavernous Maw -- @pos -564.000, 30.300, -760.000 254 -- Teleports Players to North Gustaberg ----------------------------------- package.loaded["scripts/zones/Abyssea-Grauberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Abyssea-Grauberg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00C8); 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 == 0x00C8 and option == 1) then player:setPos(-71,0.001,601,126,106); end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/items/lionhead.lua
12
1323
----------------------------------------- -- ID: 4312 -- Item: lionhead -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end 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,300,4312); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
MostTheBest/Nod-32
plugins/owners.lua
94
12617
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock 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 set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run } --Copyright and edit; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
Arcscion/Shadowlyre
scripts/zones/Selbina/npcs/Graegham.lua
3
1160
----------------------------------- -- Area: Selbina -- NPC: Graegham -- Guild Merchant NPC: Fishing Guild -- !pos -12.423 -7.287 8.665 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(5182,3,18,5)) then player:showText(npc,FISHING_SHOP_DIALOG); 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
NiLuJe/koreader-base
ffi/utf8proc_h.lua
3
8282
local ffi = require("ffi") ffi.cdef[[ typedef int8_t utf8proc_int8_t; typedef uint8_t utf8proc_uint8_t; typedef int16_t utf8proc_int16_t; typedef uint16_t utf8proc_uint16_t; typedef int32_t utf8proc_int32_t; typedef uint32_t utf8proc_uint32_t; typedef ssize_t utf8proc_ssize_t; typedef size_t utf8proc_size_t; typedef bool utf8proc_bool; typedef enum { UTF8PROC_NULLTERM = 1, UTF8PROC_STABLE = 2, UTF8PROC_COMPAT = 4, UTF8PROC_COMPOSE = 8, UTF8PROC_DECOMPOSE = 16, UTF8PROC_IGNORE = 32, UTF8PROC_REJECTNA = 64, UTF8PROC_NLF2LS = 128, UTF8PROC_NLF2PS = 256, UTF8PROC_NLF2LF = 384, UTF8PROC_STRIPCC = 512, UTF8PROC_CASEFOLD = 1024, UTF8PROC_CHARBOUND = 2048, UTF8PROC_LUMP = 4096, UTF8PROC_STRIPMARK = 8192, UTF8PROC_STRIPNA = 16384, } utf8proc_option_t; static const int UTF8PROC_ERROR_NOMEM = -1; static const int UTF8PROC_ERROR_OVERFLOW = -2; static const int UTF8PROC_ERROR_INVALIDUTF8 = -3; static const int UTF8PROC_ERROR_NOTASSIGNED = -4; static const int UTF8PROC_ERROR_INVALIDOPTS = -5; typedef short int utf8proc_propval_t; struct utf8proc_property_struct { utf8proc_propval_t category; utf8proc_propval_t combining_class; utf8proc_propval_t bidi_class; utf8proc_propval_t decomp_type; utf8proc_uint16_t decomp_seqindex; utf8proc_uint16_t casefold_seqindex; utf8proc_uint16_t uppercase_seqindex; utf8proc_uint16_t lowercase_seqindex; utf8proc_uint16_t titlecase_seqindex; utf8proc_uint16_t comb_index; unsigned int bidi_mirrored : 1; unsigned int comp_exclusion : 1; unsigned int ignorable : 1; unsigned int control_boundary : 1; unsigned int charwidth : 2; unsigned int pad : 2; unsigned char boundclass; }; typedef struct utf8proc_property_struct utf8proc_property_t; typedef enum { UTF8PROC_CATEGORY_CN = 0, UTF8PROC_CATEGORY_LU = 1, UTF8PROC_CATEGORY_LL = 2, UTF8PROC_CATEGORY_LT = 3, UTF8PROC_CATEGORY_LM = 4, UTF8PROC_CATEGORY_LO = 5, UTF8PROC_CATEGORY_MN = 6, UTF8PROC_CATEGORY_MC = 7, UTF8PROC_CATEGORY_ME = 8, UTF8PROC_CATEGORY_ND = 9, UTF8PROC_CATEGORY_NL = 10, UTF8PROC_CATEGORY_NO = 11, UTF8PROC_CATEGORY_PC = 12, UTF8PROC_CATEGORY_PD = 13, UTF8PROC_CATEGORY_PS = 14, UTF8PROC_CATEGORY_PE = 15, UTF8PROC_CATEGORY_PI = 16, UTF8PROC_CATEGORY_PF = 17, UTF8PROC_CATEGORY_PO = 18, UTF8PROC_CATEGORY_SM = 19, UTF8PROC_CATEGORY_SC = 20, UTF8PROC_CATEGORY_SK = 21, UTF8PROC_CATEGORY_SO = 22, UTF8PROC_CATEGORY_ZS = 23, UTF8PROC_CATEGORY_ZL = 24, UTF8PROC_CATEGORY_ZP = 25, UTF8PROC_CATEGORY_CC = 26, UTF8PROC_CATEGORY_CF = 27, UTF8PROC_CATEGORY_CS = 28, UTF8PROC_CATEGORY_CO = 29, } utf8proc_category_t; typedef enum { UTF8PROC_BIDI_CLASS_L = 1, UTF8PROC_BIDI_CLASS_LRE = 2, UTF8PROC_BIDI_CLASS_LRO = 3, UTF8PROC_BIDI_CLASS_R = 4, UTF8PROC_BIDI_CLASS_AL = 5, UTF8PROC_BIDI_CLASS_RLE = 6, UTF8PROC_BIDI_CLASS_RLO = 7, UTF8PROC_BIDI_CLASS_PDF = 8, UTF8PROC_BIDI_CLASS_EN = 9, UTF8PROC_BIDI_CLASS_ES = 10, UTF8PROC_BIDI_CLASS_ET = 11, UTF8PROC_BIDI_CLASS_AN = 12, UTF8PROC_BIDI_CLASS_CS = 13, UTF8PROC_BIDI_CLASS_NSM = 14, UTF8PROC_BIDI_CLASS_BN = 15, UTF8PROC_BIDI_CLASS_B = 16, UTF8PROC_BIDI_CLASS_S = 17, UTF8PROC_BIDI_CLASS_WS = 18, UTF8PROC_BIDI_CLASS_ON = 19, UTF8PROC_BIDI_CLASS_LRI = 20, UTF8PROC_BIDI_CLASS_RLI = 21, UTF8PROC_BIDI_CLASS_FSI = 22, UTF8PROC_BIDI_CLASS_PDI = 23, } utf8proc_bidi_class_t; typedef enum { UTF8PROC_DECOMP_TYPE_FONT = 1, UTF8PROC_DECOMP_TYPE_NOBREAK = 2, UTF8PROC_DECOMP_TYPE_INITIAL = 3, UTF8PROC_DECOMP_TYPE_MEDIAL = 4, UTF8PROC_DECOMP_TYPE_FINAL = 5, UTF8PROC_DECOMP_TYPE_ISOLATED = 6, UTF8PROC_DECOMP_TYPE_CIRCLE = 7, UTF8PROC_DECOMP_TYPE_SUPER = 8, UTF8PROC_DECOMP_TYPE_SUB = 9, UTF8PROC_DECOMP_TYPE_VERTICAL = 10, UTF8PROC_DECOMP_TYPE_WIDE = 11, UTF8PROC_DECOMP_TYPE_NARROW = 12, UTF8PROC_DECOMP_TYPE_SMALL = 13, UTF8PROC_DECOMP_TYPE_SQUARE = 14, UTF8PROC_DECOMP_TYPE_FRACTION = 15, UTF8PROC_DECOMP_TYPE_COMPAT = 16, } utf8proc_decomp_type_t; typedef enum { UTF8PROC_BOUNDCLASS_START = 0, UTF8PROC_BOUNDCLASS_OTHER = 1, UTF8PROC_BOUNDCLASS_CR = 2, UTF8PROC_BOUNDCLASS_LF = 3, UTF8PROC_BOUNDCLASS_CONTROL = 4, UTF8PROC_BOUNDCLASS_EXTEND = 5, UTF8PROC_BOUNDCLASS_L = 6, UTF8PROC_BOUNDCLASS_V = 7, UTF8PROC_BOUNDCLASS_T = 8, UTF8PROC_BOUNDCLASS_LV = 9, UTF8PROC_BOUNDCLASS_LVT = 10, UTF8PROC_BOUNDCLASS_REGIONAL_INDICATOR = 11, UTF8PROC_BOUNDCLASS_SPACINGMARK = 12, UTF8PROC_BOUNDCLASS_PREPEND = 13, UTF8PROC_BOUNDCLASS_ZWJ = 14, UTF8PROC_BOUNDCLASS_E_BASE = 15, UTF8PROC_BOUNDCLASS_E_MODIFIER = 16, UTF8PROC_BOUNDCLASS_GLUE_AFTER_ZWJ = 17, UTF8PROC_BOUNDCLASS_E_BASE_GAZ = 18, UTF8PROC_BOUNDCLASS_EXTENDED_PICTOGRAPHIC = 19, UTF8PROC_BOUNDCLASS_E_ZWG = 20, } utf8proc_boundclass_t; typedef utf8proc_int32_t (*utf8proc_custom_func)(utf8proc_int32_t, void *); extern const utf8proc_int8_t utf8proc_utf8class[256] __attribute__((visibility("default"))); const char *utf8proc_version(void) __attribute__((visibility("default"))); const char *utf8proc_unicode_version(void) __attribute__((visibility("default"))); const char *utf8proc_errmsg(utf8proc_ssize_t) __attribute__((visibility("default"))); utf8proc_ssize_t utf8proc_iterate(const utf8proc_uint8_t *, utf8proc_ssize_t, utf8proc_int32_t *) __attribute__((visibility("default"))); utf8proc_bool utf8proc_codepoint_valid(utf8proc_int32_t) __attribute__((visibility("default"))); utf8proc_ssize_t utf8proc_encode_char(utf8proc_int32_t, utf8proc_uint8_t *) __attribute__((visibility("default"))); const utf8proc_property_t *utf8proc_get_property(utf8proc_int32_t) __attribute__((visibility("default"))); utf8proc_ssize_t utf8proc_decompose_char(utf8proc_int32_t, utf8proc_int32_t *, utf8proc_ssize_t, utf8proc_option_t, int *) __attribute__((visibility("default"))); utf8proc_ssize_t utf8proc_decompose(const utf8proc_uint8_t *, utf8proc_ssize_t, utf8proc_int32_t *, utf8proc_ssize_t, utf8proc_option_t) __attribute__((visibility("default"))); utf8proc_ssize_t utf8proc_decompose_custom(const utf8proc_uint8_t *, utf8proc_ssize_t, utf8proc_int32_t *, utf8proc_ssize_t, utf8proc_option_t, utf8proc_custom_func, void *) __attribute__((visibility("default"))); utf8proc_ssize_t utf8proc_normalize_utf32(utf8proc_int32_t *, utf8proc_ssize_t, utf8proc_option_t) __attribute__((visibility("default"))); utf8proc_ssize_t utf8proc_reencode(utf8proc_int32_t *, utf8proc_ssize_t, utf8proc_option_t) __attribute__((visibility("default"))); utf8proc_bool utf8proc_grapheme_break_stateful(utf8proc_int32_t, utf8proc_int32_t, utf8proc_int32_t *) __attribute__((visibility("default"))); utf8proc_bool utf8proc_grapheme_break(utf8proc_int32_t, utf8proc_int32_t) __attribute__((visibility("default"))); utf8proc_int32_t utf8proc_tolower(utf8proc_int32_t) __attribute__((visibility("default"))); utf8proc_int32_t utf8proc_toupper(utf8proc_int32_t) __attribute__((visibility("default"))); utf8proc_int32_t utf8proc_totitle(utf8proc_int32_t) __attribute__((visibility("default"))); int utf8proc_islower(utf8proc_int32_t) __attribute__((visibility("default"))); int utf8proc_isupper(utf8proc_int32_t) __attribute__((visibility("default"))); int utf8proc_charwidth(utf8proc_int32_t) __attribute__((visibility("default"))); utf8proc_category_t utf8proc_category(utf8proc_int32_t) __attribute__((visibility("default"))); const char *utf8proc_category_string(utf8proc_int32_t) __attribute__((visibility("default"))); utf8proc_ssize_t utf8proc_map(const utf8proc_uint8_t *, utf8proc_ssize_t, utf8proc_uint8_t **, utf8proc_option_t) __attribute__((visibility("default"))); utf8proc_ssize_t utf8proc_map_custom(const utf8proc_uint8_t *, utf8proc_ssize_t, utf8proc_uint8_t **, utf8proc_option_t, utf8proc_custom_func, void *) __attribute__((visibility("default"))); utf8proc_uint8_t *utf8proc_NFD(const utf8proc_uint8_t *) __attribute__((visibility("default"))); utf8proc_uint8_t *utf8proc_NFC(const utf8proc_uint8_t *) __attribute__((visibility("default"))); utf8proc_uint8_t *utf8proc_NFKD(const utf8proc_uint8_t *) __attribute__((visibility("default"))); utf8proc_uint8_t *utf8proc_NFKC(const utf8proc_uint8_t *) __attribute__((visibility("default"))); utf8proc_uint8_t *utf8proc_NFKC_Casefold(const utf8proc_uint8_t *) __attribute__((visibility("default"))); ]]
agpl-3.0
jono659/enko
scripts/zones/Promyvion-Holla/mobs/Memory_Receptacle.lua
12
6808
----------------------------------- -- Area: Promyvion-Holla -- MOB: Memory Receptacle ----------------------------------- package.loaded["scripts/zones/Promyvion-Holla/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require( "scripts/zones/Promyvion-Holla/TextIDs" ); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 100); -- 10% Regain for now mob:SetAutoAttackEnabled(false); -- Recepticles only use TP moves. end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local Mem_Recep = mob:getID(); if(Mem_Recep == 16842781) then -- Floor 1 for i = Mem_Recep+1, Mem_Recep+3 do -- Keep pets linked if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end elseif(Mem_Recep == 16842839 or Mem_Recep == 16842846 or Mem_Recep == 16842853 or Mem_Recep == 16842860) then -- Floor 2 for i = Mem_Recep+1, Mem_Recep+5 do if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end elseif(Mem_Recep == 16842886 or Mem_Recep == 16842895 or Mem_Recep == 16842904 or Mem_Recep == 16842938 or Mem_Recep == 16842947 or -- Floor 3 Mem_Recep == 16842956) then for i = Mem_Recep+1, Mem_Recep+7 do if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end end -- Summons a single stray every 30 seconds. if (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16842781) and mob:AnimationSub() == 2) then -- Floor 1 for i = Mem_Recep+1, Mem_Recep+3 do if (GetMobAction(i) == 0) then -- My Stray is deeaaaaaad! mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle return; end end elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16842839 or Mem_Recep == 16842846 or Mem_Recep == 16842853 or -- Floor 2 Mem_Recep == 16842860) and mob:AnimationSub() == 2) then for i = Mem_Recep+1, Mem_Recep+5 do if (GetMobAction(i) == 0) then mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle return; end end elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16842886 or Mem_Recep == 16842895 or Mem_Recep == 16842904 or -- Floor 3 Mem_Recep == 16842938 or Mem_Recep == 16842947 or Mem_Recep == 16842956) and mob:AnimationSub() == 2) then for i = Mem_Recep+1, Mem_Recep+7 do if (GetMobAction(i) == 0) then mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); return; end end else mob:AnimationSub(2); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local rand = 0; local mobID = mob:getID(); local difX = killer:getXPos()-mob:getXPos(); local difY = killer:getYPos()-mob:getYPos(); local difZ = killer:getZPos()-mob:getZPos(); local killeranimation = killer:getAnimation(); local Distance = math.sqrt( math.pow(difX,2) + math.pow(difY,2) + math.pow(difZ,2) ); --calcul de la distance entre les "killer" et le memory receptacle -- print(mob:getID); mob:AnimationSub(0); -- Set ani. sub to default or the recepticles wont work properly if(VanadielMinute() % 2 == 1) then killer:setVar("MemoryReceptacle",2); rnd = 2; else killer:setVar("MemoryReceptacle",1); rnd = 1; end switch (mob:getID()) : caseof { [16842781] = function (x) GetNPCByID(16843057):openDoor(180); if(Distance <4 and killeranimation == 0)then killer:startEvent(0x0025); end end, [16842839] = function (x) GetNPCByID(16843053):openDoor(180); if(Distance <4 and killeranimation == 0)then if(rnd == 2) then killer:startEvent(0x0021); else killer:startEvent(0x0022); end end end, [16842846] = function (x) GetNPCByID(16843054):openDoor(180); if(Distance <4 and killeranimation == 0)then if(rnd == 2) then killer:startEvent(0x0021); else killer:startEvent(0x0022); end end end, [16842860] = function (x) GetNPCByID(16843056):openDoor(180); if(Distance <4 and killeranimation == 0)then if(rnd == 2) then killer:startEvent(0x0021); else killer:startEvent(0x0022); end end end, [16842853] = function (x) GetNPCByID(16843055):openDoor(180); if(Distance <4 and killeranimation == 0)then if(rnd == 2) then killer:startEvent(0x0021); else killer:startEvent(0x0022); end end end, [16842886] = function (x) GetNPCByID(16843050):openDoor(180); if(Distance <4 and killeranimation == 0)then killer:startEvent(0x001E); end end, [16842895] = function (x) GetNPCByID(16843051):openDoor(180); if(Distance <4 and killeranimation == 0)then killer:startEvent(0x001E); end end, [16842904] = function (x) GetNPCByID(16843052):openDoor(180); if(Distance <4 and killeranimation == 0)then killer:startEvent(0x001E) end end, [16842938] = function (x) GetNPCByID(16843058):openDoor(180); if(Distance <4 and killeranimation == 0)then killer:startEvent(0x001E); end end, [16842947] = function (x) GetNPCByID(16843059):openDoor(180); if(Distance <4 and killeranimation == 0)then killer:startEvent(0x001E); end end, [16842956] = function (x) GetNPCByID(16843060):openDoor(180); if(Distance <4 and killeranimation == 0)then killer:startEvent(0x001E); end 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 (option==1)then player:setVar("MemoryReceptacle",0); end end;
gpl-3.0
ANONYMOUSE4/DevABBAS_ALSAIDI
plugins/setwelcome.lua
1
2556
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY ABBAS ALSAIDI ▀▄ ▄▀ ▀▄ ▄▀ WRITER ABBAS ▀▄ ▄▀ ▀▄ ▄▀ Dev@Abbas9_9 ▀▄ ▄▀ ▀▄ ▄▀ وضع ترحيب =Set Wellcome ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function run(msg, matches, callback, extra) local data = load_data(_config.moderation.data) local group_welcome = data[tostring(msg.to.id)]['group_welcome'] -------------------------- Data Will be save on Moderetion.json if matches[1] == 'حذف الترحيب' and not matches[2] and is_owner(msg) then data[tostring(msg.to.id)]['group_welcome'] = nil --delete welcome save_data(_config.moderation.data, data) return 'تم حذف الترحيب' end if not is_owner(msg) then return 'للمشرفين فقط🌝🍷' end --------------------Loading Group Rules local rules = data[tostring(msg.to.id)]['rules'] if matches[1] == 'rules' and matches[2] and is_owner(msg) then if data[tostring(msg.to.id)]['rules'] == nil then --when no rules found.... return 'No Rules Found!\n\nSet Rule first by /set rules [rules]\nOr\nset normal welcome by /setwlc [wlc msg]' end data[tostring(msg.to.id)]['group_welcome'] = matches[2]..'\n\nGroup Rules :\n'..rules save_data(_config.moderation.data, data) return 'تم☑️ وضع الترحيب💕 على :\n'..matches[2] end if not is_owner(msg) then return 'للمشرفين فقط🌝🍷' end if matches[1] and is_owner(msg) then data[tostring(msg.to.id)]['group_welcome'] = matches[1] save_data(_config.moderation.data, data) return 'تم☑️ وضع الترحيب💕 على : \n'..matches[1] end if not is_owner(msg) then return 'للمشرفين فقط🌝🍷' end end return { patterns = { "^[!/]setwlc (rules) +(.*)$", "^وضع ترحيب +(.*)$", "^(حذف الترحيب)$" }, run = run } -----لا تمسح الحقوق ياعار غيرك تعبان على الملفات ------- --------------------عباس السعيدي----------------------- --------------------Dev@Abbas9_9-----------------------
gpl-2.0
Arcscion/Shadowlyre
scripts/zones/Arrapago_Reef/npcs/qm6.lua
30
1138
----------------------------------- -- Area: Arrapago Reef -- NPC: ??? (corsair job flag quest) -- ----------------------------------- package.loaded["scripts/zones/Arrapago_Reef/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Arrapago_Reef/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) LuckOfTheDraw = player:getVar("LuckOfTheDraw"); if (LuckOfTheDraw ==2) then player:startEvent(0x00D3); player:setVar("LuckOfTheDraw",3); 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
Arcscion/Shadowlyre
scripts/zones/Abyssea-Konschtat/npcs/qm5.lua
3
1347
----------------------------------- -- Zone: Abyssea-Konschtat -- NPC: qm5 (???) -- Spawns Keratyrannos -- !pos ? ? ? 15 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(2910,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(16838871) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(16838871):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 2910); -- Inform payer what items they need. 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
joewalker/prosody-modules
mod_storage_multi/mod_storage_multi.lua
32
2258
-- mod_storage_multi local storagemanager = require"core.storagemanager"; local backends = module:get_option_array(module.name); -- TODO better name? -- TODO migrate data "upwards" -- one → one successful write is success -- all → all backends must report success -- majority → majority of backends must report success local policy = module:get_option_string(module.name.."_policy", "all"); local keyval_store = {}; keyval_store.__index = keyval_store; function keyval_store:get(username) local backends = self.backends; local data, err; for i = 1, #backends do module:log("debug", "%s:%s:get(%q)", tostring(backends[i].get), backends[i]._store, username); data, err = backends[i]:get(username); if err then module:log("error", tostring(err)); elseif not data then module:log("debug", "No data returned"); else module:log("debug", "Data returned"); return data, err; end end end -- This is where it gets complicated function keyval_store:set(username, data) local backends = self.backends; local ok, err, backend; local all, one, oks = true, false, 0; for i = 1, #backends do backend = backends[i]; module:log("debug", "%s:%s:set(%q)", tostring(backends[i].get), backends[i].store, username); ok, err = backend:set(username, data); if not ok then module:log("error", "Error in storage driver %s: %s", backend.name, tostring(err)); else oks = oks + 1; end one = one or ok; -- At least one successful write all = all and ok; -- All successful end if policy == "all" then return all, err elseif policy == "majority" then return oks > (#backends/2), err; end -- elseif policy == "one" then return one, err; end local stores = { keyval = keyval_store; } local driver = {}; function driver:open(store, typ) local store_mt = stores[typ or "keyval"]; if store_mt then local my_backends = {}; local driver, opened for i = 1, #backends do driver = storagemanager.load_driver(module.host, backends[i]); opened = driver:open(store, typ); my_backends[i] = assert(driver:open(store, typ)); my_backends[i]._store = store; end return setmetatable({ backends = my_backends }, store_mt); end return nil, "unsupported-store"; end module:provides("storage", driver);
mit
Arcscion/Shadowlyre
scripts/zones/RaKaznar_Inner_Court/npcs/HomePoint#1.lua
3
1281
----------------------------------- -- Area: RaKaznar_Inner_Court -- NPC: HomePoint#1 -- !pos 757 120 17.5 276 ----------------------------------- package.loaded["scripts/zones/RaKaznar_Inner_Court/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/RaKaznar_Inner_Court/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 116); 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
jono659/enko
scripts/zones/Mine_Shaft_2716/Zone.lua
32
1656
----------------------------------- -- -- Zone: Mine_Shaft_2716 (13) -- ----------------------------------- package.loaded["scripts/zones/Mine_Shaft_2716/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Mine_Shaft_2716/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) 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; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-116.599,-122.103,-620.01,253); 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
N0U/Zero-K
LuaRules/Gadgets/cmd_factory_stop_production.lua
4
2841
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Factory Stop Production", desc = "Adds a command to clear the factory queue", author = "GoogleFrog", date = "13 November 2016", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (not gadgetHandler:IsSyncedCode()) then return false -- no unsynced code end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local spInsertUnitCmdDesc = Spring.InsertUnitCmdDesc local cmdOpts = CMD.OPT_CTRL include("LuaRules/Configs/customcmds.h.lua") local isFactory = {} for udid = 1, #UnitDefs do local ud = UnitDefs[udid] if ud.isFactory and not ud.customParams.notreallyafactory then isFactory[udid] = true end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local stopProductionCmdDesc = { id = CMD_STOP_PRODUCTION, type = CMDTYPE.ICON, name = 'Stop Production', action = 'stopproduction', cursor = 'Stop', -- Probably does nothing tooltip = 'Clear the unit production queue.', } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Handle the command function gadget:AllowCommand_GetWantedCommand() return {[CMD_STOP_PRODUCTION] = true} end function gadget:AllowCommand_GetWantedUnitDefID() return isFactory end function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions) if (cmdID ~= CMD_STOP_PRODUCTION) or (not isFactory[unitDefID]) then return end local commands = Spring.GetFactoryCommands(unitID) if not commands then return end for i = 1, #commands do Spring.GiveOrderToUnit(unitID, CMD.REMOVE, {commands[i].tag}, cmdOpts) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Add the command to factories function gadget:UnitCreated(unitID, unitDefID) if isFactory[unitDefID] then spInsertUnitCmdDesc(unitID, stopProductionCmdDesc) end end function gadget:Initialize() gadgetHandler:RegisterCMDID(CMD_STOP_PRODUCTION) for _, unitID in pairs(Spring.GetAllUnits()) do gadget:UnitCreated(unitID, Spring.GetUnitDefID(unitID)) end end
gpl-2.0
jono659/enko
scripts/zones/Kazham/npcs/Thali_Mhobrum.lua
19
1540
----------------------------------- -- Area: Kazham -- NPC: Thali Mhobrum -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); local path = { 55.816410, -11.000000, -43.992680, 54.761787, -11.000000, -44.046181, 51.805824, -11.000000, -44.200321, 52.922001, -11.000000, -44.186420, 51.890709, -11.000000, -44.224312, 47.689358, -11.000000, -44.374969, 52.826096, -11.000000, -44.191029, 47.709465, -11.000000, -44.374393, 52.782181, -11.000000, -44.192482, 47.469643, -11.000000, -44.383091 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00BE); npc:wait(-1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); npc:wait(0); end;
gpl-3.0
muhkuh-sys/org.muhkuh.tools-muhkuh_gui
bin/lua/serialnr.lua
1
6731
----------------------------------------------------------------------------- -- Copyright (C) 2008 by Christoph Thelen -- -- doc_bacardi@users.sourceforge.net -- -- -- -- This program 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. -- ----------------------------------------------------------------------------- module("serialnr", package.seeall) local m_dialog = nil local m_spinBoardCount = nil local m_spinSerial = nil local m_spinYear = nil local m_spinWeek = nil local m_iBoardCount = -1 local m_iSerial = -1 local m_iYear = -1 local m_iWeek = -1 -- generate window ids local m_ID = wx.wxID_HIGHEST function nextID() m_ID = m_ID+1 return m_ID end local ID_SERIALNODIALOG_SPINBOARDCOUNT = nextID() local ID_SERIALNODIALOG_SPINSERIAL = nextID() local ID_SERIALNODIALOG_SPINYEAR = nextID() local ID_SERIALNODIALOG_SPINWEEK = nextID() local function createControls() local mainSizer local staticBoxBoardCount local staticBoxSecMemInfos local serialSizer local labelSerial local productionDateSizer local labelProductionDate local buttonSizer local buttonOk local buttonCancel local minSize local maxSize -- init the controls -- create the main sizer mainSizer = wx.wxBoxSizer(wx.wxVERTICAL) m_dialog:SetSizer(mainSizer) -- create the board count controls staticBoxBoardCount = wx.wxStaticBoxSizer(wx.wxVERTICAL, m_dialog, "Number of boards: ") mainSizer:Add(staticBoxBoardCount, 0, wx.wxEXPAND) m_spinBoardCount = wx.wxSpinCtrl(m_dialog, ID_SERIALNODIALOG_SPINBOARDCOUNT) staticBoxBoardCount:Add(m_spinBoardCount, 0, wx.wxEXPAND) mainSizer:AddSpacer(6) -- create security memory info wxStaticBoxSizer staticBoxSecMemInfos = wx.wxStaticBoxSizer(wx.wxVERTICAL, m_dialog, "Security memory settings: ") mainSizer:Add(staticBoxSecMemInfos, 0, wx.wxEXPAND) -- create serial number controls serialSizer = wx.wxBoxSizer(wx.wxHORIZONTAL) labelSerial = wx.wxStaticText(m_dialog, wx.wxID_ANY, "Serial Number(dec) of 1st board:") m_spinSerial = wx.wxSpinCtrl(m_dialog, ID_SERIALNODIALOG_SPINSERIAL) serialSizer:Add(labelSerial, 0, wx.wxALIGN_CENTER_VERTICAL) serialSizer:Add(m_spinSerial, 0, wx.wxALIGN_CENTER_VERTICAL) staticBoxSecMemInfos:Add(serialSizer, 0, wx.wxEXPAND) staticBoxSecMemInfos:AddSpacer(6) -- create ProductionDate controls productionDateSizer = wx.wxBoxSizer(wx.wxHORIZONTAL) labelProductionDate = wx.wxStaticText(m_dialog, wx.wxID_ANY, "Production Date: YYWW(dec) ") m_spinYear = wx.wxSpinCtrl(m_dialog, ID_SERIALNODIALOG_SPINYEAR) m_spinWeek = wx.wxSpinCtrl(m_dialog, ID_SERIALNODIALOG_SPINWEEK) productionDateSizer:Add(labelProductionDate, 0, wx.wxALIGN_CENTER_VERTICAL) productionDateSizer:Add(m_spinYear, 0, wx.wxALIGN_CENTER_VERTICAL) productionDateSizer:Add(m_spinWeek, 0, wx.wxALIGN_CENTER_VERTICAL) staticBoxSecMemInfos:Add(productionDateSizer, 0, wx.wxEXPAND) staticBoxSecMemInfos:AddSpacer(8) mainSizer:AddSpacer(6) -- create the button sizer buttonSizer = wx.wxBoxSizer(wx.wxHORIZONTAL) mainSizer:Add(buttonSizer, 0, wx.wxEXPAND) buttonOk = wx.wxButton(m_dialog, wx.wxID_OK, "Ok") buttonCancel = wx.wxButton(m_dialog, wx.wxID_CANCEL, "Cancel") buttonSizer:AddStretchSpacer(1) buttonSizer:Add(buttonOk) buttonSizer:AddStretchSpacer(1) buttonSizer:Add(buttonCancel) buttonSizer:AddStretchSpacer(1) mainSizer:AddSpacer(4) -- set minimum size mainSizer:SetSizeHints(m_dialog) -- x and y are not expandable minSize = m_dialog:GetMinSize() maxSize = m_dialog:GetMaxSize() maxSize:SetHeight( minSize:GetHeight() ) maxSize:SetWidth( minSize:GetWidth() ) m_dialog:SetMaxSize(maxSize) end local function OnSpinBoardCount(event) m_iBoardCount = event:GetInt() end local function OnSpinSerial(event) m_iSerial = event:GetInt() end local function OnSpinYear(event) m_iYear = event:GetInt() end local function OnSpinWeek(event) m_iWeek = event:GetInt() end function run(iSerialNo, iBoardCount) local strMacAddrByte local dToday local strYear local strWeek -- create the dialog m_dialog = wx.wxDialog(wx.NULL, wx.wxID_ANY, "Select the plugin", wx.wxDefaultPosition, wx.wxDefaultSize, wx.wxDEFAULT_DIALOG_STYLE+wx.wxRESIZE_BORDER) -- get datecode dToday = wx.wxDateTime() dToday:SetToCurrent() -- get year number without century strYear = dToday:Format("%y") -- get week number strWeek = tostring(tonumber(dToday:Format("%W")) + 1) -- create the controls createControls() -- assign the values m_iBoardCount = iBoardCount m_spinBoardCount:SetRange(1, 1000) m_spinBoardCount:SetValue(m_iBoardCount) m_iSerial = iSerialNo m_spinSerial:SetRange(1, 999999) m_spinSerial:SetValue(m_iSerial) m_iYear = strYear m_spinYear:SetRange(0, 20) m_spinYear:SetValue(m_iYear) m_iWeek = strWeek m_spinWeek:SetRange(01, 53) m_spinWeek:SetValue(m_iWeek) -- connect some controls m_dialog:Connect(ID_SERIALNODIALOG_SPINBOARDCOUNT, wx.wxEVT_COMMAND_SPINCTRL_UPDATED, OnSpinBoardCount) m_dialog:Connect(ID_SERIALNODIALOG_SPINSERIAL, wx.wxEVT_COMMAND_SPINCTRL_UPDATED, OnSpinSerial) m_dialog:Connect(ID_SERIALNODIALOG_SPINYEAR, wx.wxEVT_COMMAND_SPINCTRL_UPDATED, OnSpinYear) m_dialog:Connect(ID_SERIALNODIALOG_SPINWEEK, wx.wxEVT_COMMAND_SPINCTRL_UPDATED, OnSpinWeek) -- Show the dialog if m_dialog:ShowModal(true)==wx.wxID_OK then if _G.__MUHKUH_PARAMETERS==nil then _G.__MUHKUH_PARAMETERS = {} end _G.__MUHKUH_PARAMETERS.BoardCount = m_iBoardCount _G.__MUHKUH_PARAMETERS.SerialNumber = m_iSerial _G.__MUHKUH_PARAMETERS.ProductionDate = m_iYear*256 + m_iWeek return true else return false end end
gpl-2.0
zhangxiangxiao/nn
TemporalSubSampling.lua
44
1378
local TemporalSubSampling, parent = torch.class('nn.TemporalSubSampling', 'nn.Module') function TemporalSubSampling:__init(inputFrameSize, kW, dW) parent.__init(self) dW = dW or 1 self.inputFrameSize = inputFrameSize self.kW = kW self.dW = dW self.weight = torch.Tensor(inputFrameSize) self.bias = torch.Tensor(inputFrameSize) self.gradWeight = torch.Tensor(inputFrameSize) self.gradBias = torch.Tensor(inputFrameSize) self:reset() end function TemporalSubSampling:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end function TemporalSubSampling:updateOutput(input) return input.nn.TemporalSubSampling_updateOutput(self, input) end function TemporalSubSampling:updateGradInput(input, gradOutput) if self.gradInput then return input.nn.TemporalSubSampling_updateGradInput(self, input, gradOutput) end end function TemporalSubSampling:accGradParameters(input, gradOutput, scale) return input.nn.TemporalSubSampling_accGradParameters(self, input, gradOutput, scale) end
bsd-3-clause
jono659/enko
scripts/globals/weaponskills/spinning_attack.lua
30
1357
----------------------------------- -- Spinning Attack -- Hand-to-Hand weapon skill -- Skill Level: 150 -- Delivers an area attack. Radius varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Flame Gorget & Thunder Gorget. -- Aligned with the Flame Belt & Thunder Belt. -- Element: None -- Modifiers: STR: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 = 2; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.35; 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.str_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
rtsisyk/tarantool
test/app/crypto.test.lua
3
1248
test_run = require('test_run').new() test_run:cmd("push filter ".."'\\.lua.*:[0-9]+: ' to '.lua:<line>\"]: '") crypto = require('crypto') type(crypto) ciph = crypto.cipher.aes128.cbc pass = '1234567887654321' iv = 'abcdefghijklmnop' enc = ciph.encrypt('test', pass, iv) enc ciph.decrypt(enc, pass, iv) --Failing scenaries crypto.cipher.aes128.cbc.encrypt('a') crypto.cipher.aes128.cbc.encrypt('a', '123456', '435') crypto.cipher.aes128.cbc.encrypt('a', '1234567887654321') crypto.cipher.aes128.cbc.encrypt('a', '1234567887654321', '12') crypto.cipher.aes256.cbc.decrypt('a') crypto.cipher.aes256.cbc.decrypt('a', '123456', '435') crypto.cipher.aes256.cbc.decrypt('a', '12345678876543211234567887654321') crypto.cipher.aes256.cbc.decrypt('12', '12345678876543211234567887654321', '12') crypto.cipher.aes192.cbc.encrypt.new() crypto.cipher.aes192.cbc.encrypt.new('123321') crypto.cipher.aes192.cbc.decrypt.new('123456788765432112345678') crypto.cipher.aes192.cbc.decrypt.new('123456788765432112345678', '12345') crypto.cipher.aes100.efb crypto.cipher.aes256.nomode crypto.digest.nodigest bad_pass = '8765432112345678' bad_iv = '123456abcdefghij' ciph.decrypt(enc, bad_pass, iv) ciph.decrypt(enc, pass, bad_iv) test_run:cmd("clear filter")
bsd-2-clause
jono659/enko
scripts/zones/Dragons_Aery/npcs/qm0.lua
8
1878
----------------------------------- -- Area: Dragons Aery -- NPC: ??? (Spawn Nidhogg) -- @pos -81 32 2 178 ----------------------------------- package.loaded["scripts/zones/Dragons_Aery/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Dragons_Aery/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local Fafnir = GetMobAction(17408018); local Nidhogg = GetMobAction(17408019); -- Trade Cup of Sweet Tea if((Nidhogg == ACTION_NONE or Nidhogg == ACTION_SPAWN) and trade:hasItemQty(3340,1) and trade:getItemCount() == 1) then -- Check trade, and if mob is ACTION_NONE (0) or waiting to spawn (24) if (LandKingSystem_HQ == 1 or LandKingSystem_HQ == 2) then player:tradeComplete(); SpawnMob(17408019,180):updateEnmity(player); -- onMobEngaged does not run for scripted spawns. end -- Trade Cup of Honey Wine elseif((Fafnir == ACTION_NONE or Fafnir == ACTION_SPAWN) and trade:hasItemQty(3339,1) and trade:getItemCount() == 1) then if (LandKingSystem_NQ == 1 or LandKingSystem_NQ == 2) then player:tradeComplete(); SpawnMob(17408018,180):updateEnmity(player); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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
Arcscion/Shadowlyre
scripts/globals/items/gateau_aux_fraises.lua
12
1575
----------------------------------------- -- ID: 5542 -- Item: Gateau aux fraises -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP 8 -- MP 8% Cap 50 -- Intelligence 1 -- HP Recovered while healing 1 -- MP Recovered while healing 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,10800,5542); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 8); target:addMod(MOD_INT, 1); target:addMod(MOD_FOOD_MPP, 8); target:addMod(MOD_FOOD_MP_CAP, 50); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 8); target:delMod(MOD_INT, 1); target:delMod(MOD_FOOD_MPP, 8); target:delMod(MOD_FOOD_MP_CAP, 50); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
N0U/Zero-K
scripts/bomberheavy.lua
5
3145
include "constants.lua" include "bombers.lua" include "fixedwingTakeOff.lua" local flare1 = piece 'flare1' local flare2 = piece 'flare2' local base = piece 'base' local wing1 = piece 'wing1' local wing2 = piece 'wing2' local rearthrust = piece 'rearthrust' local wingthrust1 = piece 'wingthrust1' local wingthrust2 = piece 'wingthrust2' local thrust1 = piece 'thrust1' local thrust2 = piece 'thrust2' local drop = piece 'drop' local emit1 = piece 'emit1' local emit2 = piece 'emit2' local emit3 = piece 'emit3' local emit4 = piece 'emit4' local smokePiece = {base} --Signal local SIG_move = 1 local SIG_TAKEOFF = 2 local takeoffHeight = UnitDefNames["bomberheavy"].wantedHeight local gun_1 = false local function Stopping() Signal(SIG_move) SetSignalMask(SIG_move) Move(wing1, x_axis, -0, 1.65) Move(wing1, z_axis, 0, 0.35) Move(wing2, x_axis, 0, 1.65) Move(wing2, z_axis, 0, 0.35) Turn(wing1, z_axis, 0, math.rad(0.62)) Turn(wing2, z_axis, 0, math.rad(1.85)) end local function Moving() Signal(SIG_move) SetSignalMask(SIG_move) Move(wing1, x_axis, 2.4, 1.65) Move(wing1, z_axis, -0.5, 0.35) Move(wing2, x_axis, -2.4, 1.65) Move(wing2, z_axis, -0.5, 0.35) Turn(wing1, z_axis, math.rad(-2.7), math.rad(1.85)) Turn(wing2, z_axis, math.rad(-2.7), math.rad(1.85)) end function script.StartMoving() StartThread(Moving) end function script.StopMoving() StartThread(Stopping) StartThread(TakeOffThread, takeoffHeight, SIG_TAKEOFF) end function script.MoveRate(rate) if rate == 1 then --Signal(SIG_BARREL) --SetSignalMask(SIG_BARREL) Turn(base, z_axis, math.rad(-240), math.rad(120)) WaitForTurn(base, z_axis) Turn(base, z_axis, math.rad(-(120)), math.rad(180)) WaitForTurn(base, z_axis) Turn(base, z_axis, 0, math.rad(120)) end end function script.Create() SetInitialBomberSettings() StartThread(TakeOffThread, takeoffHeight, SIG_TAKEOFF) StartThread(SmokeUnit, smokePiece) Hide(rearthrust) Hide(wingthrust1) Hide(wingthrust2) Hide(flare1) Hide(flare2) Hide(drop) end function script.FireWeapon(num) gun_1 = not gun_1 SetUnarmedAI() Sleep(50) -- delay before clearing attack order; else bomb loses target and fails to home Reload() end function script.AimWeapon(num) return true end function script.QueryWeapon(num) return (gun_1 and flare1) or flare2 end function script.BlockShot(num) return (GetUnitValue(COB.CRASHING) == 1) or RearmBlockShot() end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= .25 then Explode(base, sfxNone) Explode(wing1, sfxNone) Explode(wing2, sfxNone) return 1 elseif severity <= .50 or ((Spring.GetUnitMoveTypeData(unitID).aircraftState or "") == "crashing") then Explode(wing1, sfxFall + sfxSmoke + sfxFire) Explode(wing2, sfxFall + sfxSmoke + sfxFire) return 1 elseif severity <= .75 then Explode(wing1, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(wing2, sfxFall + sfxSmoke + sfxFire + sfxExplode) return 2 else Explode(wing1, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(wing2, sfxFall + sfxSmoke + sfxFire + sfxExplode) return 2 end end
gpl-2.0
spawnazzo/luci
applications/luci-statistics/luasrc/statistics/rrdtool/definitions/interface.lua
69
2769
--[[ Luci statistics - interface plugin diagram definition (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.statistics.rrdtool.definitions.interface", package.seeall) function rrdargs( graph, plugin, plugin_instance ) -- -- traffic diagram -- local traffic = { -- draw this diagram for each data instance per_instance = true, title = "%H: Transfer on %di", vlabel = "Bytes/s", -- diagram data description data = { -- defined sources for data types, if ommitted assume a single DS named "value" (optional) sources = { if_octets = { "tx", "rx" } }, -- special options for single data lines options = { if_octets__tx = { total = true, -- report total amount of bytes color = "00ff00", -- tx is green title = "Bytes (TX)" }, if_octets__rx = { flip = true, -- flip rx line total = true, -- report total amount of bytes color = "0000ff", -- rx is blue title = "Bytes (RX)" } } } } -- -- packet diagram -- local packets = { -- draw this diagram for each data instance per_instance = true, title = "%H: Packets on %di", vlabel = "Packets/s", -- diagram data description data = { -- data type order types = { "if_packets", "if_errors" }, -- defined sources for data types sources = { if_packets = { "tx", "rx" }, if_errors = { "tx", "rx" } }, -- special options for single data lines options = { -- processed packets (tx DS) if_packets__tx = { overlay = true, -- don't summarize total = true, -- report total amount of bytes color = "00ff00", -- processed tx is green title = "Processed (tx)" }, -- processed packets (rx DS) if_packets__rx = { overlay = true, -- don't summarize flip = true, -- flip rx line total = true, -- report total amount of bytes color = "0000ff", -- processed rx is blue title = "Processed (rx)" }, -- packet errors (tx DS) if_errors__tx = { overlay = true, -- don't summarize total = true, -- report total amount of packets color = "ff5500", -- tx errors are orange title = "Errors (tx)" }, -- packet errors (rx DS) if_errors__rx = { overlay = true, -- don't summarize flip = true, -- flip rx line total = true, -- report total amount of packets color = "ff0000", -- rx errors are red title = "Errors (rx)" } } } } return { traffic, packets } end
apache-2.0
Arcscion/Shadowlyre
scripts/zones/Abyssea-La_Theine/npcs/qm4.lua
3
1344
----------------------------------- -- Zone: Abyssea-LaTheine -- NPC: qm4 (???) -- Spawns Adamastor -- !pos ? ? ? 132 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(2894,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17318437) == ACTION_NONE) then -- mob not already spawned from this SpawnMob(17318437):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 2894); -- Inform payer what items they need. 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
Arcscion/Shadowlyre
scripts/globals/items/clump_of_beaugreens.lua
12
1201
----------------------------------------- -- ID: 4571 -- Item: clump_of_beaugreens -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility 2 -- Vitality -4 ----------------------------------------- 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,300,4571); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 2); target:addMod(MOD_VIT, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 2); target:delMod(MOD_VIT, -4); end;
gpl-3.0
jono659/enko
scripts/zones/Metalworks/npcs/Glarociquet_TK.lua
30
4750
----------------------------------- -- Area: Metalworks -- NPC: Glarociquet, T.K. -- @pos 19 -16 -28 237 -- X Grant Signet -- X Recharge Emperor Band, Empress Band, or Chariot Band -- X Accepts traded Crystals to fill up the Rank bar to open new Missions. -- X Sells items in exchange for Conquest Points -- X Start Supply Run Missions and offers a list of already-delivered supplies. -- Start an Expeditionary Force by giving an E.F. region insignia to you. ------------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/globals/common"); require("scripts/zones/Metalworks/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, JEUNO local guardtype = 2; -- 1: city, 2: foreign, 3: outpost, 4: border local size = table.getn(SandInv); local inventory = SandInv; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies." local region = player:getVar("supplyQuest_region"); player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region)); player:setVar("supplyQuest_started",0); player:setVar("supplyQuest_region",0); player:setVar("supplyQuest_fresh",0); else local Menu1 = getArg1(guardnation,player); local Menu2 = getExForceAvailable(guardnation,player); local Menu3 = conquestRanking(); local Menu4 = getSupplyAvailable(guardnation,player); local Menu5 = player:getNationTeleport(guardnation); local Menu6 = getArg6(player); local Menu7 = player:getCP(); local Menu8 = getRewardExForce(guardnation,player); player:startEvent(0x7ffb,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); 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]); 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 if (player:getNation() == guardnation) then itemCP = inventory[Item + 1]; else if (inventory[Item + 1] <= 8000) then itemCP = inventory[Item + 1] * 2; else itemCP = inventory[Item + 1] + 8000; end end if (player:hasItem(inventory[Item + 2]) == false) then 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 else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end break end end elseif (option >= 65541 and option <= 65565) then -- player chose supply quest. local region = option - 65541; player:addKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region)); player:setVar("supplyQuest_started",vanaDay()); player:setVar("supplyQuest_region",region); player:setVar("supplyQuest_fresh",getConquestTally()); end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Mount_Zhayolm/npcs/qm4.lua
3
1342
----------------------------------- -- Area: Mount Zhayolm -- NPC: ??? (Spawn Khromasoul Bhurborlor(ZNM T3)) -- !pos 88 -22 70 61 ----------------------------------- package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mount_Zhayolm/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local mobID = 17027474; if (trade:hasItemQty(2585,1) and trade:getItemCount() == 1) then -- Trade Vinegar Pie if (GetMobAction(mobID) == ACTION_NONE) then player:tradeComplete(); SpawnMob(mobID):updateClaim(player); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); 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
Arcscion/Shadowlyre
scripts/globals/mobskills/havoc_spiral.lua
33
1110
--------------------------------------------- -- Havoc Spiral -- -- Description: Deals damage to players in an area of effect. Additional effect: Sleep -- Type: Physical -- 2-3 Shadows -- Range: Unknown -- Special weaponskill unique to Ark Angel MR. Deals ~100-300 damage. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) -- TODO: Can skillchain? Unknown property. local numhits = 1; local accmod = 1; local dmgmod = 3; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_2_SHADOW); -- Witnessed 280 to a melee, 400 to a BRD, and 500 to a wyvern, so... target:delHP(dmg); MobStatusEffectMove(mob, target, EFFECT_SLEEP_I, 1, 0, math.random(30, 60)); return dmg; end;
gpl-3.0
develephant/mod_arthur
arthur/UtilsClass.lua
1
2040
--============================================================================-- --== mod_arthur - utilities --== An oauth.io module for CoronaSDK --== (c)2015 Chris Byerley <@develephant> --============================================================================-- local url_tools = require('socket.url') local crypto = require('crypto') local json = require('json') local Class = require('arthur.30log') local Utils = Class('Utils') function Utils:init() return false end --== Display Utils.cx = display.contentCenterX Utils.cy = display.contentCenterY Utils.cw = display.viewableContentWidth Utils.ch = display.viewableContentHeight --== URL encoding Utils.encode = url_tools.escape Utils.decode = url_tools.unescape Utils.parse = url_tools.parse --== JSON Utils.tbl2json = json.encode Utils.json2tbl = json.decode --== SHA1 Utils.get_hash = function( trim ) local sha = crypto.digest( crypto.sha1, ( tostring( os.time() )..'coronasdkrocks') ) if trim then sha = string.sub( sha, 1, trim ) end return sha end --== Display Area Utils.getPortalSize = function() return display.contentCenterX, display.contentCenterY, display.viewableContentWidth, display.viewableContentHeight end --== Print contents of a table, with keys sorted. local function printTable( t, indent ) local names = {} if not indent then indent = "" end for n,g in pairs(t) do table.insert(names,n) end table.sort(names) for i,n in pairs(names) do local v = t[n] if type(v) == "table" then if(v==t) then -- prevent endless loop if table contains reference to itself print(indent..tostring(n)..": <-") else print(indent..tostring(n)..":") printTable(v,indent.." ") end else if type(v) == "function" then print(indent..tostring(n).."()") else print(indent..tostring(n)..": "..tostring(v)) end end end end --== Alias to 'trace' Utils.trace = printTable return Utils
mit
jono659/enko
scripts/globals/spells/invisible.lua
22
1187
----------------------------------------- -- Spell: Invisible -- Lessens chance of being detected by sight. -- Duration is random number between 30 seconds and 5 minutes ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) if (target:hasStatusEffect(EFFECT_INVISIBLE) == false) then local duration = math.random(30, 300); if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then duration = duration * 3; end if (target:getMainLvl() < 20) then duration = duration * target:getMainLvl() / 20; -- level adjustment end if (target:getEquipID(15) == 13692) then -- skulker's cape duration = duration * 1.5; end spell:setMsg(230); target:addStatusEffect(EFFECT_INVISIBLE,0,10,(math.floor(duration) * SNEAK_INVIS_DURATION_MULTIPLIER)); else spell:setMsg(75); -- no effect. end return EFFECT_INVISIBLE; end;
gpl-3.0
ereizertmbot/siss
plugins/ingroup.lua
13
62332
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', lock_link = 'yes', sticker = 'ok', version = '3.0', groupmodel = 'normal', tag = 'no', lock_badw = 'no', lock_english = 'no', lock_join = 'no', lock_media = 'no', lock_share = 'no', welcome = 'group' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'به ریلیم جدید ما خوش آمدید') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', lock_link = 'yes', sticker = 'ok', version = '3.0', groupmodel = 'normal', tag = 'no', lock_badw = 'no', lock_english = 'no', lock_join = 'no', lock_media = 'no', lock_share = 'no', welcome = 'group' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'ریلیم اضافه شد!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', lock_link = 'yes', sticker = 'ok', version = '3.0', groupmodel = 'normal', tag = 'no', lock_badw = 'no', lock_english = 'no', lock_join = 'no', lock_media = 'no', lock_share = 'no', welcome = 'group' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'شما صاحب گروه شدید') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', lock_link = 'yes', sticker = 'ok', version = '3.0', groupmodel = 'normal', tag = 'no', lock_badw = 'no', lock_english = 'no', lock_join = 'no', lock_media = 'no', lock_share = 'no', welcome = 'group' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'گروه اضافه شد و شما صاحب آن شدید') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'ریلیم حذف شد') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'گروه حذف شد') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] end local lock_link = "Yes" if data[tostring(msg.to.id)]['settings']['lock_link'] then lock_link = data[tostring(msg.to.id)]['settings']['lock_link'] end local version = "2" if data[tostring(msg.to.id)]['settings']['version'] then version = data[tostring(msg.to.id)]['settings']['version'] end local groupmodel = "normal" if data[tostring(msg.to.id)]['settings']['groupmodel'] then groupmodel = data[tostring(msg.to.id)]['settings']['groupmodel'] end local sticker = "ok" if data[tostring(msg.to.id)]['settings']['sticker'] then sticker = data[tostring(msg.to.id)]['settings']['sticker'] end local tag = "no" if data[tostring(msg.to.id)]['settings']['tag'] then tag = data[tostring(msg.to.id)]['settings']['tag'] end local lock_badw = "no" if data[tostring(msg.to.id)]['settings']['lock_badw'] then lock_badw = data[tostring(msg.to.id)]['settings']['lock_badw'] end local lock_english = "no" if data[tostring(msg.to.id)]['settings']['lock_english'] then lock_english = data[tostring(msg.to.id)]['settings']['lock_english'] end local lock_join = "no" if data[tostring(msg.to.id)]['settings']['lock_join'] then lock_join = data[tostring(msg.to.id)]['settings']['lock_join'] end local lock_media = "no" if data[tostring(msg.to.id)]['settings']['lock_media'] then lock_media = data[tostring(msg.to.id)]['settings']['lock_media'] end local lock_share = "no" if data[tostring(msg.to.id)]['settings']['lock_share'] then lock_share = data[tostring(msg.to.id)]['settings']['lock_share'] end local welcome = "group" if data[tostring(msg.to.id)]['settings']['welcome'] then welcome = data[tostring(msg.to.id)]['settings']['welcome'] end local settings = data[tostring(target)]['settings'] local text = "تنظیمات گروه:\n⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙\n>قفل نام گروه : "..settings.lock_name.."\n>قفل عکس گروه : "..settings.lock_photo.."\n>قفل اعضا : "..settings.lock_member.."\n>ممنوعیت ارسال لینک : "..lock_link.."\n>قفل ورود : "..lock_join.."\n>قفل رسانه : "..lock_media.."\n>قفل اشتراک گذاری : "..lock_share.."\n>حساسیت اسپم : "..NUM_MSG_MAX.."\n>قفل ربات ها : "..bots_protection.."\n>خوشامد : "..welcome.."\n>قفل تگ : "..tag.."\n>قفل اینگلیسی :"..lock_english.."\n>قفل فحش : "..lock_badw.."\n>مدل گروه : "..groupmodel.."\n>ورژن : "..version return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "قفط مدیران" end local data_cat = 'توضیحات' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'توضیحات گروه به این متن تغییر یافت:\n'..about end local function get_description(msg, data) local data_cat = 'توضیحات' if not data[tostring(msg.to.id)][data_cat] then return 'توضیحی موجود نیست' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'درباره'..about end local function lock_group_join(msg, data, target) if not is_momod(msg) then return "قفط مدیران" end local group_join_lock = data[tostring(target)]['settings']['lock_join'] if group_join_lock == 'yes' then return 'ورود از قبل قفل است' else data[tostring(target)]['settings']['lock_join'] = 'yes' save_data(_config.moderation.data, data) return 'ورود قفل شد' end end local function unlock_group_join(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_join_lock = data[tostring(target)]['settings']['lock_join'] if group_join_lock == 'no' then return 'ورود از قبل آزاد است' else data[tostring(target)]['settings']['lock_join'] = 'no' save_data(_config.moderation.data, data) return 'ورود آزاد شد' end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_tag_lock = data[tostring(target)]['settings']['tag'] if group_tag_lock == 'yes' then return 'تگ کردن از قبل قفل است🔒' else data[tostring(target)]['settings']['tag'] = 'yes' save_data(_config.moderation.data, data) return 'تگ کردن ممنوع شد✅🔒' end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_tag_lock = data[tostring(target)]['settings']['tag'] if group_tag_lock == 'no' then return 'تگ کردن از قبل آزاد است🔓' else data[tostring(target)]['settings']['tag'] = 'no' save_data(_config.moderation.data, data) return 'تگ کردن آزاد شد✅🔓' end end local function lock_group_english(msg, data, target) if not is_momod(msg) then return "قفط مدیران❗️" end local group_english_lock = data[tostring(target)]['settings']['lock_english'] if group_english_lock == 'yes' then return 'ایگلیسی از قبل قفل است🔒' else data[tostring(target)]['settings']['lock_english'] = 'yes' save_data(_config.moderation.data, data) return 'اینگلیسی قفل شد✅🔒' end end local function unlock_group_english(msg, data, target) if not is_momod(msg) then return "قفط مدیران❗️" end local group_english_lock = data[tostring(target)]['settings']['lock_english'] if group_english_lock == 'no' then return 'اینگلیسی از قبل باز است🔓' else data[tostring(target)]['settings']['lock_english'] = 'no' save_data(_config.moderation.data, data) return 'اینگلیسی ازاد شد✅🔓' end end local function lock_group_badw(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'yes' then return 'فحاشی از قبل ممنوع است🔒' else data[tostring(target)]['settings']['lock_badw'] = 'yes' save_data(_config.moderation.data, data) return 'فحاشی قفل شد✅🔒' end end local function unlock_group_badw(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'no' then return 'فحاشی از قبل آزاد است🔓' else data[tostring(target)]['settings']['lock_badw'] = 'no' save_data(_config.moderation.data, data) return 'فحاشی آزاد شد✅🔓' end end local function lock_group_link(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'ارسال لینک از قبل ممنوع است🔒' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'ارسال لینک ممنوع شد✅🔒' end end local function unlock_group_link(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'ارسال لینک از قبل آزاد است🔓' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'ارسال لینک آزاد شد✅🔓' end end local function lock_group_english(msg, data, target) if not is_momod(msg) then return "فقط برای مدیران❗️" end local group_english_lock = data[tostring(target)]['settings']['lock_english'] if group_english_lock == 'yes' then return 'اینگلیسی از قبل قفل است🔒' else data[tostring(target)]['settings']['lock_english'] = 'yes' save_data(_config.moderation.data, data) return 'اینگلیسی آزاد شد✅🔒' end end local function unlock_group_english(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_english_lock = data[tostring(target)]['settings']['lock_english'] if group_english_lock == 'no' then return 'اینگلیسی از قبل آزاد است🔓' else data[tostring(target)]['settings']['lock_english'] = 'no' save_data(_config.moderation.data, data) return 'اینگلیسی آژاد شد✅🔓' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "قفط مدیران" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'قفل ربات ها از قبل فعال است' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'ورود ربات ها قفل شد' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'ورود ربات ها از قبل آزاد است' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'ورود ربات ها ازاد شد' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "فقط برای مدیران" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'نام گروه از قبل قفل است' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'نام گروه قفل شد' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'نام گروه از قبل باز است' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'نام گروه باز شد' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "فقط توسط گلوبال ادمین ها" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'ارسال پیام سریع ممنوع از قبل ممنوع بود' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'اسپم قفل شد' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "فقط برای گلوبال ادمین ها" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'اسپم قفل نیست!' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'ارسال سریع پیام آزاد شد' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "فقط برای مدیران!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'ورود اعضا از قبل قفل است' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'ورود اعضا قفل شد' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'عضو گیری ازاد است' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'عضو گیری ازاد شد' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "فقط برای مدیران" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'خروج از قبل ممنوع بود' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'کسانی که خارج میشوند بن خواهند شد' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "فقط مدیران!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'خروج آزاد بود' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'خروج آزاد شد' end end local function lock_group_media(msg, data, target) if not is_momod(msg) then return "قفط مدیران" end local group_media_lock = data[tostring(target)]['settings']['lock_media'] if group_media_lock == 'yes' then return 'رسانه از قبل قفل است' else data[tostring(target)]['settings']['lock_media'] = 'yes' save_data(_config.moderation.data, data) return 'ارسال رسانه ممنوع شد' end end local function unlock_group_media(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_media_lock = data[tostring(target)]['settings']['lock_media'] if group_media_lock == 'no' then return 'ارسال رسانه از قبل آزاد است' else data[tostring(target)]['settings']['lock_media'] = 'no' save_data(_config.moderation.data, data) return 'ارسال رسانه آزاد شد' end end local function lock_group_share(msg, data, target) if not is_momod(msg) then return "قفط مدیران" end local group_share_lock = data[tostring(target)]['settings']['lock_share'] if group_share_lock == 'yes' then return 'اشتراک گذاری شماره از قبل ممنوع است' else data[tostring(target)]['settings']['lock_share'] = 'yes' save_data(_config.moderation.data, data) return 'اشتراک گذاری شماره ممنوع شد' end end local function unlock_group_share(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_share_lock = data[tostring(target)]['settings']['lock_share'] if group_share_lock == 'no' then return 'اشتراک گذاری شماره آزاد بود' else data[tostring(target)]['settings']['lock_share'] = 'no' save_data(_config.moderation.data, data) return 'اشتراک گذاری شماره آزاد شد' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'عکس گروه قفل نیست' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'عکس گروه باز شد' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local data_cat = 'قوانین' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'قوانین گروه به این متن تغییر یافت:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "شما ادمین نیستید" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'گروه از قبل اد شده' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "شما ادمین نیستید" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'ریلیم از قبل اد شده' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "شما ادمین نیستید" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'گروه اضافه نشده' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "شما ادمین نیستید" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'ریلیم اد نشده' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'قوانین' if not data[tostring(msg.to.id)][data_cat] then return 'قانونی موجود نیست' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'قوانین گروه:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'عکس ذخیره شد!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_english, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'گروه اضافه نشده') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_english..' از قبل مدیر است') end data[group]['moderators'][tostring(member_id)] = member_english save_data(_config.moderation.data, data) return send_large_msg(receiver, member_english..' ترفیع یافت') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.english then member_english = '@'.. msg.from.english else member_english = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_english, member_id) end end local function demote(receiver, member_english, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'گروه اضافه نشده') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_english..' مدیر نیست !') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_english..' تنزل یافت') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.english then member_english = '@'..msg.from.english else member_english = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_english, member_id) end end local function setleader_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as leader") local text = msg.from.print_name:gsub("_", " ").." اکنون صاحب گروه است " return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_english = "@"..result.english local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'ترفیع' then return promote(receiver, member_english, member_id) elseif mod_cmd == 'تنزل' then return demote(receiver, member_english, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'گروه اد نشده' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'دراین گروه هیچ مدیری وجود ندارد' end local i = 1 local message = '\nلیست مدیر های گروه ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function fa_help() local help_fa_text = tostring(_config.help_text) return help_fa_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function user_msgs(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 = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'اضافه' or matches[1] == 'add' and not matches[2] then if is_realm(msg) then return 'خطا : از قبل ریلیم بوده' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'اضافه' or matches[1] == 'add ' and matches[2] == 'ریلیم' or matches[2] == 'realm' then if is_group(msg) then return 'خطا : اینجا یک گروه است' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'حذف' or matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'حذف' or matches[1] == 'rem' and matches[2] == 'ریلیم' or matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'تنظیم نام' or matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'تنظیم عکس' or matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'لطفا عکس جدید گروه را ارسال کنید' end if matches[1] == 'ترفیع' or matches[1] == 'promote' and not matches[2] then if not is_owner(msg) then return "فقط توسط صاحب گروه" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'ترفیع' or matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "فقط توسط صاحب گروه" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'ترفیع', from_id = msg.from.id } local english = matches[2] local english = string.gsub(matches[2], '@', '') return res_user(english, promote_demote_res, cbres_extra) end if matches[1] == 'تنزل' or matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "فقط توسط صاحب گروه" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'تنزل' or matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "فقط توسط صاحب گروه" end if string.gsub(matches[2], "@", "") == msg.from.english and not is_owner(msg) then return "شما نمیتوانید مقام خود را حذف کنید" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'تنزل', from_id = msg.from.id } local english = matches[2] local english = string.gsub(matches[2], '@', '') return res_user(english, promote_demote_res, cbres_extra) end if matches[1] == 'لیست مدیران' or matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'توضیحات' or matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'قوانین' or matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'تنظیم' or matches[1] == 'set' then if matches[2] == 'قوانین' or matches[2] == 'rules'then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'توضیحات' or matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'قفل' or matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'نام' or matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'اعضا' or matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'اسپم' or matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'ورود' or matches[2] == 'join' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked join ") return lock_group_join(msg, data, target) end if matches[2] == 'رسانه' or matches[2] == 'media' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked media ") return lock_group_media(msg, data, target) end if matches[2] == 'اشتراک گذاری' or matches[2] == 'share' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked share ") return lock_group_share(msg, data, target) end if matches[2] == 'ربات ها' or matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'لینک' or matches[2] == 'link' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link🔒 ") return lock_group_link(msg, data, target) end if matches[2] == 'تگ' or matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag🔒 ") return lock_group_tag(msg, data, target) end if matches[2] == 'فحش' or matches[2] == 'badw' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked badw🔒 ") return lock_group_badw(msg, data, target) end if matches[2] == 'اینگلیسی' or matches[2] == 'english' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked english🔒 ") return lock_group_english(msg, data, target) end if matches[2] == 'خروج' or matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end end if matches[1] == 'بازکردن' or matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'نام' or matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'اعضا' or matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'عکس' or matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'اسپم' or matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'ورود' or matches[2] == 'join' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked join ") return unlock_group_join(msg, data, target) end if matches[2] == 'رسانه' or matches[2] == 'media' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked media ") return unlock_group_media(msg, data, target) end if matches[2] == 'اشتراگ گذاری' or matches[2] == 'share' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked share ") return unlock_group_share(msg, data, target) end if matches[2] == 'ربات ها' or matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'لینک' or matches[2] == 'link' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link🔓 ") return unlock_group_link(msg, data, target) end if matches[2] == 'تگ' or matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag🔓 ") return unlock_group_tag(msg, data, target) end if matches[2] == 'فحش' or matches[2] == 'badw' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked badw🔓 ") return unlock_group_badw(msg, data, target) end if matches[2] == 'اینگلیسی' or matches[2] == 'english' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked english🔓 ") return unlock_group_english(msg, data, target) end if matches[2] == 'خروج' or matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end end if matches[1] == 'setversion' then if not is_sudo(msg) then return "فقط برای سودو❗️" end if matches[2] == '1.0' then if version ~= '1.0' then data[tostring(msg.to.id)]['settings']['version'] = '1.0' save_data(_config.moderation.data, data) end return 'group version has been changed to 1.0' end if matches[2] == '2.0' then if version ~= '2.0' then data[tostring(msg.to.id)]['settings']['version'] = '2.0' save_data(_config.moderation.data, data) end return 'group version has been changed to 2.0' end if matches[2] == '3.0' then if version == '3.0' then return 'group version has been changed to 3.0' else data[tostring(msg.to.id)]['settings']['version'] = '3.0' save_data(_config.moderation.data, data) return 'group version has been changed to 3.0' end end end if matches[1] == 'setgroup' then if not is_sudo(msg) then return "فقط برای سودو❗️" end if matches[2] == 'realm' then if groupmodel ~= 'realm' then data[tostring(msg.to.id)]['settings']['groupmodel'] = 'realm' save_data(_config.moderation.data, data) end return 'Group model has been changed to realm' end if matches[2] == 'support' then if groupmodel ~= 'support' then data[tostring(msg.to.id)]['settings']['groupmodel'] = 'support' save_data(_config.moderation.data, data) end return 'Group model has been changed to support' end if matches[2] == 'feedback' then if groupmodel ~= 'feedback' then data[tostring(msg.to.id)]['settings']['groupmodel'] = 'feedback' save_data(_config.moderation.data, data) end return 'Group model has been changed to feedback' end if matches[2] == 'vip' then if groupmodel ~= 'vip' then data[tostring(msg.to.id)]['settings']['groupmodel'] = 'vip' save_data(_config.moderation.data, data) end return 'Group model has been changed to vip' end if matches[2] == 'normal' then if groupmodel == 'normal' then return 'Group model has been changed to normal' else data[tostring(msg.to.id)]['settings']['groupmodel'] = 'normal' save_data(_config.moderation.data, data) return 'Group model has been changed to normal' end end end if matches[1] == 'settings' or matches[1] == 'تنظیمات' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'لینک جدید' or matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "فقط برای مدیران" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*خطا : \nربات سازنده گروه نیست') end send_large_msg(receiver, "لینک جدید ساخته شد") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'لینک' or matches[1] == 'link' then if not is_momod(msg) then return "فقط مدیران" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "اول با لینک جدید یک لینک جدید بسازید" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "لینک گروه:\n🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷\n"..group_link end if matches[1] == 'لینک خصوصی' or matches[1] == 'linkpv' then if not is_momod(msg) then return "فقط برای مدیران" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "اول با لینک جدید یک لینک جدید بسازید" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") send_large_msg('user#id'..msg.from.id, "لینک گروه:\n🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷\n"..group_link) end if matches[1] == 'دارنده' or matches[1] == 'setleader' and matches[2] then if not is_owner(msg) then return "شما مجاز نیستید" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as leader") local text = matches[2].." added as leader" return text end if matches[1] == 'دارنده' or matches[1] == 'setleader' and not matches[2] then if not is_owner(msg) then return "شما مجاز نیستید" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setleader_by_reply, false) end end if matches[1] == 'صاحب گروه' or matches[1] == 'owner' then local group_leader = data[tostring(msg.to.id)]['set_owner'] if not group_leader then return "no leader,ask admins in support groups to set leader for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /leader") return "آیدی صاحب گروه : ["..group_leader..']' end if matches[1] == 'صاحب' or matches[1] == 'setgpleader' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as leader" send_large_msg(receiver, text) return end if matches[1] == 'حساسیت' or matches[1] == 'setflood' then if not is_momod(msg) then return "شما مجاز نیستید" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "عددی از بین 5 و 20 انتخاب کنید" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'حساسیت اسپم تغییر یافت به '..matches[2] end if matches[1] == 'پاک کردن' or matches[1] == 'clean' then if not is_owner(msg) then return "شما مجاز نیستید" end if matches[2] == 'اعضا' or matches[2] == 'member' then if not is_owner(msg) then return "شما مجاز نیستید" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'مدیران' or matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'مدیری در گروه نیست' end local message = '\nلیست مدیران گروه ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' or matches[2] == 'قوانین' then local data_cat = 'قوانین' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'توضیحات' or matches[2] == 'about' then local data_cat = 'توضیحات' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' or matches[1] == 'help'and matches[2] =='en' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'راهنما' or matches[1] == 'help'and matches[2] =='fa' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return fa_help() end if matches[1] == 'کد' or matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local english = matches[2] local english = english:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..english) return res_user(english, callbackres, cbres_extra) end if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^(اضافه)$", "^(اضافه) (ریلیم)$", "^(حذف)$", "^(حذف) (ریلیم)$", "^(قوانین)$", "^(توضیحات)$", "^(تنظیم نام) (.*)$", "^(تنظیم عکس)$", "^(ترفیع) (.*)$", "^(ترفیع)", "^(پاک کردن) (.*)$", "^(kill) (chat)$", "^(kill) (realm)$", "^(تنزل) (.*)$", "^(تنزل)", "^(تنظیم) ([^%s]+) (.*)$", "^(قفل) (.*)$", "^(دارنده) (%d+)$", "^(دارنده)", "^(صاحب گروه)$", "^(کد) (.*)$", "^(صاحب) (%d+) (%d+)$",-- (group id) (leader id) "^(بازکردن) (.*)$", "^(حساسیت) (%d+)$", "^(تنظیمات)$", "^(لیست مدیران)$", "^(لینک جدید)$", "^(لینک)$", "^(لینک خصوصی)$", "^(setversion) (.*)$", "^(setgroup) (.*)$", "^(add)$", "^(add) (realm)$", "^(rem)$", "^(rem) (realm)$", "^(rules)$", "^(about)$", "^(setname) (.*)$", "^(help) (en)$", "^(help)$", "^(setphoto)$", "^(promote) (.*)$", "^(promote)", "^(clean) (.*)$", "^(demote) (.*)$", "^(demote)", "^(set) ([^%s]+) (.*)$", "^(lock) (.*)$", "^(setleader) (%d+)$", "^(setleader)", "^(owner)$", "^(res) (.*)$", "^(setgpleader) (%d+) (%d+)$", "^(unlock) (.*)$", "^(setflood) (%d+)$", "^(settings)$", "^(modlist)$", "^(newlink)$", "^(link)$", "^(kickinactive)$", "^(kickinactive) (%d+)$", "^(linkpv)$", "^[!/#](add)$", "^[!/#](add) (realm)$", "^[!/#](rem)$", "^[!/#](rem) (realm)$", "^[!/#](rules)$", "^[!/#](about)$", "^[!/#](setname) (.*)$", "^[!/#](help) (en)$", "^[!/#](help)$", "^[!/#](setphoto)$", "^[!/#](promote) (.*)$", "^[!/#](promote)", "^[!/#](clean) (.*)$", "^[!/#](demote) (.*)$", "^[!/#](demote)", "^[!/#](set) ([^%s]+) (.*)$", "^[!/#](lock) (.*)$", "^[!/#](setleader) (%d+)$", "^[!/#](setleader)", "^[!/#](owner)$", "^[!/#](res) (.*)$", "^[!/#](setgpleader) (%d+) (%d+)$", "^[!/#](unlock) (.*)$", "^[!/#](setflood) (%d+)$", "^[!/#](settings)$", "^[!/#](modlist)$", "^[!/#](newlink)$", "^[!/#](link)$", "^[!/#](linkpv)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
jotson/1gam-feb2013
zoetrope/utils/factory.lua
7
3584
-- Class: Factory -- A factory allows for simple object pooling; that is, -- reusing object instances instead of creating them and deleting -- them as needed. This approach saves CPU and memory. -- -- Be careful of accidentally adding an instance to a view twice. -- This will manifest itself as the sprite moving twice as fast, for -- example, each time it is recycled. The easiest way to avoid this -- problem is for the object to add itself to the view in its onNew -- handler, since that will only be called once. -- -- If you only want a certain number of instances of a class ever -- created, first call preload() to create as many instances as you want, -- then freeze() to prevent any new instances from being created. -- If a factory is ever asked to make a new instance of a frozen class -- but none are available for recycling, it returns nil. -- -- Event: onReset -- Called not on the factory, but the object is creates whenever -- it is either initially created or recycled via create(). -- -- Extends: -- <Class> Factory = Class:extend{ -- private property: objects ready to be recycled, stored by prototype _recycled = {}, -- private property: tracks which pools cannot be added to, stored by prototype. _frozen = {}, -- Method: create -- Creates a fresh object, either by reusing a previously -- recycled one or creating a new instance. If the object has -- a revive method, it calls it. -- -- Arguments: -- prototype - <Class> object -- props - table of properties to mix into the class -- -- Returns: -- fresh object create = function (self, prototype, props) local newObj if STRICT then assert(prototype.instanceOf and prototype:instanceOf(Class), 'asked to create something that isn\'t a class') end if self._recycled[prototype] and #self._recycled[prototype] > 0 then newObj = table.remove(self._recycled[prototype]) if props then newObj:mixin(props) end else -- create a new instance if we're allowed to if not self._frozen[prototype] then newObj = prototype:new(props) else return nil end end if newObj.revive then newObj:revive() end if newObj.onReset then newObj:onReset() end return newObj end, -- Method: recycle -- Marks an object as ready to be recycled. If the object -- has a die method, then this function it. -- -- Arguments: -- object - object to recycle -- -- Returns: -- nothing recycle = function (self, object) if not self._recycled[object.prototype] then self._recycled[object.prototype] = {} end table.insert(self._recycled[object.prototype], object) if object.die then object:die() end end, -- Method: preload -- Preloads the factory with a certain number of instances of a class. -- -- Arguments: -- prototype - class object -- count - number of objects to create -- -- Returns: -- nothing preload = function (self, prototype, count) if not self._recycled[prototype] then self._recycled[prototype] = {} end local i for i = 1, count do table.insert(self._recycled[prototype], prototype:new()) end end, -- Method: freeze -- Prevents any new instances of a class from being created via create(). -- -- Arguments: -- prototype - class object -- -- Returns: -- nothing freeze = function (self, prototype) self._frozen[prototype] = true end, -- Method: unfreeze -- Allows new instances of a class to be created via create(). -- -- Arguments: -- prototype - class object -- -- Returns: -- nothing unfreeze = function (self, prototype) self._frozen[prototype] = false end }
mit
zhangxiangxiao/nn
WeightedEuclidean.lua
43
8173
local WeightedEuclidean, parent = torch.class('nn.WeightedEuclidean', 'nn.Module') function WeightedEuclidean:__init(inputSize,outputSize) parent.__init(self) self.weight = torch.Tensor(inputSize,outputSize) self.gradWeight = torch.Tensor(inputSize,outputSize) -- each template (output dim) has its own diagonal covariance matrix self.diagCov = torch.Tensor(inputSize,outputSize) self.gradDiagCov = torch.Tensor(inputSize,outputSize) self:reset() end function WeightedEuclidean:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(1)) end self.weight:uniform(-stdv, stdv) self.diagCov:fill(1) end local function view(res, src, ...) local args = {...} if src:isContiguous() then res:view(src, table.unpack(args)) else res:reshape(src, table.unpack(args)) end end function WeightedEuclidean:updateOutput(input) -- lazy-initialize self._diagCov = self._diagCov or self.output.new() self._input = self._input or input.new() self._weight = self._weight or self.weight.new() self._expand = self._expand or self.output.new() self._expand2 = self._expand or self.output.new() self._expand3 = self._expand3 or self.output.new() self._repeat = self._repeat or self.output.new() self._repeat2 = self._repeat2 or self.output.new() self._repeat3 = self._repeat3 or self.output.new() local inputSize, outputSize = self.weight:size(1), self.weight:size(2) -- y_j = || c_j * (w_j - x) || if input:dim() == 1 then view(self._input, input, inputSize, 1) self._expand:expandAs(self._input, self.weight) self._repeat:resizeAs(self._expand):copy(self._expand) self._repeat:add(-1, self.weight) self._repeat:cmul(self.diagCov) self.output:norm(self._repeat, 2, 1) self.output:resize(outputSize) elseif input:dim() == 2 then local batchSize = input:size(1) view(self._input, input, batchSize, inputSize, 1) self._expand:expand(self._input, batchSize, inputSize, outputSize) -- make the expanded tensor contiguous (requires lots of memory) self._repeat:resizeAs(self._expand):copy(self._expand) self._weight:view(self.weight, 1, inputSize, outputSize) self._expand2:expandAs(self._weight, self._repeat) self._diagCov:view(self.diagCov, 1, inputSize, outputSize) self._expand3:expandAs(self._diagCov, self._repeat) if torch.type(input) == 'torch.CudaTensor' then -- requires lots of memory, but minimizes cudaMallocs and loops self._repeat2:resizeAs(self._expand2):copy(self._expand2) self._repeat:add(-1, self._repeat2) self._repeat3:resizeAs(self._expand3):copy(self._expand3) self._repeat:cmul(self._repeat3) else self._repeat:add(-1, self._expand2) self._repeat:cmul(self._expand3) end self.output:norm(self._repeat, 2, 2) self.output:resize(batchSize, outputSize) else error"1D or 2D input expected" end return self.output end function WeightedEuclidean:updateGradInput(input, gradOutput) if not self.gradInput then return end self._div = self._div or input.new() self._output = self._output or self.output.new() self._expand4 = self._expand4 or input.new() self._gradOutput = self._gradOutput or input.new() if not self.fastBackward then self:updateOutput(input) end local inputSize, outputSize = self.weight:size(1), self.weight:size(2) --[[ dy_j -2 * c_j * c_j * (w_j - x) c_j * c_j * (x - w_j) ---- = -------------------------- = --------------------- dx 2 || c_j * (w_j - x) || y_j --]] -- to prevent div by zero (NaN) bugs self._output:resizeAs(self.output):copy(self.output):add(0.0000001) view(self._gradOutput, gradOutput, gradOutput:size()) self._div:cdiv(gradOutput, self._output) if input:dim() == 1 then self._div:resize(1, outputSize) self._expand4:expandAs(self._div, self.weight) if torch.type(input) == 'torch.CudaTensor' then self._repeat2:resizeAs(self._expand4):copy(self._expand4) self._repeat2:cmul(self._repeat) else self._repeat2:cmul(self._repeat, self._expand4) end self._repeat2:cmul(self.diagCov) self.gradInput:sum(self._repeat2, 2) self.gradInput:resizeAs(input) elseif input:dim() == 2 then local batchSize = input:size(1) self._div:resize(batchSize, 1, outputSize) self._expand4:expand(self._div, batchSize, inputSize, outputSize) if torch.type(input) == 'torch.CudaTensor' then self._repeat2:resizeAs(self._expand4):copy(self._expand4) self._repeat2:cmul(self._repeat) self._repeat2:cmul(self._repeat3) else self._repeat2:cmul(self._repeat, self._expand4) self._repeat2:cmul(self._expand3) end self.gradInput:sum(self._repeat2, 3) self.gradInput:resizeAs(input) else error"1D or 2D input expected" end return self.gradInput end function WeightedEuclidean:accGradParameters(input, gradOutput, scale) local inputSize, outputSize = self.weight:size(1), self.weight:size(2) scale = scale or 1 --[[ dy_j 2 * c_j * c_j * (w_j - x) c_j * c_j * (w_j - x) ---- = ------------------------- = --------------------- dw_j 2 || c_j * (w_j - x) || y_j dy_j 2 * c_j * (w_j - x)^2 c_j * (w_j - x)^2 ---- = ----------------------- = ----------------- dc_j 2 || c_j * (w_j - x) || y_j --]] -- assumes a preceding call to updateGradInput if input:dim() == 1 then self.gradWeight:add(-scale, self._repeat2) self._repeat:cdiv(self.diagCov) self._repeat:cmul(self._repeat) self._repeat:cmul(self.diagCov) if torch.type(input) == 'torch.CudaTensor' then self._repeat2:resizeAs(self._expand4):copy(self._expand4) self._repeat2:cmul(self._repeat) else self._repeat2:cmul(self._repeat, self._expand4) end self.gradDiagCov:add(self._repeat2) elseif input:dim() == 2 then self._sum = self._sum or input.new() self._sum:sum(self._repeat2, 1) self._sum:resize(inputSize, outputSize) self.gradWeight:add(-scale, self._sum) if torch.type(input) == 'torch.CudaTensor' then -- requires lots of memory, but minimizes cudaMallocs and loops self._repeat:cdiv(self._repeat3) self._repeat:cmul(self._repeat) self._repeat:cmul(self._repeat3) self._repeat2:resizeAs(self._expand4):copy(self._expand4) self._repeat:cmul(self._repeat2) else self._repeat:cdiv(self._expand3) self._repeat:cmul(self._repeat) self._repeat:cmul(self._expand3) self._repeat:cmul(self._expand4) end self._sum:sum(self._repeat, 1) self._sum:resize(inputSize, outputSize) self.gradDiagCov:add(scale, self._sum) else error"1D or 2D input expected" end end function WeightedEuclidean:type(type, tensorCache) if type then -- prevent premature memory allocations self._input = nil self._output = nil self._gradOutput = nil self._weight = nil self._div = nil self._sum = nil self._expand = nil self._expand2 = nil self._expand3 = nil self._expand4 = nil self._repeat = nil self._repeat2 = nil self._repeat3 = nil end return parent.type(self, type, tensorCache) end function WeightedEuclidean:parameters() return {self.weight, self.diagCov}, {self.gradWeight, self.gradDiagCov} end function WeightedEuclidean:accUpdateGradParameters(input, gradOutput, lr) local gradWeight = self.gradWeight local gradDiagCov = self.gradDiagCov self.gradWeight = self.weight self.gradDiagCov = self.diagCov self:accGradParameters(input, gradOutput, -lr) self.gradWeight = gradWeight self.gradDiagCov = gradDiagCov end
bsd-3-clause
Arcscion/Shadowlyre
scripts/zones/Yuhtunga_Jungle/npcs/Mahol_IM.lua
3
3324
----------------------------------- -- Area: Yuhtunga Jungle -- NPC: Mahol, I.M. -- Outpost Conquest Guards -- !pos -242.487 -1 -402.772 123 ----------------------------------- package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Yuhtunga_Jungle/TextIDs"); local guardnation = NATION_BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ELSHIMOLOWLANDS; local csid = 0x7ff9; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %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 == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
ANONYMOUSE4/DevABBAS_ALSAIDI
plugins/stats.lua
1
4869
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY ABBAS ALSAIDI ▀▄ ▄▀ ▀▄ ▄▀ WRITER ABBAS ▀▄ ▄▀ ▀▄ ▄▀ Dev@Abbas9_9 ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do -- Returns a table with `name` and `msgs` 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(receiver, chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user 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 -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user 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 -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'Abbas9_9' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' or msg.to.type == 'channel' then local receiver = get_receiver(msg) local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(receiver, chat_id) else return end end if matches[2] == "Abbas9_9" then -- Put everything you like :) if not is_admin1(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin1(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[#!/]([Ss]tats)$", "^[#!/]([Ss]tatslist)$", "^[#!/]([Ss]tats) (group) (%d+)", "^[#!/]([Ss]tats) (Abbas9_9)", "^[#!/]([Tt]Abbas9_9)" }, run = run } end -----لا تمسح الحقوق ياعار غيرك تعبان على الملفات ------- --------------------عباس السعيدي----------------------- --------------------Dev@Abbas9_9-----------------------
gpl-2.0
hypnoscope/let-s-code-an-indie-game
episode_27/src/mobs/player.lua
5
1157
local keyboardMovement = require("src.logic.ai.movement.keyboard_movement") local spritesheet = require("src.graphics.spritesheet") local entity = require("src.logic.entity") local punch = require("src.items.punch") local status = require("src.logic.status") local animation = require("src.graphics.animation") local position = require("src.logic.position") local player = {} local adventurerSprite = spritesheet.create( "assets/sprites/adventurer.png", 16, animation.STAND) local action1 = function (self, game) local currentRoom = game.map:currentRoom() local pos = self.position local punchOffset = 10 if pos.left then punchOffset = -12 end currentRoom:addEntity(punch.create(position.create( pos.x + punchOffset, pos.y, pos.z, pos.left ))) self.interuptMovement = true local t = status.create(status.ticks(5), function (_, owner, game) owner.interuptMovement = false end) self:addStatus(t) end player.create = function () local player = entity.create( adventurerSprite, position.create(50, 0, 100), 56, keyboardMovement) player.action1 = action1 return player end return player
mit
jono659/enko
scripts/zones/Bastok_Markets/npcs/Reinberta.lua
11
1970
----------------------------------- -- Area: Bastok Markets -- NPC: Reinberta -- Type: Goldsmithing Guild Master -- @pos -190.605 -7.814 -59.432 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/crafting"); require("scripts/zones/Bastok_Markets/TextIDs"); local SKILLID = 51; -- Goldsmithing ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILLID); if(newRank ~= 0) then player:setSkillRank(SKILLID,newRank); player:startEvent(0x012d,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILLID); local testItem = getTestItem(player,npc,SKILLID); local guildMember = isGuildMember(player,6); if(guildMember == 1) then guildMember = 150995375; end if(canGetNewRank(player,craftSkill,SKILLID) == 1) then getNewRank = 100; end player:startEvent(0x012c,testItem,getNewRank,30,guildMember,44,0,0,0); end; -- 0x012c 0x012d 0x0192 ----------------------------------- -- 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 == 0x012c 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,64); end end end;
gpl-3.0
jono659/enko
scripts/globals/items/viking_herring.lua
35
1577
----------------------------------------- -- ID: 5183 -- Item: viking_herring -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 4 -- Mind -3 -- Attack % 12 -- Attack Cap 40 -- Ranged ATT % 12 -- Ranged ATT Cap 40 ----------------------------------------- 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,3600,5183); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -3); target:addMod(MOD_FOOD_ATTP, 12); target:addMod(MOD_FOOD_ATT_CAP, 40); target:addMod(MOD_FOOD_RATTP, 12); target:addMod(MOD_FOOD_RATT_CAP, 40); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -3); target:delMod(MOD_FOOD_ATTP, 12); target:delMod(MOD_FOOD_ATT_CAP, 40); target:delMod(MOD_FOOD_RATTP, 12); target:delMod(MOD_FOOD_RATT_CAP, 40); end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Lower_Jeuno/npcs/Bki_Tbujhja.lua
3
4433
----------------------------------- -- Area: Lower Jeuno -- NPC: Bki Tbujhja -- Involved in Quest: The Old Monument -- Starts and Finishes Quests: Path of the Bard (just start), The Requiem (BARD AF2) -- !pos -22 0 -60 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/shop"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local theRequiem = player:getQuestStatus(JEUNO,THE_REQUIEM); -- THE REQUIEM (holy water) if (theRequiem == QUEST_ACCEPTED and player:getVar("TheRequiemCS") == 2 and trade:hasItemQty(4154,1) and trade:getItemCount() == 1) then player:startEvent(151); end; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local aMinstrelInDespair = player:getQuestStatus(JEUNO,A_MINSTREL_IN_DESPAIR); local painfulMemory = player:getQuestStatus(JEUNO,PAINFUL_MEMORY); local theRequiem = player:getQuestStatus(JEUNO,THE_REQUIEM); -- THE OLD MONUMENT if (player:getVar("TheOldMonument_Event") == 1) then player:startEvent(181); -- mentions song runes in Buburimu -- PATH OF THE BARD (Bard Flag) elseif (aMinstrelInDespair == QUEST_COMPLETED and player:getVar("PathOfTheBard_Event") == 0) then player:startEvent(182); -- mentions song runes in Valkurm -- THE REQUIEM (Bard AF2) elseif (painfulMemory == QUEST_COMPLETED and theRequiem == QUEST_AVAILABLE and player:getMainJob() == JOBS.BRD and player:getMainLvl() >= AF2_QUEST_LEVEL) then if (player:getVar("TheRequiemCS") == 0) then player:startEvent(145); -- Long dialog & Start Quest "The Requiem" else player:startEvent(148); -- Shot dialog & Start Quest "The Requiem" end; elseif (theRequiem == QUEST_ACCEPTED and player:getVar("TheRequiemCS") == 2) then player:startEvent(146); -- During Quest "The Requiem" (before trading Holy Water) elseif (theRequiem == QUEST_ACCEPTED and player:getVar("TheRequiemCS") == 3 and player:hasKeyItem(STAR_RING1) == false) then if (math.random(1,2) == 1) then player:startEvent(147); -- oh, did you take the holy water and play the requiem? you must do both! else player:startEvent(149); -- his stone sarcophagus is deep inside the eldieme necropolis. end; elseif (theRequiem == QUEST_ACCEPTED and player:hasKeyItem(STAR_RING1) == true) then player:startEvent(150); -- Finish Quest "The Requiem" elseif (theRequiem == QUEST_COMPLETED) then player:startEvent(134); -- Standard dialog after "The Requiem" -- DEFAULT DIALOG else player:startEvent(180); end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- THE OLD MONUMENT if (csid == 181) then player:setVar("TheOldMonument_Event",2); -- PATH OF THE BARD elseif (csid == 182) then player:setVar("PathOfTheBard_Event",1); -- THE REQUIEM elseif (csid == 145 and option == 0) then player:setVar("TheRequiemCS",1); -- player declines quest elseif ((csid == 145 or csid == 148) and option == 1) then player:addQuest(JEUNO,THE_REQUIEM); player:setVar("TheRequiemCS",2); elseif (csid == 151) then player:setVar("TheRequiemCS",3); player:messageSpecial(ITEM_OBTAINED,4154); -- Holy Water (just message) player:setVar("TheRequiemRandom",math.random(1,5)); -- pick a random sarcophagus elseif (csid == 150) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14098); else player:addItem(14098); player:messageSpecial(ITEM_OBTAINED,14098); -- Choral Slippers player:addFame(JEUNO, 30); player:completeQuest(JEUNO,THE_REQUIEM); end; end; end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Aht_Urhgan_Whitegate/npcs/Fochacha.lua
3
2660
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Fochacha -- Type: Standard NPC -- !pos 2.897 -1 -10.781 50 -- Quest: Delivering the Goods ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vanishingact = player:getQuestStatus(AHT_URHGAN,VANISHING_ACT); local deliveryGoodsProg = player:getVar("deliveringTheGoodsCS"); local vanishActProg = player:getVar("vanishingactCS"); if (player:getQuestStatus(AHT_URHGAN,DELIVERING_THE_GOODS) == QUEST_AVAILABLE) then player:startEvent(0x0027); elseif (deliveryGoodsProg == 1) then player:startEvent(0x002e); elseif (deliveryGoodsProg == 2) then player:startEvent(0x0029); elseif (vanishingact == QUEST_ACCEPTED and vanishActProg == 2) then player:startEvent(0x002b); elseif (vanishActProg == 3) then player:startEvent(0x0030); elseif (vanishActProg == 4) then player:startEvent(0x0031); elseif (vanishingact == QUEST_COMPLETED) then player:startEvent(0x003b); else player:startEvent(0x002f); 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 == 0x0027) then player:addQuest(AHT_URHGAN,DELIVERING_THE_GOODS); player:setVar("deliveringTheGoodsCS",1); elseif (csid == 0x0029) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINEDX,2184,3); else player:setVar("deliveringTheGoodsCS",0); player:addItem(2184,3); player:messageSpecial(ITEM_OBTAINEDX,2184,3); player:completeQuest(AHT_URHGAN,DELIVERING_THE_GOODS); player:setVar("VANISHING_ACT_waitJPMidnight",getMidnight()); end elseif (csid == 0x002b) then player:setVar("vanishingactCS",3); end end;
gpl-3.0
Noiwex/gmod-medialib
lua/medialib/service_bass.lua
1
4683
local oop = medialib.load("oop") local mediaregistry = medialib.load("mediaregistry") local BASSService = oop.class("BASSService", "Service") function BASSService:load(url, opts) local media = oop.class("BASSMedia")() media._unresolvedUrl = url media._service = self hook.Run("Medialib_ProcessOpts", media, opts or {}) mediaregistry.add(media) self:resolveUrl(url, function(resolvedUrl, resolvedData) media:openUrl(resolvedUrl) if resolvedData and resolvedData.start and (not opts or not opts.dontSeek) then media:seek(resolvedData.start) end end) return media end local BASSMedia = oop.class("BASSMedia", "Media") function BASSMedia:initialize() self.bassPlayOptions = {"noplay", "noblock"} self.commandQueue = {} end function BASSMedia:getBaseService() return "bass" end function BASSMedia:updateFFT() local curFrame = FrameNumber() if self._lastFFTUpdate and self._lastFFTUpdate == curFrame then return end self._lastFFTUpdate = curFrame local chan = self.chan if not IsValid(chan) then return end self.fftValues = self.fftValues or {} chan:FFT(self.fftValues, FFT_512) end function BASSMedia:getFFT() return self.fftValues end function BASSMedia:draw(x, y, w, h) surface.SetDrawColor(0, 0, 0) surface.DrawRect(x, y, w, h) self:updateFFT() local fftValues = self:getFFT() if not fftValues then return end local valCount = #fftValues local valsPerX = (valCount == 0 and 1 or (w/valCount)) local barw = w / (valCount) for i=1, valCount do surface.SetDrawColor(HSVToColor(i, 0.9, 0.5)) local barh = fftValues[i]*h surface.DrawRect(x + i*barw, y + (h-barh), barw, barh) end end function BASSMedia:openUrl(url) local flags = table.concat(self.bassPlayOptions, " ") sound.PlayURL(url, flags, function(chan, errId, errName) self:bassCallback(chan, errId, errName) end) end function BASSMedia:openFile(path) local flags = table.concat(self.bassPlayOptions, " ") sound.PlayFile(path, flags, function(chan, errId, errName) self:bassCallback(chan, errId, errName) end) end function BASSMedia:bassCallback(chan, errId, errName) if not IsValid(chan) then ErrorNoHalt("[MediaLib] BassMedia play failed: ", errName) self._stopped = true self:emit("error", "loading_failed", string.format("BASS error id: %s; name: %s", errId, errName)) return end -- Check if media was stopped before loading if self._stopped then chan:Stop() return end self.chan = chan for _,c in pairs(self.commandQueue) do c(chan) end -- Empty queue self.commandQueue = {} self:startStateChecker() end function BASSMedia:startStateChecker() local timerId = "MediaLib_BASS_EndChecker_" .. self:hashCode() timer.Create(timerId, 1, 0, function() if IsValid(self.chan) and self.chan:GetState() == GMOD_CHANNEL_STOPPED then self:emit("ended") timer.Destroy(timerId) end end) end function BASSMedia:runCommand(fn) if IsValid(self.chan) then fn(self.chan) else self.commandQueue[#self.commandQueue+1] = fn end end function BASSMedia:setVolume(vol) self:runCommand(function(chan) chan:SetVolume(vol) end) end function BASSMedia:seek(time) self:runCommand(function(chan) if chan:IsBlockStreamed() then return end self._seekingTo = time local timerId = "MediaLib_BASSMedia_Seeker_" .. time .. "_" .. self:hashCode() local function AttemptSeek() -- someone used :seek with other time if self._seekingTo ~= time or -- chan not valid not IsValid(chan) then timer.Destroy(timerId) return end chan:SetTime(time) -- seek succeeded if math.abs(chan:GetTime() - time) < 1 then timer.Destroy(timerId) end end timer.Create(timerId, 0.2, 0, AttemptSeek) AttemptSeek() end) end function BASSMedia:getTime() if self:isValid() and IsValid(self.chan) then return self.chan:GetTime() end return 0 end function BASSMedia:getState() if not self:isValid() then return "error" end if not IsValid(self.chan) then return "loading" end local bassState = self.chan:GetState() if bassState == GMOD_CHANNEL_PLAYING then return "playing" end if bassState == GMOD_CHANNEL_PAUSED then return "paused" end if bassState == GMOD_CHANNEL_STALLED then return "buffering" end if bassState == GMOD_CHANNEL_STOPPED then return "paused" end -- umm?? return end function BASSMedia:play() self:runCommand(function(chan) chan:Play() self:emit("playing") end) end function BASSMedia:pause() self:runCommand(function(chan) chan:Pause() self:emit("paused") end) end function BASSMedia:stop() self._stopped = true self:runCommand(function(chan) chan:Stop() self:emit("ended") self:emit("destroyed") end) end function BASSMedia:isValid() return not self._stopped end
mit
srvz/telegram-bot
plugins/btc.lua
289
1375
-- See https://bitcoinaverage.com/api local function getBTCX(amount,currency) local base_url = 'https://api.bitcoinaverage.com/ticker/global/' -- Do request on bitcoinaverage, the final / is critical! local res,code = https.request(base_url..currency.."/") if code ~= 200 then return nil end local data = json:decode(res) -- Easy, it's right there text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid -- If we have a number as second parameter, calculate the bitcoin amount if amount~=nil then btc = tonumber(amount) / tonumber(data.ask) text = text.."\n "..currency .." "..amount.." = BTC "..btc end return text end local function run(msg, matches) local cur = 'EUR' local amt = nil -- Get the global match out of the way if matches[1] == "!btc" then return getBTCX(amt,cur) end if matches[2] ~= nil then -- There is a second match amt = matches[2] cur = string.upper(matches[1]) else -- Just a EUR or USD param cur = string.upper(matches[1]) end return getBTCX(amt,cur) end return { description = "Bitcoin global average market value (in EUR or USD)", usage = "!btc [EUR|USD] [amount]", patterns = { "^!btc$", "^!btc ([Ee][Uu][Rr])$", "^!btc ([Uu][Ss][Dd])$", "^!btc (EUR) (%d+[%d%.]*)$", "^!btc (USD) (%d+[%d%.]*)$" }, run = run }
gpl-2.0
alireza85/worstwolfa
plugins/btc.lua
289
1375
-- See https://bitcoinaverage.com/api local function getBTCX(amount,currency) local base_url = 'https://api.bitcoinaverage.com/ticker/global/' -- Do request on bitcoinaverage, the final / is critical! local res,code = https.request(base_url..currency.."/") if code ~= 200 then return nil end local data = json:decode(res) -- Easy, it's right there text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid -- If we have a number as second parameter, calculate the bitcoin amount if amount~=nil then btc = tonumber(amount) / tonumber(data.ask) text = text.."\n "..currency .." "..amount.." = BTC "..btc end return text end local function run(msg, matches) local cur = 'EUR' local amt = nil -- Get the global match out of the way if matches[1] == "!btc" then return getBTCX(amt,cur) end if matches[2] ~= nil then -- There is a second match amt = matches[2] cur = string.upper(matches[1]) else -- Just a EUR or USD param cur = string.upper(matches[1]) end return getBTCX(amt,cur) end return { description = "Bitcoin global average market value (in EUR or USD)", usage = "!btc [EUR|USD] [amount]", patterns = { "^!btc$", "^!btc ([Ee][Uu][Rr])$", "^!btc ([Uu][Ss][Dd])$", "^!btc (EUR) (%d+[%d%.]*)$", "^!btc (USD) (%d+[%d%.]*)$" }, run = run }
gpl-2.0
Cyumus/GarryWare13
gamemode/vgui_clockgame.lua
1
1858
//////////////////////////////////////////////// // // GarryWare Gold // // by Hurricaaane (Ha3) // // and Kilburn_ // // http://www.youtube.com/user/Hurricaaane // //--------------------------------------------// // Gamemode length clock // //////////////////////////////////////////////// PANEL.Base = "DPanel" /*--------------------------------------------------------- Name: gamemode:Init ---------------------------------------------------------*/ function PANEL:Init() self:SetPaintBackground( false ) self.ClockTexPath = "ware/interface/ware_clock_two" self.ClockTexID = surface.GetTextureID( self.ClockTexPath ) self.TrotterTexPath = "ware/interface/ware_trotter" self.TrotterTexID = surface.GetTextureID( self.TrotterTexPath ) --self:SetVisible( true ) self.StartAngle = -15 end /*--------------------------------------------------------- Name: PerformLayout ---------------------------------------------------------*/ function PANEL:PerformLayout() self:SetSize( ScrW(), ScrH() ) self:SetPos( 0, 0 ) end function PANEL:Think() self:InvalidateLayout() end function PANEL:Hide() self:SetVisible( false ) end /*--------------------------------------------------------- Name: PerformLayout ---------------------------------------------------------*/ function PANEL:Paint() surface.SetTexture( self.ClockTexID ) surface.SetDrawColor( 255, 255, 255, 255 ) surface.DrawTexturedRectRotated( ScrW() - 24, ScrH() - 18 , 64, 64, 0 + self.StartAngle ) surface.SetTexture( self.TrotterTexID ) surface.SetDrawColor( 255, 255, 255, 255 ) surface.DrawTexturedRectRotated( ScrW() - 24, ScrH() - 18 , 64, 64, 360 * ((gws_TimeWhenGameEnds - CurTime()) / (GAMEMODE.GameLength * 60)) + 90 + self.StartAngle ) end
gpl-2.0
Arcscion/Shadowlyre
scripts/globals/abilities/animated_flourish.lua
4
2200
----------------------------------- -- Ability: Animated Flourish -- Provokes the target. Requires at least one, but uses two Finishing Moves. -- Obtained: Dancer Level 20 -- Finishing Moves Used: 1-2 -- Recast Time: 00:30 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then return 0,0; else return msgBasic.NO_FINISHINGMOVES,0; end; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then player:delStatusEffect(EFFECT_FINISHING_MOVE_1); --Add extra enmity if 2 finishing moves are used elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then player:delStatusEffect(EFFECT_FINISHING_MOVE_2); target:addEnmity(player, 0, 500); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_3); player:addStatusEffect(EFFECT_FINISHING_MOVE_1,1,0,7200); target:addEnmity(player, 0, 500); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_4); player:addStatusEffect(EFFECT_FINISHING_MOVE_2,1,0,7200); target:addEnmity(player, 0, 500); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_5); player:addStatusEffect(EFFECT_FINISHING_MOVE_3,1,0,7200); target:addEnmity(player, 0, 500); end; end;
gpl-3.0
N0U/Zero-K
gamedata/modularcomms/weapons/lightninggun_improved.lua
4
1261
local name = "commweapon_lightninggun_improved" local weaponDef = { name = [[Heavy Lightning Gun]], areaOfEffect = 8, beamTTL = 12, craterBoost = 0, craterMult = 0, customParams = { extra_damage_mult = 3.125, slot = [[5]], muzzleEffectFire = [[custom:zeus_fire_fx]], light_camera_height = 1600, light_color = [[0.85 0.85 1.2]], light_radius = 220, }, cylinderTargeting = 0, damage = { default = 220, }, explosionGenerator = [[custom:LIGHTNINGPLOSION]], fireStarter = 110, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, intensity = 12, interceptedByShieldType = 1, paralyzeTime = 3, range = 300, reloadtime = 1 + 25/30, rgbColor = [[0.65 0.65 1]], soundStart = [[weapon/more_lightning_fast]], soundTrigger = true, sprayAngle = 500, texture1 = [[lightning]], thickness = 13, turret = true, weaponType = [[LightningCannon]], weaponVelocity = 400, } return name, weaponDef
gpl-2.0
Arcscion/Shadowlyre
scripts/globals/spells/raptor_mazurka.lua
5
1131
----------------------------------------- -- Spell: Raptor Mazurka -- Gives party members enhanced movement ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local power = 12; local iBoost = caster:getMod(MOD_MAZURKA_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then duration = duration * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then duration = duration * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MAZURKA,power,0,duration,caster:getID(), 0, 1)) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end return EFFECT_MAZURKA; end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Promyvion-Holla/MobIDs.lua
2
1740
-- [receptacle] = {group, numStrays, portal} MEMORY_RECEPTACLES = { [16842781] = {1, 3, 16843058}, [16842839] = {2, 5, 16843054}, [16842846] = {2, 5, 16843055}, [16842853] = {2, 5, 16843056}, [16842860] = {2, 5, 16843057}, [16842886] = {3, 7, 16843051}, [16842895] = {3, 7, 16843052}, [16842904] = {3, 7, 16843053}, [16842938] = {4, 7, 16843059}, [16842947] = {4, 7, 16843060}, [16842956] = {4, 7, 16843061}, } -- [memory stream] = {region, {list of events}} MEMORY_STREAMS = { [11] = { 78, -4, 78, 82, 4, 82, {46}}, -- floor 1 return [21] = {-122, -4, -2, -118, 4, 2, {41}}, -- floor 2 return [31] = {-162, -4, 118, -158, 4, 122, {42}}, -- floor 3 return [32] = { 158, -4, 238, 162, 4, 242, {42}}, -- floor 3 return [41] = { 118, -4, -322, 121, 4, -318, {33,34}}, -- floor 4 return [16843058] = { -42, -4, 198, -38, 4, 202, {37}}, -- floor 1 MR1 [16843054] = {-240, -4, 38, -237, 4, 41, {33,34}}, -- floor 2 MR1 [16843055] = {-282, -4, -42, -278, 4, -38, {33,34}}, -- floor 2 MR2 [16843056] = {-162, -4, -202, -157, 4, -198, {33,34}}, -- floor 2 MR3 [16843057] = { -2, -4, -42, 2, 4, -38, {33,34}}, -- floor 2 MR4 [16843051] = {-282, -4, 277, -278, 4, 282, {30}}, -- floor 3 MR1 [16843052] = {-362, -4, 237, -358, 4, 242, {30}}, -- floor 3 MR2 [16843053] = {-362, -4, 118, -358, 4, 122, {30}}, -- floor 3 MR3 [16843059] = { 38, -4, 318, 42, 4, 322, {30}}, -- floor 3 MR4 [16843060] = { 158, -4, 358, 162, 4, 362, {30}}, -- floor 3 MR5 [16843061] = { 278, -4, 197, 282, 4, 202, {30}}, -- floor 3 MR6 }
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Castle_Oztroja/npcs/_47f.lua
3
1232
----------------------------------- -- Area: Castle Oztroja -- NPC: _47f (Handle) -- Notes: Opens door _471 -- !pos -182 -15 -19 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- To be implemented (This is temporary) local DoorID = npc:getID() - 2; local DoorA = GetNPCByID(DoorID):getAnimation(); if (DoorA == 9 and npc:getAnimation() == 9) then npc:openDoor(8); -- Should be a 1 second delay here before the door opens GetNPCByID(DoorID):openDoor(6); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
jono659/enko
scripts/zones/RuLude_Gardens/npcs/relic.lua
41
1848
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: <this space intentionally left blank> -- @pos 0 8 -40 243 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece if (player:getVar("RELIC_IN_PROGRESS") == 18293 and trade:getItemCount() == 4 and trade:hasItemQty(18293,1) and trade:hasItemQty(1576,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1457,1)) then player:startEvent(10035,18294); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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 == 10035) then if (player:getFreeSlotsCount() < 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18294); player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1456); else player:tradeComplete(); player:addItem(18294); player:addItem(1456,30); player:messageSpecial(ITEM_OBTAINED,18294); player:messageSpecial(ITEMS_OBTAINED,1456,30); player:setVar("RELIC_IN_PROGRESS",0); end end end;
gpl-3.0
verath/GuildSkadaHighScore
vendor/Ace3/AceGUI-3.0/widgets/AceGUIWidget-DropDown-Items.lua
13
10576
--[[ $Id: AceGUIWidget-DropDown-Items.lua 1202 2019-05-15 23:11:22Z nevcairiel $ ]]-- local AceGUI = LibStub("AceGUI-3.0") -- Lua APIs local select, assert = select, assert -- WoW APIs local PlaySound = PlaySound local CreateFrame = CreateFrame local function fixlevels(parent,...) local i = 1 local child = select(i, ...) while child do child:SetFrameLevel(parent:GetFrameLevel()+1) fixlevels(child, child:GetChildren()) i = i + 1 child = select(i, ...) end end local function fixstrata(strata, parent, ...) local i = 1 local child = select(i, ...) parent:SetFrameStrata(strata) while child do fixstrata(strata, child, child:GetChildren()) i = i + 1 child = select(i, ...) end end -- ItemBase is the base "class" for all dropdown items. -- Each item has to use ItemBase.Create(widgetType) to -- create an initial 'self' value. -- ItemBase will add common functions and ui event handlers. -- Be sure to keep basic usage when you override functions. local ItemBase = { -- NOTE: The ItemBase version is added to each item's version number -- to ensure proper updates on ItemBase changes. -- Use at least 1000er steps. version = 1000, counter = 0, } function ItemBase.Frame_OnEnter(this) local self = this.obj if self.useHighlight then self.highlight:Show() end self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end end function ItemBase.Frame_OnLeave(this) local self = this.obj self.highlight:Hide() self:Fire("OnLeave") if self.specialOnLeave then self.specialOnLeave(self) end end -- exported, AceGUI callback function ItemBase.OnAcquire(self) self.frame:SetToplevel(true) self.frame:SetFrameStrata("FULLSCREEN_DIALOG") end -- exported, AceGUI callback function ItemBase.OnRelease(self) self:SetDisabled(false) self.pullout = nil self.frame:SetParent(nil) self.frame:ClearAllPoints() self.frame:Hide() end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetPullout(self, pullout) self.pullout = pullout self.frame:SetParent(nil) self.frame:SetParent(pullout.itemFrame) self.parent = pullout.itemFrame fixlevels(pullout.itemFrame, pullout.itemFrame:GetChildren()) end -- exported function ItemBase.SetText(self, text) self.text:SetText(text or "") end -- exported function ItemBase.GetText(self) return self.text:GetText() end -- exported function ItemBase.SetPoint(self, ...) self.frame:SetPoint(...) end -- exported function ItemBase.Show(self) self.frame:Show() end -- exported function ItemBase.Hide(self) self.frame:Hide() end -- exported function ItemBase.SetDisabled(self, disabled) self.disabled = disabled if disabled then self.useHighlight = false self.text:SetTextColor(.5, .5, .5) else self.useHighlight = true self.text:SetTextColor(1, 1, 1) end end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetOnLeave(self, func) self.specialOnLeave = func end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetOnEnter(self, func) self.specialOnEnter = func end function ItemBase.Create(type) -- NOTE: Most of the following code is copied from AceGUI-3.0/Dropdown widget local count = AceGUI:GetNextWidgetNum(type) local frame = CreateFrame("Button", "AceGUI30DropDownItem"..count) local self = {} self.frame = frame frame.obj = self self.type = type self.useHighlight = true frame:SetHeight(17) frame:SetFrameStrata("FULLSCREEN_DIALOG") local text = frame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall") text:SetTextColor(1,1,1) text:SetJustifyH("LEFT") text:SetPoint("TOPLEFT",frame,"TOPLEFT",18,0) text:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-8,0) self.text = text local highlight = frame:CreateTexture(nil, "OVERLAY") highlight:SetTexture(136810) -- Interface\\QuestFrame\\UI-QuestTitleHighlight highlight:SetBlendMode("ADD") highlight:SetHeight(14) highlight:ClearAllPoints() highlight:SetPoint("RIGHT",frame,"RIGHT",-3,0) highlight:SetPoint("LEFT",frame,"LEFT",5,0) highlight:Hide() self.highlight = highlight local check = frame:CreateTexture("OVERLAY") check:SetWidth(16) check:SetHeight(16) check:SetPoint("LEFT",frame,"LEFT",3,-1) check:SetTexture(130751) -- Interface\\Buttons\\UI-CheckBox-Check check:Hide() self.check = check local sub = frame:CreateTexture("OVERLAY") sub:SetWidth(16) sub:SetHeight(16) sub:SetPoint("RIGHT",frame,"RIGHT",-3,-1) sub:SetTexture(130940) -- Interface\\ChatFrame\\ChatFrameExpandArrow sub:Hide() self.sub = sub frame:SetScript("OnEnter", ItemBase.Frame_OnEnter) frame:SetScript("OnLeave", ItemBase.Frame_OnLeave) self.OnAcquire = ItemBase.OnAcquire self.OnRelease = ItemBase.OnRelease self.SetPullout = ItemBase.SetPullout self.GetText = ItemBase.GetText self.SetText = ItemBase.SetText self.SetDisabled = ItemBase.SetDisabled self.SetPoint = ItemBase.SetPoint self.Show = ItemBase.Show self.Hide = ItemBase.Hide self.SetOnLeave = ItemBase.SetOnLeave self.SetOnEnter = ItemBase.SetOnEnter return self end -- Register a dummy LibStub library to retrieve the ItemBase, so other addons can use it. local IBLib = LibStub:NewLibrary("AceGUI-3.0-DropDown-ItemBase", ItemBase.version) if IBLib then IBLib.GetItemBase = function() return ItemBase end end --[[ Template for items: -- Item: -- do local widgetType = "Dropdown-Item-" local widgetVersion = 1 local function Constructor() local self = ItemBase.Create(widgetType) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end --]] -- Item: Header -- A single text entry. -- Special: Different text color and no highlight do local widgetType = "Dropdown-Item-Header" local widgetVersion = 1 local function OnEnter(this) local self = this.obj self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end end local function OnLeave(this) local self = this.obj self:Fire("OnLeave") if self.specialOnLeave then self.specialOnLeave(self) end end -- exported, override local function SetDisabled(self, disabled) ItemBase.SetDisabled(self, disabled) if not disabled then self.text:SetTextColor(1, 1, 0) end end local function Constructor() local self = ItemBase.Create(widgetType) self.SetDisabled = SetDisabled self.frame:SetScript("OnEnter", OnEnter) self.frame:SetScript("OnLeave", OnLeave) self.text:SetTextColor(1, 1, 0) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Execute -- A simple button do local widgetType = "Dropdown-Item-Execute" local widgetVersion = 1 local function Frame_OnClick(this, button) local self = this.obj if self.disabled then return end self:Fire("OnClick") if self.pullout then self.pullout:Close() end end local function Constructor() local self = ItemBase.Create(widgetType) self.frame:SetScript("OnClick", Frame_OnClick) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Toggle -- Some sort of checkbox for dropdown menus. -- Does not close the pullout on click. do local widgetType = "Dropdown-Item-Toggle" local widgetVersion = 4 local function UpdateToggle(self) if self.value then self.check:Show() else self.check:Hide() end end local function OnRelease(self) ItemBase.OnRelease(self) self:SetValue(nil) end local function Frame_OnClick(this, button) local self = this.obj if self.disabled then return end self.value = not self.value if self.value then PlaySound(856) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON else PlaySound(857) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_OFF end UpdateToggle(self) self:Fire("OnValueChanged", self.value) end -- exported local function SetValue(self, value) self.value = value UpdateToggle(self) end -- exported local function GetValue(self) return self.value end local function Constructor() local self = ItemBase.Create(widgetType) self.frame:SetScript("OnClick", Frame_OnClick) self.SetValue = SetValue self.GetValue = GetValue self.OnRelease = OnRelease AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Menu -- Shows a submenu on mouse over -- Does not close the pullout on click do local widgetType = "Dropdown-Item-Menu" local widgetVersion = 2 local function OnEnter(this) local self = this.obj self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end self.highlight:Show() if not self.disabled and self.submenu then self.submenu:Open("TOPLEFT", self.frame, "TOPRIGHT", self.pullout:GetRightBorderWidth(), 0, self.frame:GetFrameLevel() + 100) end end local function OnHide(this) local self = this.obj if self.submenu then self.submenu:Close() end end -- exported local function SetMenu(self, menu) assert(menu.type == "Dropdown-Pullout") self.submenu = menu end -- exported local function CloseMenu(self) self.submenu:Close() end local function Constructor() local self = ItemBase.Create(widgetType) self.sub:Show() self.frame:SetScript("OnEnter", OnEnter) self.frame:SetScript("OnHide", OnHide) self.SetMenu = SetMenu self.CloseMenu = CloseMenu AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Separator -- A single line to separate items do local widgetType = "Dropdown-Item-Separator" local widgetVersion = 2 -- exported, override local function SetDisabled(self, disabled) ItemBase.SetDisabled(self, disabled) self.useHighlight = false end local function Constructor() local self = ItemBase.Create(widgetType) self.SetDisabled = SetDisabled local line = self.frame:CreateTexture(nil, "OVERLAY") line:SetHeight(1) line:SetColorTexture(.5, .5, .5) line:SetPoint("LEFT", self.frame, "LEFT", 10, 0) line:SetPoint("RIGHT", self.frame, "RIGHT", -10, 0) self.text:Hide() self.useHighlight = false AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end
mit
zzh442856860/skynet-Note
service/sharedatad.lua
23
2745
local skynet = require "skynet" local sharedata = require "sharedata.corelib" local table = table local NORET = {} local pool = {} local pool_count = {} local objmap = {} local function newobj(name, tbl) assert(pool[name] == nil) local cobj = sharedata.host.new(tbl) sharedata.host.incref(cobj) local v = { value = tbl , obj = cobj, watch = {} } objmap[cobj] = v pool[name] = v pool_count[name] = { n = 0, threshold = 16 } end local function collectobj() while true do skynet.sleep(600 * 100) -- sleep 10 min collectgarbage() for obj, v in pairs(objmap) do if v == true then if sharedata.host.getref(obj) <= 0 then objmap[obj] = nil sharedata.host.delete(obj) end end end end end local CMD = {} local env_mt = { __index = _ENV } function CMD.new(name, t) local dt = type(t) local value if dt == "table" then value = t elseif dt == "string" then value = setmetatable({}, env_mt) local f = load(t, "=" .. name, "t", value) assert(skynet.pcall(f)) setmetatable(value, nil) elseif dt == "nil" then value = {} else error ("Unknown data type " .. dt) end newobj(name, value) end function CMD.delete(name) local v = assert(pool[name]) pool[name] = nil pool_count[name] = nil assert(objmap[v.obj]) objmap[v.obj] = true sharedata.host.decref(v.obj) for _,response in pairs(v.watch) do response(true) end end function CMD.query(name) local v = assert(pool[name]) local obj = v.obj sharedata.host.incref(obj) return v.obj end function CMD.confirm(cobj) if objmap[cobj] then sharedata.host.decref(cobj) end return NORET end function CMD.update(name, t) local v = pool[name] local watch, oldcobj if v then watch = v.watch oldcobj = v.obj objmap[oldcobj] = true sharedata.host.decref(oldcobj) pool[name] = nil pool_count[name] = nil end CMD.new(name, t) local newobj = pool[name].obj if watch then sharedata.host.markdirty(oldcobj) for _,response in pairs(watch) do response(true, newobj) end end end local function check_watch(queue) local n = 0 for k,response in pairs(queue) do if not response "TEST" then queue[k] = nil n = n + 1 end end return n end function CMD.monitor(name, obj) local v = assert(pool[name]) if obj ~= v.obj then return v.obj end local n = pool_count[name].n pool_count[name].n = n + 1 if n > pool_count[name].threshold then n = n - check_watch(v.watch) pool_count[name].threshold = n * 2 end table.insert(v.watch, skynet.response()) return NORET end skynet.start(function() skynet.fork(collectobj) skynet.dispatch("lua", function (session, source ,cmd, ...) local f = assert(CMD[cmd]) local r = f(...) if r ~= NORET then skynet.ret(skynet.pack(r)) end end) end)
mit
rtsisyk/tarantool
src/box/lua/schema.lua
1
51457
-- schema.lua (internal file) -- local ffi = require('ffi') local msgpack = require('msgpack') local msgpackffi = require('msgpackffi') local fun = require('fun') local log = require('log') local session = box.session local internal = require('box.internal') local builtin = ffi.C -- performance fixup for hot functions local tuple_encode = box.tuple.encode local tuple_bless = box.tuple.bless local is_tuple = box.tuple.is assert(tuple_encode ~= nil and tuple_bless ~= nil and is_tuple ~= nil) ffi.cdef[[ struct space *space_by_id(uint32_t id); void space_run_triggers(struct space *space, bool yesno); size_t space_bsize(struct space *space); typedef struct tuple box_tuple_t; typedef struct iterator box_iterator_t; /** \cond public */ box_iterator_t * box_index_iterator(uint32_t space_id, uint32_t index_id, int type, const char *key, const char *key_end); int box_iterator_next(box_iterator_t *itr, box_tuple_t **result); void box_iterator_free(box_iterator_t *itr); /** \endcond public */ /** \cond public */ ssize_t box_index_len(uint32_t space_id, uint32_t index_id); ssize_t box_index_bsize(uint32_t space_id, uint32_t index_id); int box_index_random(uint32_t space_id, uint32_t index_id, uint32_t rnd, box_tuple_t **result); int box_index_get(uint32_t space_id, uint32_t index_id, const char *key, const char *key_end, box_tuple_t **result); int box_index_min(uint32_t space_id, uint32_t index_id, const char *key, const char *key_end, box_tuple_t **result); int box_index_max(uint32_t space_id, uint32_t index_id, const char *key, const char *key_end, box_tuple_t **result); ssize_t box_index_count(uint32_t space_id, uint32_t index_id, int type, const char *key, const char *key_end); /** \endcond public */ /** \cond public */ int box_txn_begin(); /** \endcond public */ struct port_entry { struct port_entry *next; struct tuple *tuple; }; struct port { size_t size; struct port_entry *first; struct port_entry *last; struct port_entry first_entry; }; void port_create(struct port *port); void port_destroy(struct port *port); int box_select(struct port *port, uint32_t space_id, uint32_t index_id, int iterator, uint32_t offset, uint32_t limit, const char *key, const char *key_end); void password_prepare(const char *password, int len, char *out, int out_len); ]] local function user_or_role_resolve(user) local _user = box.space[box.schema.USER_ID] local tuple if type(user) == 'string' then tuple = _user.index.name:get{user} else tuple = _user:get{user} end if tuple == nil then return nil end return tuple[1] end local function role_resolve(name_or_id) local _user = box.space[box.schema.USER_ID] local tuple if type(name_or_id) == 'string' then tuple = _user.index.name:get{name_or_id} elseif type(name_or_id) ~= 'nil' then tuple = _user:get{name_or_id} end if tuple == nil or tuple[4] ~= 'role' then return nil else return tuple[1] end end local function user_resolve(name_or_id) local _user = box.space[box.schema.USER_ID] local tuple if type(name_or_id) == 'string' then tuple = _user.index.name:get{name_or_id} elseif type(name_or_id) ~= 'nil' then tuple = _user:get{name_or_id} end if tuple == nil or tuple[4] ~= 'user' then return nil else return tuple[1] end end --[[ @brief Common function to check table with parameters (like options) @param table - table with parameters @param template - table with expected types of expected parameters type could be comma separated string with lua types (number, string etc), or 'any' if any type is allowed The function checks following: 1)that parameters table is a table (or nil) 2)all keys in parameters are present in template 3)type of every parameter fits (one of) types described in template Check (2) and (3) could be disabled by adding {, dont_check = <smth is true>, } into parameters table The functions calls box.error(box.error.ILLEGAL_PARAMS, ..) on error @example check_param_table(options, { user = 'string', port = 'string, number', data = 'any'} ) --]] local function check_param_table(table, template) if table == nil then return end if type(table) ~= 'table' then box.error(box.error.ILLEGAL_PARAMS, "options should be a table") end -- just pass {.. dont_check = true, ..} to disable checks below if table.dont_check then return end for k,v in pairs(table) do if template[k] == nil then box.error(box.error.ILLEGAL_PARAMS, "unexpected option '" .. k .. "'") elseif template[k] == 'any' then -- any type is ok elseif (string.find(template[k], ',') == nil) then -- one type if type(v) ~= template[k] then box.error(box.error.ILLEGAL_PARAMS, "options parameter '" .. k .. "' should be of type " .. template[k]) end else local good_types = string.gsub(template[k], ' ', '') local haystack = ',' .. good_types .. ',' local needle = ',' .. type(v) .. ',' if (string.find(haystack, needle) == nil) then good_types = string.gsub(good_types, ',', ', ') box.error(box.error.ILLEGAL_PARAMS, "options parameter '" .. k .. "' should be one of types: " .. template[k]) end end end end --[[ @brief Common function to check type parameter (of function) Calls box.error(box.error.ILLEGAL_PARAMS, ) on error @example: check_param(user, 'user', 'string') --]] local function check_param(param, name, should_be_type) if type(param) ~= should_be_type then box.error(box.error.ILLEGAL_PARAMS, name .. " should be a " .. should_be_type) end end --[[ Adds to a table key-value pairs from defaults table that is not present in original table. Returns updated table. If nil is passed instead of table, it's treated as empty table {} For example update_param_table({ type = 'hash', temporary = true }, { type = 'tree', unique = true }) will return table { type = 'hash', temporary = true, unique = true } --]] local function update_param_table(table, defaults) local new_table = {} if defaults ~= nil then for k,v in pairs(defaults) do new_table[k] = v end end if table ~= nil then for k,v in pairs(table) do new_table[k] = v end end return new_table end box.begin = function() if builtin.box_txn_begin() == -1 then box.error() end end -- box.commit yields, so it's defined as Lua/C binding -- box.rollback yields as well box.schema.space = {} box.schema.space.create = function(name, options) check_param(name, 'name', 'string') local options_template = { if_not_exists = 'boolean', engine = 'string', id = 'number', field_count = 'number', user = 'string, number', format = 'table', temporary = 'boolean', } local options_defaults = { engine = 'memtx', field_count = 0, temporary = false, } check_param_table(options, options_template) options = update_param_table(options, options_defaults) local _space = box.space[box.schema.SPACE_ID] if box.space[name] then if options.if_not_exists then return box.space[name], "not created" else box.error(box.error.SPACE_EXISTS, name) end end local id = options.id if not id then local _schema = box.space._schema local max_id = _schema:update({'max_id'}, {{'+', 2, 1}}) if max_id == nil then id = _space.index.primary:max()[1] if id < box.schema.SYSTEM_ID_MAX then id = box.schema.SYSTEM_ID_MAX end max_id = _schema:insert{'max_id', id + 1} end id = max_id[2] end local uid = nil if options.user then uid = user_or_role_resolve(options.user) end if uid == nil then uid = session.uid() end local format = options.format and options.format or {} -- filter out global parameters from the options array local space_options = setmetatable({ temporary = options.temporary and true or nil, }, { __serialize = 'map' }) _space:insert{id, uid, name, options.engine, options.field_count, space_options, format} return box.space[id], "created" end -- space format - the metadata about space fields function box.schema.space.format(id, format) local _space = box.space._space check_param(id, 'id', 'number') check_param(format, 'format', 'table') if format == nil then return _space:get(id)[7] else _space:update(id, {{'=', 7, format}}) end end box.schema.create_space = box.schema.space.create box.schema.space.drop = function(space_id, space_name, opts) check_param(space_id, 'space_id', 'number') opts = opts or {} check_param_table(opts, { if_exists = 'boolean' }) local _space = box.space[box.schema.SPACE_ID] local _index = box.space[box.schema.INDEX_ID] local _priv = box.space[box.schema.PRIV_ID] local keys = _index:select(space_id) for i = #keys, 1, -1 do local v = keys[i] _index:delete{v[1], v[2]} end local privs = _priv.index.object:select{'space', space_id} for k, tuple in pairs(privs) do box.schema.user.revoke(tuple[2], tuple[5], tuple[3], tuple[4]) end if _space:delete{space_id} == nil then if space_name == nil then space_name = '#'..tostring(space_id) end if not opts.if_exists then box.error(box.error.NO_SUCH_SPACE, space_name) end end end box.schema.space.rename = function(space_id, space_name) check_param(space_id, 'space_id', 'number') check_param(space_name, 'space_name', 'string') local _space = box.space[box.schema.SPACE_ID] _space:update(space_id, {{"=", 3, space_name}}) end box.schema.index = {} local function check_index_parts(parts) if type(parts) ~= "table" then box.error(box.error.ILLEGAL_PARAMS, "options.parts parameter should be a table") end if #parts % 2 ~= 0 then box.error(box.error.ILLEGAL_PARAMS, "options.parts: expected field_no (number), type (string) pairs") end for i=1,#parts,2 do if type(parts[i]) ~= "number" then box.error(box.error.ILLEGAL_PARAMS, "options.parts: expected field_no (number), type (string) pairs") elseif parts[i] == 0 then -- Lua uses one-based field numbers but _space is zero-based box.error(box.error.ILLEGAL_PARAMS, "invalid index parts: field_no must be one-based") end end for i=2,#parts,2 do if type(parts[i]) ~= "string" then box.error(box.error.ILLEGAL_PARAMS, "options.parts: expected field_no (number), type (string) pairs") end end end local function update_index_parts(parts) local new_parts = {} for i=1,#parts do -- Lua uses one-based field numbers but _space is zero-based if i % 2 == 1 then new_parts[i] = parts[i] - 1 else new_parts[i] = parts[i] end end return new_parts end box.schema.index.create = function(space_id, name, options) check_param(space_id, 'space_id', 'number') check_param(name, 'name', 'string') local options_template = { type = 'string', parts = 'table', unique = 'boolean', id = 'number', if_not_exists = 'boolean', dimension = 'number', distance = 'string', path = 'string', page_size = 'number', range_size = 'number', run_count_per_level = 'number', run_size_ratio = 'number', } check_param_table(options, options_template) local options_defaults = { type = 'tree', } options = update_param_table(options, options_defaults) local type_dependent_defaults = { rtree = {parts = { 2, 'array' }, unique = false}, bitset = {parts = { 2, 'unsigned' }, unique = false}, other = {parts = { 1, 'unsigned' }, unique = true}, } options_defaults = type_dependent_defaults[options.type] and type_dependent_defaults[options.type] or type_dependent_defaults.other options = update_param_table(options, options_defaults) if box.space[space_id] ~= nil and box.space[space_id].engine == 'vinyl' then options_defaults = { -- path has no default, or, rather, it defaults -- to a subdirectory of the server data dir if it is not set page_size = box.cfg.vinyl_page_size, range_size = box.cfg.vinyl_range_size, run_count_per_level = box.cfg.vinyl_run_count_per_level, run_size_ratio = box.cfg.vinyl_run_size_ratio, } else options_defaults = {} end options = update_param_table(options, options_defaults) check_index_parts(options.parts) options.parts = update_index_parts(options.parts) local _index = box.space[box.schema.INDEX_ID] if _index.index.name:get{space_id, name} then if options.if_not_exists then return box.space[space_id].index[name], "not created" else box.error(box.error.INDEX_EXISTS, name) end end local iid = 0 if options.id then iid = options.id else -- max local tuple = _index.index[0] :select(space_id, { limit = 1, iterator = 'LE' })[1] if tuple then local id = tuple[1] if id == space_id then iid = tuple[2] + 1 end end end local parts = {} for i = 1, #options.parts, 2 do table.insert(parts, {options.parts[i], options.parts[i + 1]}) end -- create_index() options contains type, parts, etc, -- stored separately. Remove these members from index_opts local index_opts = { dimension = options.dimension, unique = options.unique, distance = options.distance, path = options.path, page_size = options.page_size, range_size = options.range_size, run_count_per_level = options.run_count_per_level, run_size_ratio = options.run_size_ratio, lsn = box.info.cluster.signature, } local field_type_aliases = { num = 'unsigned'; -- Deprecated since 1.7.2 uint = 'unsigned'; str = 'string'; int = 'integer'; }; for _, part in pairs(parts) do local field_type = part[2]:lower() part[2] = field_type_aliases[field_type] or field_type if field_type == 'num' then log.warn("field type '%s' is deprecated since Tarantool 1.7, ".. "please use '%s' instead", field_type, part[2]) end end _index:insert{space_id, iid, name, options.type, index_opts, parts} return box.space[space_id].index[name] end box.schema.index.drop = function(space_id, index_id) check_param(space_id, 'space_id', 'number') check_param(index_id, 'index_id', 'number') local _index = box.space[box.schema.INDEX_ID] _index:delete{space_id, index_id} end box.schema.index.rename = function(space_id, index_id, name) check_param(space_id, 'space_id', 'number') check_param(index_id, 'index_id', 'number') check_param(name, 'name', 'string') local _index = box.space[box.schema.INDEX_ID] _index:update({space_id, index_id}, {{"=", 3, name}}) end box.schema.index.alter = function(space_id, index_id, options) if box.space[space_id] == nil then box.error(box.error.NO_SUCH_SPACE, '#'..tostring(space_id)) end if box.space[space_id].engine == 'vinyl' then box.error(box.error.VINYL, 'alter is not supported for a Vinyl index') end if box.space[space_id].index[index_id] == nil then box.error(box.error.NO_SUCH_INDEX, index_id, box.space[space_id].name) end if options == nil then return end local options_template = { id = 'number', name = 'string', type = 'string', parts = 'table', unique = 'boolean', dimension = 'number', distance = 'string', } check_param_table(options, options_template) if type(space_id) ~= "number" then space_id = box.space[space_id].id end if type(index_id) ~= "number" then index_id = box.space[space_id].index[index_id].id end local _index = box.space[box.schema.INDEX_ID] if options.id ~= nil then local can_update_field = {id = true, name = true, type = true } local can_update = true local cant_update_fields = '' for k,v in pairs(options) do if not can_update_field[k] then can_update = false cant_update_fields = cant_update_fields .. ' ' .. k end end if not can_update then box.error(box.error.PROC_LUA, "Don't know how to update both id and" .. cant_update_fields) end local ops = {} local function add_op(value, field_no) if value then table.insert(ops, {'=', field_no, value}) end end add_op(options.id, 2) add_op(options.name, 3) add_op(options.type, 4) _index:update({space_id, index_id}, ops) return end local tuple = _index:get{space_id, index_id } local parts = {} local index_opts = {} local OPTS = 5 local PARTS = 6 if type(tuple[OPTS]) == 'number' then -- old format index_opts.unique = tuple[OPTS] == 1 local part_count = tuple[PARTS] for i = 1, part_count do table.insert(parts, {tuple[2 * i + 4], tuple[2 * i + 5]}); end else -- new format index_opts = tuple[OPTS] parts = tuple[PARTS] end if options.name == nil then options.name = tuple[3] end if options.type == nil then options.type = tuple[4] end if options.unique ~= nil then index_opts.unique = options.unique and true or false end if options.dimension ~= nil then index_opts.dimension = options.dimension end if options.distance ~= nil then index_opts.distance = options.distance end if options.parts ~= nil then check_index_parts(options.parts) options.parts = update_index_parts(options.parts) parts = {} for i = 1, #options.parts, 2 do table.insert(parts, {options.parts[i], options.parts[i + 1]}) end end _index:replace{space_id, index_id, options.name, options.type, index_opts, parts} end -- a static box_tuple_t ** instance for calling box_index_* API local ptuple = ffi.new('box_tuple_t *[1]') local function keify(key) if key == nil then return {} elseif type(key) == "table" or is_tuple(key) then return key end return {key} end local iterator_t = ffi.typeof('struct iterator') ffi.metatype(iterator_t, { __tostring = function(iterator) return "<iterator state>" end; }) local iterator_gen = function(param, state) --[[ index:pairs() mostly conforms to the Lua for-in loop conventions and tries to follow the best practices of Lua community. - this generating function is stateless. - *param* should contain **immutable** data needed to fully define an iterator. *param* is opaque for users. Currently it contains keybuf string just to prevent GC from collecting it. In future some other variables like space_id, index_id, sc_version will be stored here. - *state* should contain **immutable** transient state of an iterator. *state* is opaque for users. Currently it contains `struct iterator` cdata that is modified during iteration. This is a sad limitation of underlying C API. Moreover, the separation of *param* and *state* is not properly implemented here. These drawbacks can be fixed in future without changing this API. Please check out http://www.lua.org/pil/7.3.html for details. --]] if not ffi.istype(iterator_t, state) then error('usage: next(param, state)') end -- next() modifies state in-place if builtin.box_iterator_next(state, ptuple) ~= 0 then return box.error() -- error elseif ptuple[0] ~= nil then return state, tuple_bless(ptuple[0]) -- new state, value else return nil end end local iterator_gen_luac = function(param, state) local tuple = internal.iterator_next(state) if tuple ~= nil then return state, tuple -- new state, value else return nil end end -- global struct port instance to use by select()/get() local port = ffi.new('struct port') local port_entry_t = ffi.typeof('struct port_entry') -- Helper function to check space:method() usage local function check_space_arg(space, method) if type(space) ~= 'table' or space.id == nil then local fmt = 'Use space:%s(...) instead of space.%s(...)' error(string.format(fmt, method, method)) end end box.internal.check_space_arg = check_space_arg -- for net.box -- Helper function for nicer error messages -- in some cases when space object is misused -- Takes time so should not be used for DML. local function check_space_exists(space) local s = box.space[space.id] if s == nil then box.error(box.error.NO_SUCH_SPACE, space.name) end end -- Helper function to check index:method() usage local function check_index_arg(index, method) if type(index) ~= 'table' or index.id == nil then local fmt = 'Use index:%s(...) instead of index.%s(...)' error(string.format(fmt, method, method)) end end box.internal.check_index_arg = check_index_arg -- for net.box -- Helper function to check that space have primary key and return it local function check_primary_index(space) local pk = space.index[0] if pk == nil then box.error(box.error.NO_SUCH_INDEX, 0, space.name) end return pk end box.internal.check_primary_index = check_primary_index -- for net.box local function check_iterator_type(opts, key_is_nil) local itype if opts and opts.iterator then if type(opts.iterator) == "number" then itype = opts.iterator elseif type(opts.iterator) == "string" then itype = box.index[string.upper(opts.iterator)] if itype == nil then box.error(box.error.ITERATOR_TYPE, opts.iterator) end else box.error(box.error.ITERATOR_TYPE, tostring(opts.iterator)) end elseif opts and type(opts) == "string" then itype = box.index[string.upper(opts)] if itype == nil then box.error(box.error.ITERATOR_TYPE, opts) end else -- Use ALL for {} and nil keys and EQ for other keys itype = key_is_nil and box.index.ALL or box.index.EQ end return itype end internal.check_iterator_type = check_iterator_type -- export for net.box function box.schema.space.bless(space) local index_mt = {} -- __len and __index index_mt.len = function(index) check_index_arg(index, 'len') local ret = builtin.box_index_len(index.space_id, index.id) if ret == -1 then box.error() end return tonumber(ret) end -- index.bsize index_mt.bsize = function(index) check_index_arg(index, 'bsize') local ret = builtin.box_index_bsize(index.space_id, index.id) if ret == -1 then box.error() end return tonumber(ret) end index_mt.__len = index_mt.len -- Lua 5.2 compatibility index_mt.__newindex = function(table, index) return error('Attempt to modify a read-only table') end index_mt.__index = index_mt -- min and max index_mt.min_ffi = function(index, key) check_index_arg(index, 'min') local pkey, pkey_end = tuple_encode(key) if builtin.box_index_min(index.space_id, index.id, pkey, pkey_end, ptuple) ~= 0 then box.error() -- error elseif ptuple[0] ~= nil then return tuple_bless(ptuple[0]) else return end end index_mt.min_luac = function(index, key) check_index_arg(index, 'min') key = keify(key) return internal.min(index.space_id, index.id, key); end index_mt.max_ffi = function(index, key) check_index_arg(index, 'max') local pkey, pkey_end = tuple_encode(key) if builtin.box_index_max(index.space_id, index.id, pkey, pkey_end, ptuple) ~= 0 then box.error() -- error elseif ptuple[0] ~= nil then return tuple_bless(ptuple[0]) else return end end index_mt.max_luac = function(index, key) check_index_arg(index, 'max') key = keify(key) return internal.max(index.space_id, index.id, key); end index_mt.random_ffi = function(index, rnd) check_index_arg(index, 'random') rnd = rnd or math.random() if builtin.box_index_random(index.space_id, index.id, rnd, ptuple) ~= 0 then box.error() -- error elseif ptuple[0] ~= nil then return tuple_bless(ptuple[0]) else return end end index_mt.random_luac = function(index, rnd) check_index_arg(index, 'random') rnd = rnd or math.random() return internal.random(index.space_id, index.id, rnd); end -- iteration index_mt.pairs_ffi = function(index, key, opts) check_index_arg(index, 'pairs') local pkey, pkey_end = tuple_encode(key) local itype = check_iterator_type(opts, pkey + 1 >= pkey_end); local keybuf = ffi.string(pkey, pkey_end - pkey) local pkeybuf = ffi.cast('const char *', keybuf) local cdata = builtin.box_index_iterator(index.space_id, index.id, itype, pkeybuf, pkeybuf + #keybuf); if cdata == nil then box.error() end return fun.wrap(iterator_gen, keybuf, ffi.gc(cdata, builtin.box_iterator_free)) end index_mt.pairs_luac = function(index, key, opts) check_index_arg(index, 'pairs') key = keify(key) local itype = check_iterator_type(opts, #key == 0); local keymp = msgpack.encode(key) local keybuf = ffi.string(keymp, #keymp) local cdata = internal.iterator(index.space_id, index.id, itype, keymp); return fun.wrap(iterator_gen_luac, keybuf, ffi.gc(cdata, builtin.box_iterator_free)) end -- index subtree size index_mt.count_ffi = function(index, key, opts) check_index_arg(index, 'count') local pkey, pkey_end = tuple_encode(key) local itype = check_iterator_type(opts, pkey + 1 >= pkey_end); local count = builtin.box_index_count(index.space_id, index.id, itype, pkey, pkey_end); if count == -1 then box.error() end return tonumber(count) end index_mt.count_luac = function(index, key, opts) check_index_arg(index, 'count') key = keify(key) local itype = check_iterator_type(opts, #key == 0); return internal.count(index.space_id, index.id, itype, key); end index_mt.get_ffi = function(index, key) check_index_arg(index, 'get') local key, key_end = tuple_encode(key) if builtin.box_index_get(index.space_id, index.id, key, key_end, ptuple) ~= 0 then return box.error() -- error elseif ptuple[0] ~= nil then return tuple_bless(ptuple[0]) else return end end index_mt.get_luac = function(index, key) check_index_arg(index, 'get') key = keify(key) return internal.get(index.space_id, index.id, key) end local function check_select_opts(opts, key_is_nil) local offset = 0 local limit = 4294967295 local iterator = check_iterator_type(opts, key_is_nil) if opts ~= nil then if opts.offset ~= nil then offset = opts.offset end if opts.limit ~= nil then limit = opts.limit end end return iterator, offset, limit end index_mt.select_ffi = function(index, key, opts) check_index_arg(index, 'select') local key, key_end = tuple_encode(key) local iterator, offset, limit = check_select_opts(opts, key + 1 >= key_end) builtin.port_create(port) if builtin.box_select(port, index.space_id, index.id, iterator, offset, limit, key, key_end) ~=0 then builtin.port_destroy(port); return box.error() end local ret = {} local entry = port.first for i=1,tonumber(port.size),1 do ret[i] = tuple_bless(entry.tuple) entry = entry.next end builtin.port_destroy(port); return ret end index_mt.select_luac = function(index, key, opts) check_index_arg(index, 'select') local key = keify(key) local iterator, offset, limit = check_select_opts(opts, #key == 0) return internal.select(index.space_id, index.id, iterator, offset, limit, key) end index_mt.update = function(index, key, ops) check_index_arg(index, 'update') return internal.update(index.space_id, index.id, keify(key), ops); end index_mt.delete = function(index, key) check_index_arg(index, 'delete') return internal.delete(index.space_id, index.id, keify(key)); end index_mt.drop = function(index) check_index_arg(index, 'drop') return box.schema.index.drop(index.space_id, index.id) end index_mt.rename = function(index, name) check_index_arg(index, 'rename') return box.schema.index.rename(index.space_id, index.id, name) end index_mt.alter = function(index, options) check_index_arg(index, 'alter') if index.id == nil or index.space_id == nil then box.error(box.error.PROC_LUA, "Usage: index:alter{opts}") end return box.schema.index.alter(index.space_id, index.id, options) end -- true if reading operations may yield local read_yields = space.engine == 'vinyl' local read_ops = {'select', 'get', 'min', 'max', 'count', 'random', 'pairs'} for _, op in ipairs(read_ops) do if read_yields then -- use Lua/C implmenetation index_mt[op] = index_mt[op .. "_luac"] else -- use FFI implementation index_mt[op] = index_mt[op .. "_ffi"] end end index_mt.__pairs = index_mt.pairs -- Lua 5.2 compatibility index_mt.__ipairs = index_mt.pairs -- Lua 5.2 compatibility -- local space_mt = {} space_mt.len = function(space) check_space_arg(space, 'len') local pk = space.index[0] if pk == nil then return 0 -- empty space without indexes, return 0 end return space.index[0]:len() end space_mt.count = function(space, key, opts) check_space_arg(space, 'count') local pk = space.index[0] if pk == nil then return 0 -- empty space without indexes, return 0 end return pk:count(key, opts) end space_mt.bsize = function(space) check_space_arg(space, 'bsize') local s = builtin.space_by_id(space.id) if s == nil then box.error(box.error.NO_SUCH_SPACE, space.name) end return builtin.space_bsize(s) end space_mt.__newindex = index_mt.__newindex space_mt.get = function(space, key) check_space_arg(space, 'get') return check_primary_index(space):get(key) end space_mt.select = function(space, key, opts) check_space_arg(space, 'select') return check_primary_index(space):select(key, opts) end space_mt.insert = function(space, tuple) check_space_arg(space, 'insert') return internal.insert(space.id, tuple); end space_mt.replace = function(space, tuple) check_space_arg(space, 'replace') return internal.replace(space.id, tuple); end space_mt.put = space_mt.replace; -- put is an alias for replace space_mt.update = function(space, key, ops) check_space_arg(space, 'update') return check_primary_index(space):update(key, ops) end space_mt.upsert = function(space, tuple_key, ops, deprecated) check_space_arg(space, 'upsert') if deprecated ~= nil then local msg = "Error: extra argument in upsert call: " msg = msg .. tostring(deprecated) msg = msg .. ". Usage :upsert(tuple, operations)" box.error(box.error.PROC_LUA, msg) end return internal.upsert(space.id, tuple_key, ops); end space_mt.delete = function(space, key) check_space_arg(space, 'delete') return check_primary_index(space):delete(key) end -- Assumes that spaceno has a TREE (NUM) primary key -- inserts a tuple after getting the next value of the -- primary key and returns it back to the user space_mt.auto_increment = function(space, tuple) check_space_arg(space, 'auto_increment') local max_tuple = check_primary_index(space):max() local max = 0 if max_tuple ~= nil then max = max_tuple[1] end table.insert(tuple, 1, max + 1) return space:insert(tuple) end space_mt.pairs = function(space, key, opts) check_space_arg(space, 'pairs') local pk = space.index[0] if pk == nil then -- empty space without indexes, return empty iterator return fun.iter({}) end return pk:pairs(key, opts) end space_mt.__pairs = space_mt.pairs -- Lua 5.2 compatibility space_mt.__ipairs = space_mt.pairs -- Lua 5.2 compatibility space_mt.truncate = function(space) check_space_arg(space, 'truncate') return internal.truncate(space.id) end space_mt.format = function(space, format) check_space_arg(space, 'format') return box.schema.space.format(space.id, format) end space_mt.drop = function(space) check_space_arg(space, 'drop') check_space_exists(space) return box.schema.space.drop(space.id, space.name) end space_mt.rename = function(space, name) check_space_arg(space, 'rename') check_space_exists(space) return box.schema.space.rename(space.id, name) end space_mt.create_index = function(space, name, options) check_space_arg(space, 'create_index') check_space_exists(space) return box.schema.index.create(space.id, name, options) end space_mt.run_triggers = function(space, yesno) check_space_arg(space, 'run_triggers') local s = builtin.space_by_id(space.id) if s == nil then box.error(box.error.NO_SUCH_SPACE, space.name) end builtin.space_run_triggers(s, yesno) end space_mt.__index = space_mt setmetatable(space, space_mt) if type(space.index) == 'table' and space.enabled then for j, index in pairs(space.index) do if type(j) == 'number' then setmetatable(index, index_mt) end end end end local function privilege_resolve(privilege) local numeric = 0 if type(privilege) == 'string' then privilege = string.lower(privilege) if string.find(privilege, 'read') then numeric = numeric + 1 end if string.find(privilege, 'write') then numeric = numeric + 2 end if string.find(privilege, 'execute') then numeric = numeric + 4 end else numeric = privilege end return numeric end local function checked_privilege(privilege, object_type) local priv_hex = privilege_resolve(privilege) if object_type == 'role' and priv_hex ~= 4 then box.error(box.error.UNSUPPORTED_ROLE_PRIV, privilege) end return priv_hex end local function privilege_name(privilege) local names = {} if bit.band(privilege, 1) ~= 0 then table.insert(names, "read") end if bit.band(privilege, 2) ~= 0 then table.insert(names, "write") end if bit.band(privilege, 4) ~= 0 then table.insert(names, "execute") end return table.concat(names, ",") end local function object_resolve(object_type, object_name) if object_type == 'universe' then return 0 end if object_type == 'space' then local space = box.space[object_name] if space == nil then box.error(box.error.NO_SUCH_SPACE, object_name) end return space.id end if object_type == 'function' then local _func = box.space[box.schema.FUNC_ID] local func if type(object_name) == 'string' then func = _func.index.name:get{object_name} else func = _func:get{object_name} end if func then return func[1] else box.error(box.error.NO_SUCH_FUNCTION, object_name) end end if object_type == 'role' then local _user = box.space[box.schema.USER_ID] local role if type(object_name) == 'string' then role = _user.index.name:get{object_name} else role = _user:get{object_name} end if role and role[4] == 'role' then return role[1] else box.error(box.error.NO_SUCH_ROLE, object_name) end end box.error(box.error.UNKNOWN_SCHEMA_OBJECT, object_type) end local function object_name(object_type, object_id) if object_type == 'universe' then return "" end local space if object_type == 'space' then space = box.space._space elseif object_type == 'function' then space = box.space._func elseif object_type == 'role' or object_type == 'user' then space = box.space._user else box.error(box.error.UNKNOWN_SCHEMA_OBJECT, object_type) end return space:get{object_id}[3] end box.schema.func = {} box.schema.func.create = function(name, opts) opts = opts or {} check_param_table(opts, { setuid = 'boolean', if_not_exists = 'boolean', language = 'string'}) local _func = box.space[box.schema.FUNC_ID] local func = _func.index.name:get{name} if func then if not opts.if_not_exists then box.error(box.error.FUNCTION_EXISTS, name) end return end opts = update_param_table(opts, { setuid = false, language = 'lua'}) opts.language = string.upper(opts.language) opts.setuid = opts.setuid and 1 or 0 _func:auto_increment{session.uid(), name, opts.setuid, opts.language} end box.schema.func.drop = function(name, opts) opts = opts or {} check_param_table(opts, { if_exists = 'boolean' }) local _func = box.space[box.schema.FUNC_ID] local _priv = box.space[box.schema.PRIV_ID] local fid local tuple if type(name) == 'string' then tuple = _func.index.name:get{name} else tuple = _func:get{name} end if tuple then fid = tuple[1] end if fid == nil then if not opts.if_exists then box.error(box.error.NO_SUCH_FUNCTION, name) end return end local privs = _priv.index.object:select{'function', fid} for k, tuple in pairs(privs) do box.schema.user.revoke(tuple[2], tuple[5], tuple[3], tuple[4]) end _func:delete{fid} end function box.schema.func.exists(name_or_id) local _func = box.space[box.schema.FUNC_ID] local tuple = nil if type(name_or_id) == 'string' then tuple = _func.index.name:get{name_or_id} elseif type(name_or_id) == 'number' then tuple = _func:get{name_or_id} end return tuple ~= nil end box.schema.user = {} box.schema.user.password = function(password) local BUF_SIZE = 128 local buf = ffi.new("char[?]", BUF_SIZE) builtin.password_prepare(password, #password, buf, BUF_SIZE) return ffi.string(buf) end local function chpasswd(uid, new_password) local _user = box.space[box.schema.USER_ID] local auth_mech_list = {} auth_mech_list["chap-sha1"] = box.schema.user.password(new_password) _user:update({uid}, {{"=", 5, auth_mech_list}}) end box.schema.user.passwd = function(name, new_password) if name == nil then box.error(box.error.PROC_LUA, "Usage: box.schema.user.passwd([user,] password)") end if new_password == nil then -- change password for current user new_password = name box.session.su('admin', chpasswd, session.uid(), new_password) else -- change password for other user local uid = user_resolve(name) if uid == nil then box.error(box.error.NO_SUCH_USER, name) end return chpasswd(uid, new_password) end end box.schema.user.create = function(name, opts) local uid = user_or_role_resolve(name) opts = opts or {} check_param_table(opts, { password = 'string', if_not_exists = 'boolean' }) if uid then if not opts.if_not_exists then box.error(box.error.USER_EXISTS, name) end return end local auth_mech_list = {} if opts.password then auth_mech_list["chap-sha1"] = box.schema.user.password(opts.password) end local _user = box.space[box.schema.USER_ID] uid = _user:auto_increment{session.uid(), name, 'user', auth_mech_list}[1] -- grant role 'public' to the user box.schema.user.grant(uid, 'public') end box.schema.user.exists = function(name) if user_resolve(name) then return true else return false end end local function grant(uid, name, privilege, object_type, object_name, options) -- From user point of view, role is the same thing -- as a privilege. Allow syntax grant(user, role). if object_name == nil and object_type == nil then -- sic: avoid recursion, to not bother with roles -- named 'execute' object_type = 'role' object_name = privilege privilege = 'execute' end local privilege_hex = checked_privilege(privilege, object_type) local oid = object_resolve(object_type, object_name) options = options or {} if options.grantor == nil then options.grantor = session.uid() else options.grantor = user_or_role_resolve(options.grantor) end local _priv = box.space[box.schema.PRIV_ID] -- add the granted privilege to the current set local tuple = _priv:get{uid, object_type, oid} local old_privilege if tuple ~= nil then old_privilege = tuple[5] else old_privilege = 0 end privilege_hex = bit.bor(privilege_hex, old_privilege) -- do not execute a replace if it does not change anything -- XXX bug if we decide to add a grant option: new grantor -- replaces the old one, old grantor is lost if privilege_hex ~= old_privilege then _priv:replace{options.grantor, uid, object_type, oid, privilege_hex} elseif not options.if_not_exists then if object_type == 'role' then box.error(box.error.ROLE_GRANTED, name, object_name) else box.error(box.error.PRIV_GRANTED, name, privilege, object_type, object_name) end end end local function revoke(uid, name, privilege, object_type, object_name, options) -- From user point of view, role is the same thing -- as a privilege. Allow syntax revoke(user, role). if object_name == nil and object_type == nil then object_type = 'role' object_name = privilege privilege = 'execute' end local privilege_hex = checked_privilege(privilege, object_type) options = options or {} local oid = object_resolve(object_type, object_name) local _priv = box.space[box.schema.PRIV_ID] local tuple = _priv:get{uid, object_type, oid} if tuple == nil then if options.if_exists then return end if object_type == 'role' then box.error(box.error.ROLE_NOT_GRANTED, name, object_name) else box.error(box.error.PRIV_NOT_GRANTED, name, privilege, object_type, object_name) end end local old_privilege = tuple[5] local grantor = tuple[1] -- sic: -- a user may revoke more than he/she granted -- (erroneous user input) -- privilege_hex = bit.band(old_privilege, bit.bnot(privilege_hex)) if privilege_hex ~= 0 then _priv:replace{grantor, uid, object_type, oid, privilege_hex} else _priv:delete{uid, object_type, oid} end end local function drop(uid, opts) -- recursive delete of user data local _priv = box.space[box.schema.PRIV_ID] local privs = _priv.index.primary:select{uid} for k, tuple in pairs(privs) do revoke(uid, uid, tuple[5], tuple[3], tuple[4]) end local spaces = box.space[box.schema.SPACE_ID].index.owner:select{uid} for k, tuple in pairs(spaces) do box.space[tuple[1]]:drop() end local funcs = box.space[box.schema.FUNC_ID].index.owner:select{uid} for k, tuple in pairs(funcs) do box.schema.func.drop(tuple[1]) end -- if this is a role, revoke this role from whoever it was granted to local grants = _priv.index.object:select{'role', uid} for k, tuple in pairs(grants) do revoke(tuple[2], tuple[2], uid) end box.space[box.schema.USER_ID]:delete{uid} end box.schema.user.grant = function(user_name, ...) local uid = user_resolve(user_name) if uid == nil then box.error(box.error.NO_SUCH_USER, user_name) end return grant(uid, user_name, ...) end box.schema.user.revoke = function(user_name, ...) local uid = user_resolve(user_name) if uid == nil then box.error(box.error.NO_SUCH_USER, user_name) end return revoke(uid, user_name, ...) end box.schema.user.drop = function(name, opts) opts = opts or {} check_param_table(opts, { if_exists = 'boolean' }) local uid = user_resolve(name) if uid ~= nil then if uid >= box.schema.SYSTEM_USER_ID_MIN and uid <= box.schema.SYSTEM_USER_ID_MAX then -- gh-1205: box.schema.user.info fails box.error(box.error.DROP_USER, name, "the user or the role is a system") end return drop(uid, opts) end if not opts.if_exists then box.error(box.error.NO_SUCH_USER, name) end return end local function info(id) local _priv = box.space._priv local _user = box.space._priv local privs = {} for _, v in pairs(_priv:select{id}) do table.insert( privs, {privilege_name(v[5]), v[3], object_name(v[3], v[4])} ) end return privs end box.schema.user.info = function(user_name) local uid if user_name == nil then uid = box.session.uid() else uid = user_resolve(user_name) if uid == nil then box.error(box.error.NO_SUCH_USER, user_name) end end return info(uid) end box.schema.role = {} box.schema.role.exists = function(name) if role_resolve(name) then return true else return false end end box.schema.role.create = function(name, opts) opts = opts or {} check_param_table(opts, { if_not_exists = 'boolean' }) local uid = user_or_role_resolve(name) if uid then if not opts.if_not_exists then box.error(box.error.ROLE_EXISTS, name) end return end local _user = box.space[box.schema.USER_ID] _user:auto_increment{session.uid(), name, 'role'} end box.schema.role.drop = function(name, opts) opts = opts or {} check_param_table(opts, { if_exists = 'boolean' }) local uid = role_resolve(name) if uid == nil then if not opts.if_exists then box.error(box.error.NO_SUCH_ROLE, name) end return end if uid >= box.schema.SYSTEM_USER_ID_MIN and uid <= box.schema.SYSTEM_USER_ID_MAX then -- gh-1205: box.schema.user.info fails box.error(box.error.DROP_USER, name, "the user or the role is a system") end return drop(uid) end box.schema.role.grant = function(user_name, ...) local uid = role_resolve(user_name) if uid == nil then box.error(box.error.NO_SUCH_ROLE, user_name) end return grant(uid, user_name, ...) end box.schema.role.revoke = function(user_name, ...) local uid = role_resolve(user_name) if uid == nil then box.error(box.error.NO_SUCH_ROLE, user_name) end return revoke(uid, user_name, ...) end box.schema.role.info = function(role_name) local rid = role_resolve(role_name) if rid == nil then box.error(box.error.NO_SUCH_ROLE, role_name) end return info(rid) end -- -- once -- box.once = function(key, func, ...) if type(key) ~= 'string' or type(func) ~= 'function' then box.error(box.error.ILLEGAL_PARAMS, "Usage: box.once(key, func, ...)") end local key = "once"..key if box.space._schema:get{key} ~= nil then return end box.space._schema:put{key} return func(...) end -- -- nice output when typing box.space in admin console -- box.space = {} local function box_space_mt(tab) local t = {} for k,v in pairs(tab) do -- skip system spaces and views if type(k) == 'string' and #k > 0 and k:sub(1,1) ~= '_' then t[k] = { engine = v.engine, temporary = v.temporary } end end return t end setmetatable(box.space, { __serialize = box_space_mt })
bsd-2-clause
jono659/enko
scripts/globals/items/earth_wand.lua
16
1034
----------------------------------------- -- ID: 17076 -- Item: Earth Wand -- Additional Effect: Earth Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(6,20); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_EARTH, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_EARTH,0); dmg = adjustForTarget(target,dmg,ELE_EARTH); dmg = finalMagicNonSpellAdjustments(player,target,ELE_EARTH,dmg); local message = 163; if (dmg < 0) then message = 167; end return SUBEFFECT_EARTH_DAMAGE,message,dmg; end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Upper_Jeuno/npcs/Champalpieu.lua
17
1243
----------------------------------- -- Area: Upper Jeuno -- NPC: Champalpieu -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CHAMPALPIEU_SHOP_DIALOG); stock = {0x110D,120, --Rolanberry 0x43A8,7, --Iron Arrow 0x43B8,5, --Crossbow Bolt 0x025D,180, --Pickaxe 0x13C8,567, --Wind Threnody 0x13CB,420} --Water Threnody showShop(player, STATIC, 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
Arcscion/Shadowlyre
scripts/zones/Eastern_Altepa_Desert/npcs/Telepoint.lua
17
1706
----------------------------------- -- Area: Eastern Altepa Desert -- NPC: Telepoint ----------------------------------- package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Eastern_Altepa_Desert/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) item = trade:getItemId(); if (trade:getItemCount() == 1 and item > 4095 and item < 4104) then if (player:getFreeSlotsCount() > 0 and player:hasItem(613) == false) then player:tradeComplete(); player:addItem(613); player:messageSpecial(ITEM_OBTAINED,613); -- Faded Crystal else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,613); -- Faded Crystal end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(ALTEPA_GATE_CRYSTAL) == false) then player:addKeyItem(ALTEPA_GATE_CRYSTAL); player:messageSpecial(KEYITEM_OBTAINED,ALTEPA_GATE_CRYSTAL); else player:messageSpecial(ALREADY_OBTAINED_TELE); 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
davidedmonds/darkstar
scripts/zones/Northern_San_dOria/npcs/Madaline.lua
36
1615
----------------------------------- -- Area: Northern San d'Oria -- NPC: Madaline -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); 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) Telmoda_Madaline = player:getVar("Telmoda_Madaline_Event"); if (Telmoda_Madaline ~= 1) then player:setVar(player,"Telmoda_Madaline_Event",1); player:startEvent(0x0213); else player:startEvent(0x0269); 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
davidedmonds/darkstar
scripts/globals/spells/blind_ii.lua
18
1733
----------------------------------------- -- Spell: Blind II -- caster:getMerit() returns a value which is equal to the number of merit points TIMES the value of each point -- Blind II value per point is '1' This is a constant set in the table 'merits' ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local merits = caster:getMerit(MERIT_BLIND_II); -- Pull base stats. local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_MND)); --blind uses caster INT vs target MND -- Base power. May need more research. local power = math.floor((dINT + 100) / 4); if (power < 15) then power = 15; end if (power > 30) then power = 30; end if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then power = power * 2; end power = power + merits; --similar to Slow II, merit potency bonus is added after the cap -- Duration, including resistance. Unconfirmed. local duration = 180 * applyResistanceEffect(caster,spell,target,dINT,35,merits*2,EFFECT_BLINDNESS); if (duration >= 90) then --Do it! if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then duration = duration * 2; end caster:delStatusEffect(EFFECT_SABOTEUR); if (target:addStatusEffect(EFFECT_BLINDNESS,power,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end return EFFECT_BLINDNESS; end;
gpl-3.0
kidaa/darkstar
scripts/globals/spells/absorb-agi.lua
11
1193
-------------------------------------- -- Spell: Absorb-AGI -- Steals an enemy's agility. -------------------------------------- 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) if(target:hasStatusEffect(EFFECT_AGI_DOWN) or caster:hasStatusEffect(EFFECT_AGI_BOOST)) then spell:setMsg(75); -- no effect else local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local resist = applyResistance(caster,spell,target,dINT,37,0); if(resist <= 0.125) then spell:setMsg(85); else spell:setMsg(332); caster:addStatusEffect(EFFECT_AGI_BOOST,ABSORB_SPELL_AMOUNT*resist, ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_DISPELABLE); -- caster gains AGI target:addStatusEffect(EFFECT_AGI_DOWN,ABSORB_SPELL_AMOUNT*resist, ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_ERASBLE); -- target loses AGI end end return EFFECT_AGI_DOWN; end;
gpl-3.0
MonokuroInzanaito/ygopro-777DIY
expansions/script/c60158703.lua
1
5347
--中华少女·缘木 function c60158703.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+LOCATION_GRAVE) e1:SetCountLimit(1,60158703) e1:SetCondition(c60158703.spcon) e1:SetValue(1) c:RegisterEffect(e1) -- local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetCondition(c60158703.descon) e2:SetOperation(c60158703.desop) c:RegisterEffect(e2) -- local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_LVCHANGE) e3:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_SINGLE) e3:SetCode(EVENT_SUMMON_SUCCESS) e3:SetProperty(EFFECT_FLAG_DELAY) e3:SetTarget(c60158703.tg) e3:SetOperation(c60158703.op) c:RegisterEffect(e3) local e4=e3:Clone() e4:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e4) -- local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_QUICK_O) e5:SetCode(EVENT_FREE_CHAIN) e5:SetHintTiming(0,0x1e0) e5:SetRange(LOCATION_HAND) e5:SetProperty(EFFECT_FLAG_CARD_TARGET) e5:SetCountLimit(1,6018703) e5:SetCost(c60158703.cost) e5:SetTarget(c60158703.target) e5:SetOperation(c60158703.operation) c:RegisterEffect(e5) end c60158703.card_code_list={60158702} function c60158703.filter(c) return c:IsFaceup() and c:IsCode(60158702) end function c60158703.spcon(e,c) if c==nil then return true end return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c60158703.filter,c:GetControler(),LOCATION_MZONE,0,1,nil) end function c60158703.descon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL+1 end function c60158703.desop(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():GetSummonLocation()==LOCATION_GRAVE then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetDescription(aux.Stringid(60151601,0)) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_LEAVE_FIELD_REDIRECT) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_CLIENT_HINT) e1:SetReset(RESET_EVENT+0x47e0000) e1:SetValue(LOCATION_REMOVED) e:GetHandler():RegisterEffect(e1,true) end end function c60158703.filter2(c) return c:IsSetCard(0x6b28) and c:IsFaceup() end function c60158703.filter3(c) return c:IsType(TYPE_MONSTER) and c:IsFaceup() end function c60158703.tg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c60158703.filter2,tp,LOCATION_MZONE,0,1,e:GetHandler()) and Duel.IsExistingMatchingCard(c60158703.filter3,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET) local g=Duel.SelectTarget(tp,c60158703.filter3,tp,LOCATION_MZONE,LOCATION_MZONE,1,2,nil) Duel.SetOperationInfo(0,CATEGORY_ATKCHANGE+CATEGORY_LVCHANGE,g,g:GetCount(),0,0) end function c60158703.op(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e) local tc=g:GetFirst() while tc do local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SET_ATTACK_FINAL) e1:SetValue(tc:GetAttack()/2) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) if not tc:IsType(TYPE_XYZ) then local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_CHANGE_LEVEL) e2:SetValue(tc:GetLevel()/2) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e2) else local e3=Effect.CreateEffect(e:GetHandler()) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_CHANGE_RANK) e3:SetValue(tc:GetRank()/2) e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e3) end tc=g:GetNext() end end function c60158703.filter4(c) return not (c:IsSetCard(0x6b28) and c:IsFaceup()) end function c60158703.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c60158703.filter2,tp,LOCATION_MZONE,0,1,nil) and not Duel.IsExistingMatchingCard(c60158703.filter4,tp,LOCATION_MZONE,0,1,nil) and e:GetHandler():IsAbleToGraveAsCost() and e:GetHandler():IsDiscardable() end Duel.SendtoGrave(e:GetHandler(),REASON_COST) end function c60158703.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chk==0 then return Duel.IsExistingTarget(c60158703.filter2,tp,LOCATION_MZONE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET) local g=Duel.SelectTarget(tp,c60158703.filter2,tp,LOCATION_MZONE,0,1,1,nil) end function c60158703.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc and tc:IsRelateToEffect(e) then local e3=Effect.CreateEffect(e:GetHandler()) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_IMMUNE_EFFECT) e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e3:SetRange(LOCATION_MZONE) e3:SetValue(c60158703.efilter) e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e3:SetOwnerPlayer(tp) tc:RegisterEffect(e3) end end function c60158703.efilter(e,re) return e:GetOwnerPlayer()~=re:GetOwnerPlayer() end
gpl-3.0
stevedonovan/luabuild
modules/luasocket/src/http.lua
5
12251
----------------------------------------------------------------------------- -- HTTP/1.1 client support for the Lua language. -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ------------------------------------------------------------------------------- local socket = require("socket") local url = require("socket.url") local ltn12 = require("ltn12") local mime = require("mime") local string = require("string") local headers = require("socket.headers") local base = _G local table = require("table") module("socket.http") ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- -- connection timeout in seconds TIMEOUT = 60 -- default port for document retrieval PORT = 80 -- user agent field sent in request USERAGENT = socket._VERSION ----------------------------------------------------------------------------- -- Reads MIME headers from a connection, unfolding where needed ----------------------------------------------------------------------------- local function receiveheaders(sock, headers) local line, name, value, err headers = headers or {} -- get first line line, err = sock:receive() if err then return nil, err end -- headers go until a blank line is found while line ~= "" do -- get field-name and value name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)")) if not (name and value) then return nil, "malformed reponse headers" end name = string.lower(name) -- get next line (value might be folded) line, err = sock:receive() if err then return nil, err end -- unfold any folded values while string.find(line, "^%s") do value = value .. line line = sock:receive() if err then return nil, err end end -- save pair in table if headers[name] then headers[name] = headers[name] .. ", " .. value else headers[name] = value end end return headers end ----------------------------------------------------------------------------- -- Extra sources and sinks ----------------------------------------------------------------------------- socket.sourcet["http-chunked"] = function(sock, headers) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function() -- get chunk size, skip extention local line, err = sock:receive() if err then return nil, err end local size = base.tonumber(string.gsub(line, ";.*", ""), 16) if not size then return nil, "invalid chunk size" end -- was it the last chunk? if size > 0 then -- if not, get chunk and skip terminating CRLF local chunk, err, part = sock:receive(size) if chunk then sock:receive() end return chunk, err else -- if it was, read trailers into headers table headers, err = receiveheaders(sock, headers) if not headers then return nil, err end end end }) end socket.sinkt["http-chunked"] = function(sock) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function(self, chunk, err) if not chunk then return sock:send("0\r\n\r\n") end local size = string.format("%X\r\n", string.len(chunk)) return sock:send(size .. chunk .. "\r\n") end }) end ----------------------------------------------------------------------------- -- Low level HTTP API ----------------------------------------------------------------------------- local metat = { __index = {} } function open(host, port, create) -- create socket with user connect function, or with default local c = socket.try((create or socket.tcp)()) local h = base.setmetatable({ c = c }, metat) -- create finalized try h.try = socket.newtry(function() h:close() end) -- set timeout before connecting h.try(c:settimeout(TIMEOUT)) h.try(c:connect(host, port or PORT)) -- here everything worked return h end function metat.__index:sendrequestline(method, uri) local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri) return self.try(self.c:send(reqline)) end function metat.__index:sendheaders(tosend) local canonic = headers.canonic local h = "\r\n" for f, v in base.pairs(tosend) do h = (canonic[f] or f) .. ": " .. v .. "\r\n" .. h end self.try(self.c:send(h)) return 1 end function metat.__index:sendbody(headers, source, step) source = source or ltn12.source.empty() step = step or ltn12.pump.step -- if we don't know the size in advance, send chunked and hope for the best local mode = "http-chunked" if headers["content-length"] then mode = "keep-open" end return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step)) end function metat.__index:receivestatusline() local status = self.try(self.c:receive(5)) -- identify HTTP/0.9 responses, which do not contain a status line -- this is just a heuristic, but is what the RFC recommends if status ~= "HTTP/" then return nil, status end -- otherwise proceed reading a status line status = self.try(self.c:receive("*l", status)) local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)")) return self.try(base.tonumber(code), status) end function metat.__index:receiveheaders() return self.try(receiveheaders(self.c)) end function metat.__index:receivebody(headers, sink, step) sink = sink or ltn12.sink.null() step = step or ltn12.pump.step local length = base.tonumber(headers["content-length"]) local t = headers["transfer-encoding"] -- shortcut local mode = "default" -- connection close if t and t ~= "identity" then mode = "http-chunked" elseif base.tonumber(headers["content-length"]) then mode = "by-length" end return self.try(ltn12.pump.all(socket.source(mode, self.c, length), sink, step)) end function metat.__index:receive09body(status, sink, step) local source = ltn12.source.rewind(socket.source("until-closed", self.c)) source(status) return self.try(ltn12.pump.all(source, sink, step)) end function metat.__index:close() return self.c:close() end ----------------------------------------------------------------------------- -- High level HTTP API ----------------------------------------------------------------------------- local function adjusturi(reqt) local u = reqt -- if there is a proxy, we need the full url. otherwise, just a part. if not reqt.proxy and not PROXY then u = { path = socket.try(reqt.path, "invalid path 'nil'"), params = reqt.params, query = reqt.query, fragment = reqt.fragment } end return url.build(u) end local function adjustproxy(reqt) local proxy = reqt.proxy or PROXY if proxy then proxy = url.parse(proxy) return proxy.host, proxy.port or 3128 else return reqt.host, reqt.port end end local function adjustheaders(reqt) -- default headers local lower = { ["user-agent"] = USERAGENT, ["host"] = reqt.host, ["connection"] = "close, TE", ["te"] = "trailers" } -- if we have authentication information, pass it along if reqt.user and reqt.password then lower["authorization"] = "Basic " .. (mime.b64(reqt.user .. ":" .. reqt.password)) end -- override with user headers for i,v in base.pairs(reqt.headers or lower) do lower[string.lower(i)] = v end return lower end -- default url parts local default = { host = "", port = PORT, path ="/", scheme = "http" } local function adjustrequest(reqt) -- parse url if provided local nreqt = reqt.url and url.parse(reqt.url, default) or {} -- explicit components override url for i,v in base.pairs(reqt) do nreqt[i] = v end if nreqt.port == "" then nreqt.port = 80 end socket.try(nreqt.host and nreqt.host ~= "", "invalid host '" .. base.tostring(nreqt.host) .. "'") -- compute uri if user hasn't overriden nreqt.uri = reqt.uri or adjusturi(nreqt) -- ajust host and port if there is a proxy nreqt.host, nreqt.port = adjustproxy(nreqt) -- adjust headers in request nreqt.headers = adjustheaders(nreqt) return nreqt end local function shouldredirect(reqt, code, headers) return headers.location and string.gsub(headers.location, "%s", "") ~= "" and (reqt.redirect ~= false) and (code == 301 or code == 302 or code == 303 or code == 307) and (not reqt.method or reqt.method == "GET" or reqt.method == "HEAD") and (not reqt.nredirects or reqt.nredirects < 5) end local function shouldreceivebody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 then return nil end if code >= 100 and code < 200 then return nil end return 1 end -- forward declarations local trequest, tredirect function tredirect(reqt, location) local result, code, headers, status = trequest { -- the RFC says the redirect URL has to be absolute, but some -- servers do not respect that url = url.absolute(reqt.url, location), source = reqt.source, sink = reqt.sink, headers = reqt.headers, proxy = reqt.proxy, nredirects = (reqt.nredirects or 0) + 1, create = reqt.create } -- pass location header back as a hint we redirected headers = headers or {} headers.location = headers.location or location return result, code, headers, status end function trequest(reqt) -- we loop until we get what we want, or -- until we are sure there is no way to get it local nreqt = adjustrequest(reqt) local h = open(nreqt.host, nreqt.port, nreqt.create) -- send request line and headers h:sendrequestline(nreqt.method, nreqt.uri) h:sendheaders(nreqt.headers) -- if there is a body, send it if nreqt.source then h:sendbody(nreqt.headers, nreqt.source, nreqt.step) end local code, status = h:receivestatusline() -- if it is an HTTP/0.9 server, simply get the body and we are done if not code then h:receive09body(status, nreqt.sink, nreqt.step) return 1, 200 end local headers -- ignore any 100-continue messages while code == 100 do headers = h:receiveheaders() code, status = h:receivestatusline() end headers = h:receiveheaders() -- at this point we should have a honest reply from the server -- we can't redirect if we already used the source, so we report the error if shouldredirect(nreqt, code, headers) and not nreqt.source then h:close() return tredirect(reqt, headers.location) end -- here we are finally done if shouldreceivebody(nreqt, code) then h:receivebody(headers, nreqt.sink, nreqt.step) end h:close() return 1, code, headers, status end local function srequest(u, b) local t = {} local reqt = { url = u, sink = ltn12.sink.table(t) } if b then reqt.source = ltn12.source.string(b) reqt.headers = { ["content-length"] = string.len(b), ["content-type"] = "application/x-www-form-urlencoded" } reqt.method = "POST" end local code, headers, status = socket.skip(1, trequest(reqt)) return table.concat(t), code, headers, status end request = socket.protect(function(reqt, body) if base.type(reqt) == "string" then return srequest(reqt, body) else return trequest(reqt) end end)
mit
davidedmonds/darkstar
scripts/globals/spells/bluemagic/regeneration.lua
46
1483
----------------------------------------- -- Spell: Regeneration -- Gradually restores HP -- Spell cost: 36 MP -- Monster Type: Aquans -- Spell Type: Magical (Light) -- Blue Magic Points: 2 -- Stat Bonus: MND+2 -- Level: 78 -- Casting Time: 2 Seconds -- Recast Time: 60 Seconds -- Spell Duration: 30 ticks, 90 Seconds -- -- Combos: None ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_REGEN; local power = 25; local duration = 90; 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:hasStatusEffect(EFFECT_REGEN) and target:getStatusEffect(EFFECT_REGEN):getTier() == 1) then target:delStatusEffect(EFFECT_REGEN); end if (target:addStatusEffect(typeEffect,power,3,duration,0,0,0) == false) then spell:setMsg(75); end; return typeEffect; end;
gpl-3.0
MonokuroInzanaito/ygopro-777DIY
expansions/script/c37564513.lua
1
2091
--Lahm Loving local m=37564513 local cm=_G["c"..m] xpcall(function() require("expansions/script/c37564765") end,function() require("script/c37564765") end) cm.Senya_desc_with_nanahira=true function cm.initial_effect(c) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1,m+EFFECT_COUNT_CODE_OATH) e1:SetTarget(Senya.multi_choice_target(m,cm.tg1,cm.tg2)) e1:SetOperation(Senya.multi_choice_operation(cm.op1,cm.op2)) c:RegisterEffect(e1) Senya.NanahiraTrap(c,e1) end function cm.tg1(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(1-tp) and chkc:IsOnField() and chkc~=e:GetHandler() end if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,0,LOCATION_ONFIELD,1,e:GetHandler()) and Senya.NanahiraExistingCondition(false)(e,tp,eg,ep,ev,re,r,rp) end local pr1,pr2=e:GetProperty() e:SetProperty(bit.bor(pr1,EFFECT_FLAG_CARD_TARGET),pr2) e:SetCategory(CATEGORY_DESTROY) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,aux.TRUE,tp,0,LOCATION_ONFIELD,1,1,e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function cm.tg2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD,1,nil) and Senya.NanahiraExistingCondition(true)(e,tp,eg,ep,ev,re,r,rp) and Duel.IsPlayerCanDraw(tp,1) end local pr1,pr2=e:GetProperty() e:SetProperty(pr1-bit.band(pr1,EFFECT_FLAG_CARD_TARGET),pr2) e:SetCategory(CATEGORY_REMOVE+CATEGORY_DRAW) local g=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD,nil) Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0) end function cm.op1(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc and tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end function cm.op2(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD,1,1,nil) if g:GetCount()>0 and Duel.Remove(g,POS_FACEUP,REASON_EFFECT) then Duel.Draw(tp,1,REASON_EFFECT) end end
gpl-3.0
lhog/Zero-K
effects/unused_charlize.lua
25
30008
-- charlize_7 -- charlize_3 -- charlize_2 -- charlize_14 -- charlize_1 -- charlize_17 -- charlize_6 -- charlize_4 -- charlize_10 -- charlize_11 -- charlize_12 -- charlize_21 -- charlize -- charlize_18 -- charlize_8 -- charlize_19 -- charlize_ani -- charlize_9 -- charlize_15 -- charlize_13 -- charlize_5 -- charlize_16 -- charlize_20 return { ["charlize_7"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0007]], }, }, }, ["charlize_3"] = { groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 100, ttl = 10, color = { [1] = 1, [2] = 1, [3] = 0, }, }, wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0003]], }, }, }, ["charlize_2"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0002]], }, }, }, ["charlize_14"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0014]], }, }, }, ["charlize_1"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0001]], }, }, }, ["charlize_17"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0017]], }, }, }, ["charlize_6"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0006]], }, }, }, ["charlize_4"] = { groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 100, ttl = 23, color = { [1] = 1, [2] = 0.40000000596046, [3] = 0, }, }, wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0004]], }, }, }, ["charlize_10"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0010]], }, }, }, ["charlize_11"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0011]], }, }, }, ["charlize_12"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0012]], }, }, }, ["charlize_21"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0021]], }, }, }, ["charlize"] = { animation = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:CHARLIZE_ANI]], pos = [[0, 0, 0]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 2, ground = true, water = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[1 1 0 0.01 1 0.7 0.5 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 15, particlelifespread = 0, particlesize = 2, particlesizespread = 5, particlespeed = 6, particlespeedspread = 4, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["charlize_18"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0018]], }, }, }, ["charlize_8"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0008]], }, }, }, ["charlize_19"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0019]], }, }, }, ["charlize_ani"] = { frame1 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:CHARLIZE_1]], pos = [[0, 5, 0]], }, }, frame10 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 10, explosiongenerator = [[custom:CHARLIZE_10]], pos = [[0, 5, 0]], }, }, frame11 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 11, explosiongenerator = [[custom:CHARLIZE_11]], pos = [[0, 5, 0]], }, }, frame12 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 12, explosiongenerator = [[custom:CHARLIZE_12]], pos = [[0, 5, 0]], }, }, frame13 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 13, explosiongenerator = [[custom:CHARLIZE_13]], pos = [[0, 5, 0]], }, }, frame14 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 14, explosiongenerator = [[custom:CHARLIZE_14]], pos = [[0, 5, 0]], }, }, frame15 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 15, explosiongenerator = [[custom:CHARLIZE_15]], pos = [[0, 5, 0]], }, }, frame16 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 16, explosiongenerator = [[custom:CHARLIZE_16]], pos = [[0, 5, 0]], }, }, frame17 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 17, explosiongenerator = [[custom:CHARLIZE_17]], pos = [[0, 5, 0]], }, }, frame18 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 18, explosiongenerator = [[custom:CHARLIZE_18]], pos = [[0, 5, 0]], }, }, frame19 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 19, explosiongenerator = [[custom:CHARLIZE_19]], pos = [[0, 5, 0]], }, }, frame2 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 2, explosiongenerator = [[custom:CHARLIZE_2]], pos = [[0, 5, 0]], }, }, frame20 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 20, explosiongenerator = [[custom:CHARLIZE_20]], pos = [[0, 5, 0]], }, }, frame21 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 21, explosiongenerator = [[custom:CHARLIZE_21]], pos = [[0, 5, 0]], }, }, frame3 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 3, explosiongenerator = [[custom:CHARLIZE_3]], pos = [[0, 5, 0]], }, }, frame4 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 4, explosiongenerator = [[custom:CHARLIZE_4]], pos = [[0, 5, 0]], }, }, frame5 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 5, explosiongenerator = [[custom:CHARLIZE_5]], pos = [[0, 5, 0]], }, }, frame6 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 6, explosiongenerator = [[custom:CHARLIZE_6]], pos = [[0, 5, 0]], }, }, frame7 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 7, explosiongenerator = [[custom:CHARLIZE_7]], pos = [[0, 5, 0]], }, }, frame8 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 8, explosiongenerator = [[custom:CHARLIZE_8]], pos = [[0, 5, 0]], }, }, frame9 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 9, explosiongenerator = [[custom:CHARLIZE_9]], pos = [[0, 5, 0]], }, }, }, ["charlize_9"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0009]], }, }, }, ["charlize_15"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0015]], }, }, }, ["charlize_13"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0013]], }, }, }, ["charlize_5"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0005]], }, }, }, ["charlize_16"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0016]], }, }, }, ["charlize_20"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, alwaysvisible = true, colormap = [[0 0 0 0.01 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 2, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0, pos = [[0, 15, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[kE1_0020]], }, }, }, }
gpl-2.0
MonokuroInzanaito/ygopro-777DIY
expansions/script/c91000014.lua
1
6293
--天印-灵威仰 function c91000014.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,nil,2,2,nil,nil,5) c:EnableReviveLimit() --Damage local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(91000014,0)) e1:SetCategory(CATEGORY_DAMAGE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_FREE_CHAIN) e1:SetRange(LOCATION_MZONE) e1:SetHintTiming(0,0x1e0) e1:SetCost(c91000014.damcost) e1:SetTarget(c91000014.damtg) e1:SetOperation(c91000014.damop) c:RegisterEffect(e1) --adjust local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_ADJUST) e2:SetRange(LOCATION_MZONE) e2:SetOperation(c91000014.aop) c:RegisterEffect(e2) if not c91000014.global_check then c91000014.global_check=true local ge1=Effect.CreateEffect(c) ge1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) ge1:SetCode(EVENT_ADJUST) ge1:SetOperation(c91000014.rop) Duel.RegisterEffect(ge1,0) end end function c91000014.rfilter(c) return c:IsType(TYPE_XYZ) and c:GetOriginalRank()==2 and c:GetFlagEffect(91000014)==0 end function c91000014.rop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(c91000014.rfilter,tp,LOCATION_MZONE,0,nil) local tc=g:GetFirst() while tc do local ct=tc:GetOverlayCount() local code=tc:GetOriginalCode()*3+1 local e1=Effect.CreateEffect(tc) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_ADJUST) e1:SetRange(LOCATION_MZONE) e1:SetOperation(c91000014.reop) e1:SetLabel(ct) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1,true) tc:RegisterFlagEffect(91000014,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) tc:RegisterFlagEffect(code,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1,0) tc=g:GetNext() end end function c91000014.reop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local ct1=e:GetLabel() local ct2=c:GetOverlayCount() if ct1==ct2 then return end if ct1>ct2 then local ct=ct1-ct2 local code=c:GetOriginalCode()*3+1 local lt=c:GetFlagEffectLabel(code) c:SetFlagEffectLabel(code,lt+ct) end e:SetLabel(ct2) Duel.Readjust() end function c91000014.afilter(c) local code=c:GetOriginalCode()*3+1 return c:GetFlagEffect(code)>0 and c:IsType(TYPE_XYZ) and c:GetOriginalRank()==2 end function c91000014.aop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(c91000014.afilter,tp,LOCATION_MZONE,0,nil) local tc=g:GetFirst() while tc do local code=tc:GetOriginalCode()*3+1 local ct=tc:GetFlagEffectLabel(code) if ct>=1 and tc:GetFlagEffect(91000114)==0 then local e1=Effect.CreateEffect(tc) e1:SetDescription(aux.Stringid(91000014,2)) e1:SetProperty(EFFECT_FLAG_CLIENT_HINT) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_IMMUNE_EFFECT) e1:SetRange(LOCATION_MZONE) e1:SetCondition(c91000014.effcon) e1:SetValue(c91000014.efilter) e1:SetLabel(1) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1,true) tc:RegisterFlagEffect(91000114,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) end if ct>=2 and tc:GetFlagEffect(91000214)==0 then local e2=Effect.CreateEffect(tc) e2:SetDescription(aux.Stringid(91000014,3)) e2:SetProperty(EFFECT_FLAG_CLIENT_HINT) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_PIERCE) e2:SetCondition(c91000014.effcon) e2:SetLabel(2) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e2,true) local e3=Effect.CreateEffect(tc) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_EXTRA_ATTACK) e3:SetCondition(c91000014.effcon) e3:SetValue(1) e3:SetLabel(2) e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e3,true) tc:RegisterFlagEffect(91000214,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) end if ct>=3 and tc:GetFlagEffect(91000314)==0 then local e4=Effect.CreateEffect(tc) e4:SetDescription(aux.Stringid(91000014,4)) e4:SetProperty(EFFECT_FLAG_CLIENT_HINT) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e4:SetCode(EVENT_DAMAGE_CALCULATING) e4:SetCondition(c91000014.effcon) e4:SetOperation(c91000014.cgop) e4:SetLabel(3) e4:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e4,true) tc:RegisterFlagEffect(91000314,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) end tc=g:GetNext() end end function c91000014.effcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local code=c:GetOriginalCode()*3+1 if c:GetFlagEffect(code)>0 then return c:GetFlagEffectLabel(code)>=e:GetLabel() else return false end end function c91000014.efilter(e,re) return re:GetOwnerPlayer()~=e:GetHandler():GetControler() end function c91000014.cgop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local code=c:GetOriginalCode()*3+1 local ct=0 if c:GetFlagEffect(code)>0 then ct=c:GetFlagEffectLabel(code) end local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetCondition(function(e) return Duel.GetAttacker()==e:GetHandler() or Duel.GetAttackTarget()==e:GetHandler() end) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_DAMAGE_CAL) e1:SetValue(ct*600) c:RegisterEffect(e1) end function c91000014.damcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.CheckRemoveOverlayCard,tp,LOCATION_MZONE,0,1,nil,tp,1,REASON_COST) and e:GetHandler():GetFlagEffect(91000414)==0 end Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(91000014,1)) local sg=Duel.SelectMatchingCard(tp,Card.CheckRemoveOverlayCard,tp,LOCATION_MZONE,0,1,1,nil,tp,1,REASON_COST) Duel.HintSelection(sg) local tc=sg:GetFirst() local ct=tc:GetOverlayCount() tc:RemoveOverlayCard(tp,1,ct,REASON_COST) local ct2=Duel.GetOperatedGroup():GetCount() e:SetLabel(ct2) e:GetHandler():RegisterFlagEffect(91000414,RESET_CHAIN,0,1) end function c91000014.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local ct=e:GetLabel() Duel.SetTargetPlayer(1-tp) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,ct*600) end function c91000014.damop(e,tp,eg,ep,ev,re,r,rp) local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER) local ct=e:GetLabel() Duel.Damage(p,ct*600,REASON_EFFECT) end
gpl-3.0
davidedmonds/darkstar
scripts/zones/Valkurm_Dunes/npcs/Quanteilleron_RK.lua
28
3133
----------------------------------- -- Area: Valkurm Dunes -- NPC: Quanteilleron, R.K. -- Outpost Conquest Guards -- @pos 144 -7 104 103 ------------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Valkurm_Dunes/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ZULKHEIM; local csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %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 == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
kidaa/darkstar
scripts/zones/Valkurm_Dunes/npcs/Quanteilleron_RK.lua
28
3133
----------------------------------- -- Area: Valkurm Dunes -- NPC: Quanteilleron, R.K. -- Outpost Conquest Guards -- @pos 144 -7 104 103 ------------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Valkurm_Dunes/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ZULKHEIM; local csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %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 == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
waterlgndx/darkstar
scripts/zones/Castle_Oztroja/npcs/_m73.lua
2
1856
----------------------------------- -- Area: Castle Oztroja -- NPC: _m73 (Torch Stand) -- Notes: Opens door _477 when _m72 to _m75 are lit -- !pos -140.146 -72.058 -137.145 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/settings"); ----------------------------------- function onTrigger(player,npc) DoorID = npc:getID() - 3; Torch1 = npc:getID() - 1 ; Torch2 = npc:getID(); Torch3 = npc:getID() + 1; Torch4 = npc:getID() + 2; DoorA = GetNPCByID(DoorID):getAnimation(); TorchStand1A = GetNPCByID(Torch1):getAnimation(); TorchStand2A = npc:getAnimation(); TorchStand3A = GetNPCByID(Torch3):getAnimation(); TorchStand4A = GetNPCByID(Torch4):getAnimation(); if (DoorA == 9 and TorchStand2A == 9) then player:startEvent(10); else player:messageSpecial(TORCH_LIT); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (option == 1) then GetNPCByID(Torch2):openDoor(55); if ((DoorA == 9)) then GetNPCByID(DoorID):openDoor(35); -- The lamps shouldn't go off here, but I couldn't get the torches to update animation times without turning them off first -- They need to be reset to the door open time(35s) + 4s (39 seconds) GetNPCByID(Torch1):setAnimation(9); GetNPCByID(Torch2):setAnimation(9); GetNPCByID(Torch3):setAnimation(9); GetNPCByID(Torch4):setAnimation(9); GetNPCByID(Torch1):openDoor(39); GetNPCByID(Torch2):openDoor(39); GetNPCByID(Torch3):openDoor(39); GetNPCByID(Torch4):openDoor(39); end end end;
gpl-3.0
waterlgndx/darkstar
scripts/globals/spells/sheepfoe_mambo.lua
2
1632
----------------------------------------- -- Spell: Sheepfoe Mambo -- Grants evasion bonus to all members. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(dsp.skill.SINGING); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(dsp.slot.RANGED); -- Since nobody knows the evasion values for mambo, I'll just make shit up! (aka - same as madrigal) local power = 5; if (sLvl+iLvl > 85) then power = power + math.floor((sLvl+iLvl-85) / 18); end if (power >= 15) then power = 15; end local iBoost = caster:getMod(dsp.mod.MAMBO_EFFECT) + caster:getMod(dsp.mod.ALL_SONGS_EFFECT); if (iBoost > 0) then power = power + 1 + (iBoost-1)*4; end if (caster:hasStatusEffect(dsp.effect.SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(dsp.effect.MARCATO)) then power = power * 1.5; end caster:delStatusEffect(dsp.effect.MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(dsp.mod.SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(dsp.effect.TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,dsp.effect.MAMBO,power,0,duration,caster:getID(), 0, 1)) then spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT); end return dsp.effect.MAMBO; end;
gpl-3.0
will4wachter/Project1
scripts/globals/items/handful_of_sunflower_seeds.lua
35
1215
----------------------------------------- -- ID: 4505 -- Item: handful_of_sunflower_seeds -- Food Effect: 5Min, All Races ----------------------------------------- -- Dexterity -3 -- Intelligence 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,300,4505); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -3); target:addMod(MOD_INT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -3); target:delMod(MOD_INT, 1); end;
gpl-3.0
will4wachter/Project1
scripts/zones/Bastok_Mines/npcs/Crying_Wind_IM.lua
6
4806
----------------------------------- -- Area: Bastok Mines -- NPC: Crying Wind, I.M. -- X Grant Signet -- X Recharge Emperor Band, Empress Band, or Chariot Band -- X Accepts traded Crystals to fill up the Rank bar to open new Missions. -- X Sells items in exchange for Conquest Points -- X Start Supply Run Missions and offers a list of already-delivered supplies. -- Start an Expeditionary Force by giving an E.F. region insignia to you. ------------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/globals/common"); require("scripts/zones/Bastok_Mines/TextIDs"); guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, JEUNO guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border size = table.getn(BastInv); inventory = BastInv; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies." region = player:getVar("supplyQuest_region"); player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region)); player:setVar("supplyQuest_started",0); player:setVar("supplyQuest_region",0); player:setVar("supplyQuest_fresh",0); else Menu1 = getArg1(guardnation,player); Menu2 = getExForceAvailable(guardnation,player); Menu3 = conquestRanking(); Menu4 = getSupplyAvailable(guardnation,player); Menu5 = player:getNationTeleport(guardnation); Menu6 = getArg6(player); Menu7 = player:getCP(); Menu8 = getRewardExForce(guardnation,player); player:startEvent(0x7ff9,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdateCSID: %u",csid); --printf("onUpdateOPTION: %u",option); 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]); break; end; end; end; end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinishCSID: %u",csid); --printf("onFinishOPTION: %u",option); if(option == 1) then duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; 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 if(player:getNation() == guardnation) then itemCP = inventory[Item + 1]; else if(inventory[Item + 1] <= 8000) then itemCP = inventory[Item + 1] * 2; else itemCP = inventory[Item + 1] + 8000; end; end; if(player:hasItem(inventory[Item + 2]) == false) then 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; else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end; break; end; end; elseif(option >= 65541 and option <= 65565) then -- player chose supply quest. region = option - 65541; player:addKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region)); player:setVar("supplyQuest_started",vanaDay()); player:setVar("supplyQuest_region",region); player:setVar("supplyQuest_fresh",getConquestTally()); end; end;
gpl-3.0
wyaocn/skynet-ejoy2d
lualib/ejoy2d/particle.lua
1
3799
local debug = debug local ej = require "ejoy2d" local c = require "ejoy2d.particle.c" local shader = require "ejoy2d.shader" local pack = require "ejoy2d.spritepack.c" local fw = require "window.c" local matrix = require "ejoy2d.matrix" local math = require "math" local sprite = require "ejoy2d.sprite" local particle_configs = dofile(fw.WorkDir..[[asset/interface/particle_particle_config.lua]]) local particle_group_configs = {} local particle = {} local particle_meta = {__index = {mat = {}, col = {}}} function particle_meta.__index:update(dt) if not self.is_active then return end self.is_active = false loop_active = false for _, v in ipairs(self.particles) do local visible = self:is_particle_visible(v) if visible then if not v.is_visible then v.is_visible = true c.reset(v.particle) end local active = c.update(v.particle, dt, matrix(v.anchor.world_matrix), v.edge) self.is_active = active or self.is_active loop_active = loop_active or (self.is_active and v.is_loop or false) else if v.is_visible then v.is_visible = false end end end if self.group.type == pack.TYPE_ANIMATION and self.group.frame_count > 1 then local stay_last = false local last_frame = self.group.frame >= self.group.frame_count - 1 if self.is_active then if last_frame then if loop_active then stay_last = true self.group.frame = self.group.frame_count - 1 else self.is_active = false end end else if not last_frame then self.is_active = true end end --print(self.group.frame, self.group.frame_count, stay_last, last_frame, loop_active) if not stay_last and not last_frame then self.float_frame = self.float_frame + fw.AnimationFramePerFrame self.group.frame = self.float_frame end end end function particle_meta.__index:reset() self.is_active = true if self.group.type == pack.TYPE_ANIMATION then self.group.frame = 0 end self.float_frame = 0 for _, v in ipairs(self.particles) do v.is_visible = false end end function particle_meta.__index:is_particle_visible(particle) if self.group.type == pack.TYPE_ANIMATION then return self.group:child_visible(particle.anchor.name) else return true end end function particle.preload(config_path) particle_configs = dofile(config_path.."_particle_config.lua") end local function new_single(name, anchor) local config = rawget(particle_configs, name) assert(config ~= nil, "particle not exists:"..name) local texName = config.texName local cobj = c.new(config) anchor.visible = true if cobj then local sprite = ej.sprite("particle", texName) local x, y, w, h = sprite:aabb() local edge = 2 * math.min(w, h) anchor:anchor_particle(cobj, sprite) return {particle = cobj, sprite = sprite, edge = edge, src_blend = config.blendFuncSource, dst_blend = config.blendFuncDestination, anchor = anchor, is_loop = config.duration < 0, emit_in_world = config.positionType == 2, name = name } end end function particle.new(name, callback) local config,particles,loop,group = rawget(particle_configs, name),{},false if config then group = ej.sprite("particle", 0xffff) local spr = new_single(name, group) rawset(particles, #particles+1, spr) loop = loop or spr.is_loop else group = ej.sprite("particle", name) local config = table.pack(group:children_name()) for _, v in ipairs(config) do local anchor = group:fetch(v) local spr = new_single(v, anchor) rawset(particles, #particles+1, spr) -- group:mount(v, spr.sprite) loop = loop or spr.is_loop end end return debug.setmetatable({group=group, is_active = true, is_visible = false, particles = particles, end_callback = callback, is_loop = loop, float_frame = 0, }, particle_meta) end return particle
mit
will4wachter/Project1
scripts/zones/Aht_Urhgan_Whitegate/npcs/Rytaal.lua
5
4537
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Rytaal -- Type: Standard NPC -- @pos 112.002 -1.338 -45.038 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentday = tonumber(os.date("%j")); local lastarmyIDtag = player:getVar("TIME_IMPERIAL_ARMY_ID_TAG"); local currenttagnummber = player:getVar("REMAINING_IMPERIAL_ARMY_ID_TAG"); local diffday = currentday - lastarmyIDtag ; local currentassault = player:getCurrentMission(ASSAULT); local haveimperialIDtag; if(player:getCurrentMission(TOAU) == PRESIDENT_SALAHEEM and player:getVar("TOAUM3") == 0)then player:startEvent(0x010D,0,0,0,0,0,0,0,0,0); elseif(player:getCurrentMission(TOAU) <= IMMORTAL_SENTRIES or player:getMainLvl() <= 49) then player:startEvent(0x010E); elseif ((currentassault ~= 0) and (hasAssaultOrders(player) == 0)) then if (player:getVar("AssaultComplete") == 1) then player:messageText(player,RYTAAL_MISSION_COMPLETE); player:completeMission(ASSAULT, currentassault); else player:messageText(player,RYTAAL_MISSION_FAILED); player:addMission(ASSAULT,0); end player:setVar("AssaultComplete",0); elseif((player:getCurrentMission(TOAU) > PRESIDENT_SALAHEEM) or (player:getCurrentMission(TOAU) == PRESIDENT_SALAHEEM and player:getVar("TOAUM3") ==1))then if (lastarmyIDtag == 0 )then -- first time you get the tag player:setVar("REMAINING_IMPERIAL_ARMY_ID_TAG",3); currenttagnummber =3; player:setVar("TIME_IMPERIAL_ARMY_ID_TAG",currentday); elseif ( diffday > 0 )then currenttagnummber = currenttagnummber + diffday ; if (currenttagnummber > 3)then -- store 3 TAG max currenttagnummber = 3; end player:setVar("REMAINING_IMPERIAL_ARMY_ID_TAG",currenttagnummber); player:setVar("TIME_IMPERIAL_ARMY_ID_TAG",currentday); end if(player:hasKeyItem(IMPERIAL_ARMY_ID_TAG))then haveimperialIDtag = 1; else haveimperialIDtag = 0; end player:startEvent(0x010C,IMPERIAL_ARMY_ID_TAG,currenttagnummber,currentassault,haveimperialIDtag); 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); local currenttagnummber = player:getVar("REMAINING_IMPERIAL_ARMY_ID_TAG"); local CurrentAssault = player:getCurrentMission(ASSAULT); if(csid == 0x010D)then player:setVar("TOAUM3",1); elseif(csid == 0x010C and option == 1 and player:hasKeyItem(IMPERIAL_ARMY_ID_TAG)==false and currenttagnummber > 0)then player:addKeyItem(IMPERIAL_ARMY_ID_TAG); player:messageSpecial(KEYITEM_OBTAINED,IMPERIAL_ARMY_ID_TAG); player:setVar("REMAINING_IMPERIAL_ARMY_ID_TAG",currenttagnummber - 1); elseif(csid == 0x010C and option == 2 and player:hasKeyItem(IMPERIAL_ARMY_ID_TAG)==false and hasAssaultOrders(player) ~= 0)then if(player:hasKeyItem(LEUJAOAM_ASSAULT_ORDERS))then player:delKeyItem(LEUJAOAM_ASSAULT_ORDERS); elseif(player:hasKeyItem(MAMMOOL_JA_ASSAULT_ORDERS))then player:delKeyItem(MAMMOOL_JA_ASSAULT_ORDERS); elseif(player:hasKeyItem(LEBROS_ASSAULT_ORDERS))then player:delKeyItem(LEBROS_ASSAULT_ORDERS); elseif(player:hasKeyItem(PERIQIA_ASSAULT_ORDERS))then player:delKeyItem(PERIQIA_ASSAULT_ORDERS); elseif(player:hasKeyItem(ILRUSI_ASSAULT_ORDERS ))then player:delKeyItem(ILRUSI_ASSAULT_ORDERS); elseif(player:hasKeyItem(NYZUL_ISLE_ASSAULT_ORDERS))then player:delKeyItem(NYZUL_ISLE_ASSAULT_ORDERS); end player:addKeyItem(IMPERIAL_ARMY_ID_TAG); player:messageSpecial(KEYITEM_OBTAINED,IMPERIAL_ARMY_ID_TAG); player:delMission(ASSAULT,CurrentAssault); end end;
gpl-3.0
waterlgndx/darkstar
scripts/zones/Bastok_Markets/npcs/Wulfnoth.lua
2
1357
----------------------------------- -- Area: Bastok Markets -- NPC: Wulfnoth -- Type: Goldsmithing Synthesis Image Support -- !pos -211.937 -7.814 -56.292 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local guildMember = isGuildMember(player,6); local SkillCap = getCraftSkillCap(player, dsp.skill.GOLDSMITHING); local SkillLevel = player:getSkillLevel(dsp.skill.GOLDSMITHING); if (guildMember == 1) then if (player:hasStatusEffect(dsp.effect.GOLDSMITHING_IMAGERY) == false) then player:startEvent(303,SkillCap,SkillLevel,1,201,player:getGil(),0,3,0); else player:startEvent(303,SkillCap,SkillLevel,1,201,player:getGil(),7054,3,0); end else player:startEvent(303); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 303 and option == 1) then player:messageSpecial(GOLDSMITHING_SUPPORT,0,3,1); player:addStatusEffect(dsp.effect.GOLDSMITHING_IMAGERY,1,0,120); end end;
gpl-3.0
davidedmonds/darkstar
scripts/globals/items/broiled_carp.lua
35
1291
----------------------------------------- -- ID: 4586 -- Item: Broiled Carp -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 2 -- Mind -1 -- Ranged ATT % 14 ----------------------------------------- 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,3600,4586); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -1); target:addMod(MOD_RATTP, 14); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -1); target:delMod(MOD_RATTP, 14); end;
gpl-3.0
will4wachter/Project1
scripts/globals/items/broiled_carp.lua
35
1291
----------------------------------------- -- ID: 4586 -- Item: Broiled Carp -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 2 -- Mind -1 -- Ranged ATT % 14 ----------------------------------------- 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,3600,4586); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -1); target:addMod(MOD_RATTP, 14); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -1); target:delMod(MOD_RATTP, 14); end;
gpl-3.0
unknowntg/unknowntg
plugins/help_plug.lua
2
3218
do function run(msg, matches) local text = [[ >>لیست ابزار های آواست: _____________________ »دریافت متن تبلیغ تبلیغ »دریافت وضعیت ارز !arz »دریافت اوقات شرعی !praytime [نام شهر] »دریافت عکس های P.o.r.n !boobs »دریافت شماره ربات !share »انجام محاسبات ریاضی !calc 2+2 »دریافت عکس قاره نام قاره مورد نطر را به زبان فارسی ارسال کنید »تکرار متن !echo [متن] »دانلود عکس لینک عکس را بفرستید و بات بصورت خودکار برای شما دانلود و ارسال میکند »برای فیلتر کردن کلمه filter + [کلمه] و برای خارج کردن از فیلتر filter - [کلمه] »برای دیدن درباره خود !info !aboutme »برای مشاهده اطلاعات یک اکانت گیت هاب github [نام پروژه] [نام گیت هاب] »برای جستوجو در گوگل !google [متن] »برای مشاهده راهنما کامل helps »برای نوشتن بر روی عکس !meme [متن] [موضوع پس زمینه] »برای دیدن مقام خود !me »برای تبدیل متن به عکس کیو آر کد !qr [متن] »برای تنظیم لینک !setlink [لینک] [نام گروه] و برای دریافت لینک !get [نام گروه] »برای دیدن درباره خود !info »برای کار با آیپی ip config [ip] ping [ip] getip »(برای دریافت لینک گروه در خصوصی(لطفا برای جلوگیری از ریپورت شدن ربات شماره ربات را ذخیره کنید !linkpv »برای دریافت نقشه یک مکان !loc [نام مکان] »برای ارسال پیام به تمام اعضای گروه !s2a [متن] »برای اسپم دادن از طرف ربات !spam [متن اسپم] [تعداد] Avast [متن اسپم] [تعداد] »برای دریافت پشتیبانی پیشرفته !support »برای دریافت یوزرنیم تمام کاربران !tagall . »برای تبدیل متن به عکس !tex [متن] »برای دریافت زمان !time [نام شهر] »برای ترجمه متن !tr [متن] »برای جستوجو در ویکی پدیا !wiki [موضوع] »برای کار با زیبا نویس write [متن] »برای دیدن اعضای تیم آواست تنها مدیران تیم vcard »برای دیدن متن درباره ربات !version !avast »تبدیل متن به صدا !voice [متن] »برای امتیاز دادن به ربات !vote [عدد] »برای دریافت اب و هوا !weather [نام شهر] »برای دریافت اسکرین شات از یک سایت /web [آدرس سایت] »برای دریافت موج رادیو نام رادیو را بفرستید »دریافت خدمات ایرانسل !irancell »دریافت کد های مخفی اندروید !secretcode ________________________ >>برای دریافت اطلاعات بیشتر در @avast_Team عضو شوید ]] return text end return { patterns = { "^[!/#](helppl)$", }, run = run } end
gpl-2.0
will4wachter/Project1
scripts/globals/abilities/pets/burning_strike.lua
6
1279
--------------------------------------------------- -- Burning Strike M = 6? --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/summon"); require("/scripts/globals/magic"); require("/scripts/globals/monstertpmoves"); --------------------------------------------------- function OnAbilityCheck(player, target, ability) return 0,0; end; function OnPetAbility(target, pet, skill) local numhits = 1; local accmod = 1; local dmgmod = 6; local totaldamage = 0; local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,0,TP_NO_EFFECT,1,2,3); --get resist multiplier (1x if no resist) local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, ELE_FIRE); --get the resisted damage damage.dmg = damage.dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) damage.dmg = mobAddBonuses(pet,spell,target,damage.dmg,1); totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,numhits); target:delHP(totaldamage); target:updateEnmityFromDamage(pet,totaldamage); return totaldamage; end
gpl-3.0
dmzgroup/lmk
scripts/src/version.lua
2
2146
require "lmkbuild" local exec = lmkbuild.exec local get_var = lmkbuild.get_var local io = io local ipairs = ipairs local os = os local print = print local resolve = lmkbuild.resolve local rm = lmkbuild.rm local set_local = lmkbuild.set_local local tostring = tostring local get_build_number = lmkbuild.get_build_number module (...) function main (files) local vFileName = files[1] if vFileName then local name = resolve ("$(appName)") if not name then name = resolve ("$(name)") end if name == "" then name = "UNKNOWN APPLICATION" end local major = resolve ("$(majorVersion)") if major == "" then major = "?" end local minor = resolve ("$(minorVersion)") if minor == "" then minor = "?" end local bug = resolve ("$(bugVersion)") if bug == "" then bug = "?" end local rtype = resolve ("$(releaseType)") local image = resolve ("$(aboutImage)") local f = io.open (resolve ("$(localTmpDir)/" .. vFileName), "w") local build, p1, p2 = get_build_number () if f then f:write ('<?xml version="1.0" encoding="UTF-8"?>\n') f:write ('<dmz>\n') f:write ('<version>\n') f:write (' <name value="' .. name .. '"/>\n') f:write (' <major value="' .. major.. '"/>\n') f:write (' <minor value="' .. minor .. '"/>\n') f:write (' <bug value="' .. bug .. '"/>\n') f:write (' <build value="' .. build .. '"/>\n') if releaseType ~= "" then f:write (' <release value="' .. rtype .. '"/>\n') end if image and image ~= "" then f:write (' <image value="' .. image .. '"/>\n') end f:write ('</version>\n') f:write ('</dmz>\n') f:close () end f = io.open (resolve ("$(localTmpDir)buildnumber.txt"), "w") if f then f:write (build) f:close () end f = io.open (resolve ("$(localTmpDir)versionnumber.txt"), "w") if f then f:write (major .. "-" .. minor .. "-" .. bug) f:close () end end end function test (files) end function clean (files) end function clobber (files) end
mit
antagon/coroner
src/coroner/protocol/eth.lua
1
3382
--- Ethernet II frame dissector. -- This module is based on code adapted from nmap's nselib. See http://nmap.org/. -- @classmod coroner.protocol.eth local bstr = require ("coroner/bstr") local eth = {} --- EtherType constants. -- @see eth:get_ethertype eth.ethertype = { ETHERTYPE_IP = 0x0800, -- Internet Protocol version 4 ETHERTYPE_ARP = 0x0806, -- Address Resolution Protocol ETHERTYPE_IPV6 = 0x86DD -- Internet Protocol version 6 } local function eth_ntop (binstr) return ("%02x:%02x:%02x:%02x:%02x:%02x"):format (binstr:byte (1), binstr:byte (2), binstr:byte (3), binstr:byte (4), binstr:byte (5), binstr:byte (6)) end --- Create a new object. -- @tparam string frame pass frame data as an opaque string -- @treturn table New eth table. function eth:new (frame) if type (frame) ~= "string" then error ("parameter 'frame' is not a string", 2) end local eth_frame = setmetatable ({}, { __index = eth }) eth_frame.buff = frame return eth_frame end --- Parse frame data. -- @treturn boolean True on success, false on failure (error message is set). -- @see eth:new -- @see eth:set_frame function eth:parse () if self.buff == nil then self.errmsg = "no data" return false elseif string.len (self.buff) < 14 then self.errmsg = "incomplete Ethernet frame data" return false end self.mac_dst = string.sub (self.buff, 1, 6) self.mac_src = string.sub (self.buff, 7, 12) self.ether_type = bstr.u16 (self.buff, 12) return true end --- Get the module name. -- @treturn string Module name. function eth:type () return "eth" end --- Get raw packet data encapsulated in the frame data. -- @treturn string Raw packet data or an empty string. function eth:get_rawpacket () if string.len (self.buff) > 14 then return string.sub (self.buff, 15, -1) end return "" end --- Change or set new frame data. -- @tparam string frame pass frame data as an opaque string function eth:set_frame (frame) if type (frame) ~= "string" then error ("parameter 'frame' is not a string", 2) end self.buff = frame end --- Get EtherType value from the parsed content. -- @treturn integer Value representing a type of encapsulated packet. -- @see eth.ethertype function eth:get_ethertype () return self.ether_type end --- Get source MAC address from the parsed content. -- @treturn string MAC address formatted as xx:xx:xx:xx:xx:xx string. function eth:get_saddr () return eth_ntop (self.mac_src) end --- Get destination MAC address from the parsed content. -- @treturn string MAC address formatted as xx:xx:xx:xx:xx:xx string. function eth:get_daddr () return eth_ntop (self.mac_dst) end --- Get source MAC address from the parsed content. -- @treturn string Byte string representing a MAC address. function eth:get_rawsaddr () return self.mac_src end --- Get destination MAC address from the parsed content. -- @treturn string Byte string representing a MAC address. function eth:get_rawdaddr () return self.mac_dst end --- Get frame's length. -- @treturn integer Frame length. function eth:get_length () return #self.buff - 14 end --- Get frame's header length. -- @treturn integer Header length. function eth:get_hdrlen () return 14 end --- Get last error message. -- @treturn string Error message. function eth:get_error () return self.errmsg or "no error" end return eth
gpl-2.0
Murloc992/TBCBackporting
Jamba/Jamba/Libs/AceGUI-3.0/widgets/AceGUIContainer-Window.lua
52
9726
local AceGUI = LibStub("AceGUI-3.0") -- Lua APIs local pairs, assert, type = pairs, assert, type -- WoW APIs local PlaySound = PlaySound local CreateFrame, UIParent = CreateFrame, UIParent -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: GameFontNormal ---------------- -- Main Frame -- ---------------- --[[ Events : OnClose ]] do local Type = "Window" local Version = 4 local function frameOnClose(this) this.obj:Fire("OnClose") end local function closeOnClick(this) PlaySound("gsTitleOptionExit") this.obj:Hide() end local function frameOnMouseDown(this) AceGUI:ClearFocus() end local function titleOnMouseDown(this) this:GetParent():StartMoving() AceGUI:ClearFocus() end local function frameOnMouseUp(this) local frame = this:GetParent() frame:StopMovingOrSizing() local self = frame.obj local status = self.status or self.localstatus status.width = frame:GetWidth() status.height = frame:GetHeight() status.top = frame:GetTop() status.left = frame:GetLeft() end local function sizerseOnMouseDown(this) this:GetParent():StartSizing("BOTTOMRIGHT") AceGUI:ClearFocus() end local function sizersOnMouseDown(this) this:GetParent():StartSizing("BOTTOM") AceGUI:ClearFocus() end local function sizereOnMouseDown(this) this:GetParent():StartSizing("RIGHT") AceGUI:ClearFocus() end local function sizerOnMouseUp(this) this:GetParent():StopMovingOrSizing() end local function SetTitle(self,title) self.titletext:SetText(title) end local function SetStatusText(self,text) -- self.statustext:SetText(text) end local function Hide(self) self.frame:Hide() end local function Show(self) self.frame:Show() end local function OnAcquire(self) self.frame:SetParent(UIParent) self.frame:SetFrameStrata("FULLSCREEN_DIALOG") self:ApplyStatus() self:EnableResize(true) self:Show() end local function OnRelease(self) self.status = nil for k in pairs(self.localstatus) do self.localstatus[k] = nil end end -- called to set an external table to store status in local function SetStatusTable(self, status) assert(type(status) == "table") self.status = status self:ApplyStatus() end local function ApplyStatus(self) local status = self.status or self.localstatus local frame = self.frame self:SetWidth(status.width or 700) self:SetHeight(status.height or 500) if status.top and status.left then frame:SetPoint("TOP",UIParent,"BOTTOM",0,status.top) frame:SetPoint("LEFT",UIParent,"LEFT",status.left,0) else frame:SetPoint("CENTER",UIParent,"CENTER") end end local function OnWidthSet(self, width) local content = self.content local contentwidth = width - 34 if contentwidth < 0 then contentwidth = 0 end content:SetWidth(contentwidth) content.width = contentwidth end local function OnHeightSet(self, height) local content = self.content local contentheight = height - 57 if contentheight < 0 then contentheight = 0 end content:SetHeight(contentheight) content.height = contentheight end local function EnableResize(self, state) local func = state and "Show" or "Hide" self.sizer_se[func](self.sizer_se) self.sizer_s[func](self.sizer_s) self.sizer_e[func](self.sizer_e) end local function Constructor() local frame = CreateFrame("Frame",nil,UIParent) local self = {} self.type = "Window" self.Hide = Hide self.Show = Show self.SetTitle = SetTitle self.OnRelease = OnRelease self.OnAcquire = OnAcquire self.SetStatusText = SetStatusText self.SetStatusTable = SetStatusTable self.ApplyStatus = ApplyStatus self.OnWidthSet = OnWidthSet self.OnHeightSet = OnHeightSet self.EnableResize = EnableResize self.localstatus = {} self.frame = frame frame.obj = self frame:SetWidth(700) frame:SetHeight(500) frame:SetPoint("CENTER",UIParent,"CENTER",0,0) frame:EnableMouse() frame:SetMovable(true) frame:SetResizable(true) frame:SetFrameStrata("FULLSCREEN_DIALOG") frame:SetScript("OnMouseDown", frameOnMouseDown) frame:SetScript("OnHide",frameOnClose) frame:SetMinResize(240,240) frame:SetToplevel(true) local titlebg = frame:CreateTexture(nil, "BACKGROUND") titlebg:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Title-Background]]) titlebg:SetPoint("TOPLEFT", 9, -6) titlebg:SetPoint("BOTTOMRIGHT", frame, "TOPRIGHT", -28, -24) local dialogbg = frame:CreateTexture(nil, "BACKGROUND") dialogbg:SetTexture([[Interface\Tooltips\UI-Tooltip-Background]]) dialogbg:SetPoint("TOPLEFT", 8, -24) dialogbg:SetPoint("BOTTOMRIGHT", -6, 8) dialogbg:SetVertexColor(0, 0, 0, .75) local topleft = frame:CreateTexture(nil, "BORDER") topleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) topleft:SetWidth(64) topleft:SetHeight(64) topleft:SetPoint("TOPLEFT") topleft:SetTexCoord(0.501953125, 0.625, 0, 1) local topright = frame:CreateTexture(nil, "BORDER") topright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) topright:SetWidth(64) topright:SetHeight(64) topright:SetPoint("TOPRIGHT") topright:SetTexCoord(0.625, 0.75, 0, 1) local top = frame:CreateTexture(nil, "BORDER") top:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) top:SetHeight(64) top:SetPoint("TOPLEFT", topleft, "TOPRIGHT") top:SetPoint("TOPRIGHT", topright, "TOPLEFT") top:SetTexCoord(0.25, 0.369140625, 0, 1) local bottomleft = frame:CreateTexture(nil, "BORDER") bottomleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) bottomleft:SetWidth(64) bottomleft:SetHeight(64) bottomleft:SetPoint("BOTTOMLEFT") bottomleft:SetTexCoord(0.751953125, 0.875, 0, 1) local bottomright = frame:CreateTexture(nil, "BORDER") bottomright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) bottomright:SetWidth(64) bottomright:SetHeight(64) bottomright:SetPoint("BOTTOMRIGHT") bottomright:SetTexCoord(0.875, 1, 0, 1) local bottom = frame:CreateTexture(nil, "BORDER") bottom:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) bottom:SetHeight(64) bottom:SetPoint("BOTTOMLEFT", bottomleft, "BOTTOMRIGHT") bottom:SetPoint("BOTTOMRIGHT", bottomright, "BOTTOMLEFT") bottom:SetTexCoord(0.376953125, 0.498046875, 0, 1) local left = frame:CreateTexture(nil, "BORDER") left:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) left:SetWidth(64) left:SetPoint("TOPLEFT", topleft, "BOTTOMLEFT") left:SetPoint("BOTTOMLEFT", bottomleft, "TOPLEFT") left:SetTexCoord(0.001953125, 0.125, 0, 1) local right = frame:CreateTexture(nil, "BORDER") right:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]]) right:SetWidth(64) right:SetPoint("TOPRIGHT", topright, "BOTTOMRIGHT") right:SetPoint("BOTTOMRIGHT", bottomright, "TOPRIGHT") right:SetTexCoord(0.1171875, 0.2421875, 0, 1) local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton") close:SetPoint("TOPRIGHT", 2, 1) close:SetScript("OnClick", closeOnClick) self.closebutton = close close.obj = self local titletext = frame:CreateFontString(nil, "ARTWORK") titletext:SetFontObject(GameFontNormal) titletext:SetPoint("TOPLEFT", 12, -8) titletext:SetPoint("TOPRIGHT", -32, -8) self.titletext = titletext local title = CreateFrame("Button", nil, frame) title:SetPoint("TOPLEFT", titlebg) title:SetPoint("BOTTOMRIGHT", titlebg) title:EnableMouse() title:SetScript("OnMouseDown",titleOnMouseDown) title:SetScript("OnMouseUp", frameOnMouseUp) self.title = title local sizer_se = CreateFrame("Frame",nil,frame) sizer_se:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0) sizer_se:SetWidth(25) sizer_se:SetHeight(25) sizer_se:EnableMouse() sizer_se:SetScript("OnMouseDown",sizerseOnMouseDown) sizer_se:SetScript("OnMouseUp", sizerOnMouseUp) self.sizer_se = sizer_se local line1 = sizer_se:CreateTexture(nil, "BACKGROUND") self.line1 = line1 line1:SetWidth(14) line1:SetHeight(14) line1:SetPoint("BOTTOMRIGHT", -8, 8) line1:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") local x = 0.1 * 14/17 line1:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5) local line2 = sizer_se:CreateTexture(nil, "BACKGROUND") self.line2 = line2 line2:SetWidth(8) line2:SetHeight(8) line2:SetPoint("BOTTOMRIGHT", -8, 8) line2:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") local x = 0.1 * 8/17 line2:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5) local sizer_s = CreateFrame("Frame",nil,frame) sizer_s:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-25,0) sizer_s:SetPoint("BOTTOMLEFT",frame,"BOTTOMLEFT",0,0) sizer_s:SetHeight(25) sizer_s:EnableMouse() sizer_s:SetScript("OnMouseDown",sizersOnMouseDown) sizer_s:SetScript("OnMouseUp", sizerOnMouseUp) self.sizer_s = sizer_s local sizer_e = CreateFrame("Frame",nil,frame) sizer_e:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,25) sizer_e:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0) sizer_e:SetWidth(25) sizer_e:EnableMouse() sizer_e:SetScript("OnMouseDown",sizereOnMouseDown) sizer_e:SetScript("OnMouseUp", sizerOnMouseUp) self.sizer_e = sizer_e --Container Support local content = CreateFrame("Frame",nil,frame) self.content = content content.obj = self content:SetPoint("TOPLEFT",frame,"TOPLEFT",12,-32) content:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-12,13) AceGUI:RegisterAsContainer(self) return self end AceGUI:RegisterWidgetType(Type,Constructor,Version) end
gpl-3.0
MonokuroInzanaito/ygopro-777DIY
expansions/script/c11111012.lua
1
1922
--温柔的兔耳少女 小莩 function c11111012.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsSetCard,0x15d),8,2,nil,nil,5) c:EnableReviveLimit() --actlimit local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetRange(LOCATION_MZONE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetCode(EFFECT_CANNOT_ACTIVATE) e1:SetTargetRange(1,1) e1:SetCondition(c11111012.condition) e1:SetValue(c11111012.aclimit) c:RegisterEffect(e1) --immune local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetRange(LOCATION_MZONE) e2:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET) e2:SetCondition(c11111012.condition) e2:SetValue(c11111012.tgvalue) c:RegisterEffect(e2) --remove material local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(11111012,0)) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e3:SetCode(EVENT_PHASE+PHASE_END) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(1) e3:SetCondition(c11111012.rmcon) e3:SetOperation(c11111012.rmop) c:RegisterEffect(e3) --atk local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e4:SetRange(LOCATION_MZONE) e4:SetCode(EFFECT_UPDATE_ATTACK) e4:SetValue(c11111012.atkval) c:RegisterEffect(e4) end function c11111012.condition(e) return e:GetHandler():GetOverlayCount()>0 end function c11111012.aclimit(e,re,tp) return re:IsActiveType(TYPE_SPELL+TYPE_TRAP) end function c11111012.tgvalue(e,re,rp) return rp~=e:GetHandlerPlayer() end function c11111012.rmcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsType(TYPE_XYZ) and e:GetHandler():GetOverlayCount()>0 end function c11111012.rmop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:GetOverlayCount()>0 then c:RemoveOverlayCard(tp,1,1,REASON_EFFECT) end end function c11111012.atkval(e,c) return c:GetOverlayCount()*100 end
gpl-3.0
lhog/Zero-K
LuaRules/Gadgets/unit_enlarger.lua
6
4575
function gadget:GetInfo() return { name = "Unit Enlarger", desc = "Scales units physically and graphically", author = "Rafal", date = "May 2015", license = "GNU LGPL, v2.1 or later", layer = 0, enabled = false } end -------------------------------------------------------------------------------- -- speedups -------------------------------------------------------------------------------- local CMD_DECREASE_SIZE = 33500 local CMD_INCREASE_SIZE = 33501 if (gadgetHandler:IsSyncedCode()) then -------------------------------------------------------------------------------- -- SYNCED -------------------------------------------------------------------------------- local spGetUnitDefID = Spring.GetUnitDefID local spGetUnitTeam = Spring.GetUnitTeam local decreaseSizeCmdDesc = { id = CMD_DECREASE_SIZE, name = "Decrease size", action = "decrease_size", type = CMDTYPE.ICON, tooltip = "Decrease physical unit size", } local increaseSizeCmdDesc = { id = CMD_INCREASE_SIZE, name = "Increase size", action = "increase_size", type = CMDTYPE.ICON, tooltip = "Increase physical unit size", } local LOS_ACCESS = { inlos = true } ------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:Initialize() --gadgetHandler:RegisterCMDID (CMD_DECREASE_SIZE) --gadgetHandler:RegisterCMDID (CMD_INCREASE_SIZE) local allUnits = Spring.GetAllUnits() for i = 1, #allUnits do local unitID = allUnits[i] local udID = spGetUnitDefID(unitID) local team = spGetUnitTeam(unitID) gadget:UnitCreated(unitID, udID, team) end end --[[ local unitData = {} local spInsertUnitCmdDesc = Spring.InsertUnitCmdDesc function gadget:UnitCreated(unitID, unitDefID, team) if UnitDefs[unitDefID].commander then spInsertUnitCmdDesc(unitID, decreaseSizeCmdDesc) spInsertUnitCmdDesc(unitID, increaseSizeCmdDesc) end end function gadget:UnitDestroyed(unitID, unitDefID, unitTeam) unitData[unitID] = nil end function gadget:AllowCommand_GetWantedCommand() return { [CMD_DECREASE_SIZE] = true, [CMD_INCREASE_SIZE] = true } end function gadget:AllowCommand_GetWantedUnitDefID() return true end local spSetUnitRulesParam = Spring.SetUnitRulesParam function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions, cmdTag) if (cmdID == CMD_DECREASE_SIZE or cmdID == CMD_INCREASE_SIZE) then if (not unitData[unitID]) then unitData[unitID] = { scale = 1.0 } end local data = unitData[unitID] local prevScale = data.scale if (cmdID == CMD_DECREASE_SIZE) then data.scale = prevScale - 0.2 else data.scale = prevScale + 0.2 end spSetUnitRulesParam( unitID, "physical_scale", data.scale, LOS_ACCESS ) if (prevScale == 1.0) then SendToUnsynced( "Enlarger_SetUnitLuaDraw", unitID, true ) --spurSetUnitLuaDraw (unitID, true); elseif (data.scale == 1.0) then --spurSetUnitLuaDraw (unitID, false); end return false end return true end ]] -------------------------------------------------------------------------------- -- SYNCED -------------------------------------------------------------------------------- else -------------------------------------------------------------------------------- -- UNSYNCED -------------------------------------------------------------------------------- local spurSetUnitLuaDraw = Spring.UnitRendering.SetUnitLuaDraw local spGetUnitRulesParam = Spring.GetUnitRulesParam local spGetUnitPosition = Spring.GetUnitPosition local glTranslate = gl.Translate local glScale = gl.Scale -------------------------------------------------------------------------------- local function SetUnitLuaDraw(_, unitID, enabled) spurSetUnitLuaDraw (unitID, enabled) end function gadget:Initialize() Spring.UnitRendering.SetUnitLuaDraw (1, true); gadgetHandler:AddSyncAction("Enlarger_SetUnitLuaDraw", SetUnitLuaDraw) end function gadget:Shutdown() gadgetHandler.RemoveSyncAction("Enlarger_SetUnitLuaDraw") end function gadget:DrawUnit(unitID, drawMode) local scale = spGetUnitRulesParam( unitID, "physical_scale" ); if (scale and scale ~= 1.0) then local bx, by, bz = spGetUnitPosition(unitID) --glTranslate( -bx, -by, -bz ) glScale( scale, scale, scale ) --glTranslate( bx, by, bz ) end return false end -------------------------------------------------------------------------------- -- UNSYNCED -------------------------------------------------------------------------------- end
gpl-2.0
lhog/Zero-K
effects/DOT_Merl_explo.lua
7
4213
return { DOT_Merl_Explo = { Dreck = { class = [[CSimpleParticleSystem]], properties = { Texture = [[smokesmall]], colorMap = [[.07 .05 .05 0.80 .00 .00 .00 0.01]], pos = [[0, 1, 0]], gravity = [[0, -0.2, 0]], emitVector = [[0, 1, 0]], emitRot = 0, emitRotSpread = [[5 r20]], sizeGrowth = 0.0, sizeMod = 1.0, airdrag = 1, particleLife = 25, particleLifeSpread = 25, numParticles = 80, particleSpeed = 1, particleSpeedSpread = 5, particleSize = 0.5, particleSizeSpread = 1, directional = false, useAirLos = true, }, air = false, ground = true, water = false, count = 1, }, Rauchwirbel = { class = [[CSimpleParticleSystem]], properties = { Texture = [[smokesmall]], colorMap = [[1.0 1.0 1.0 0.80 0.6 0.6 0.6 0.80 0.0 0.0 0.0 0.01]], pos = [[0, 1, 0]], gravity = [[0.005, 0.001, 0]], emitVector = [[0, 1, 0]], emitRot = 0, emitRotSpread = 90, sizeGrowth = [[0.5 r.5]], sizeMod = 1.0, airdrag = 1, particleLife = 12, particleLifeSpread = 32, numParticles = 12, particleSpeed = 0.5, particleSpeedSpread = 0.65, particleSize = 0.5, particleSizeSpread = 1, directional = false, useAirLos = true, }, air = false, ground = true, water = false, count = 1, }, licht = { class = [[CSimpleGroundFlash]], properties = { texture = [[groundflash]], size = 30, sizeGrowth = 0, ttl = 8, colorMap = [[1 1 1 1.00 0 0 0 0.01]], }, air = false, ground = true, water = false, count = 1, }, Wasserding = { class = [[CSimpleParticleSystem]], properties = { Texture = [[smokesmall]], colorMap = [[1 1 1 0.80 0 0 0 0.01]], pos = [[0, 1, 0]], gravity = [[0, -0.2, 0]], emitVector = [[0, 1, 0]], emitRot = 0, emitRotSpread = [[5 r20]], sizeGrowth = 0.0, sizeMod = 1.0, airdrag = 1, particleLife = 25, particleLifeSpread = 25, numParticles = 80, particleSpeed = 1, particleSpeedSpread = 5, particleSize = 0.5, particleSizeSpread = 1, directional = false, useAirLos = true, }, air = false, ground = false, water = true, underwater = true, count = 1, }, WasserWirbel = { class = [[CSimpleParticleSystem]], properties = { Texture = [[smokesmall]], colorMap = [[1 1 1 0.80 0 0 0 0.01]], pos = [[0, 1, 0]], gravity = [[0, 0.001, 0]], emitVector = [[0, 1, 0]], emitRot = 0, emitRotSpread = 40, sizeGrowth = [[0.5 r.5]], sizeMod = 1.0, airdrag = 1, particleLife = 12, particleLifeSpread = 32, numParticles = 24, particleSpeed = 0.5, particleSpeedSpread = 0.65, particleSize = 0.5, particleSizeSpread = 1, directional = false, useAirLos = true, }, air = false, ground = false, water = true, underwater = true, count = 1, }, Explo = { class = [[CSimpleParticleSystem]], properties = { Texture = [[redexplo]], colorMap = [[1 0.65 0.3 0.005 0 0.00 0.0 0.010]], pos = [[0, 1, 0]], gravity = [[0, -0.5, 0]], emitVector = [[0, 1, 0]], emitRot = 0, emitRotSpread = 360, sizeGrowth = 0, sizeMod = 1.0, airdrag = 1, particleLife = 8, particleLifeSpread = 12, numParticles = 30, particleSpeed = 5, particleSpeedSpread = 3, particleSize = 0.5, particleSizeSpread = 6, directional = false, useAirLos = true, }, air = true, ground = false, water = false, count = 1, }, Explo2 = { class = [[CSimpleParticleSystem]], properties = { Texture = [[gunshot]], colorMap = [[1 0.65 0.3 0.005 1 0.40 0.2 0.005 0 0.00 0.0 0.010]], pos = [[0, 1, 0]], gravity = [[0, -1, 0]], emitVector = [[0, 1, 0]], emitRot = 0, emitRotSpread = 360, sizeGrowth = 0, sizeMod = 1.0, airdrag = 1, particleLife = 8, particleLifeSpread = 16, numParticles = 20, particleSpeed = 14, particleSpeedSpread = 3, particleSize = 8, particleSizeSpread = 6, directional = true, useAirLos = true, }, air = true, ground = false, water = false, count = 1, }, }}
gpl-2.0
MonokuroInzanaito/ygopro-777DIY
expansions/script/c32822004.lua
1
1365
--火舌图腾 local m=32822004 local cm=_G["c"..m] if not orion or not orion.totem then if not pcall(function() require("expansions/script/c32822000") end) then require("script/c32822000") end end function cm.initial_effect(c) local e1=nil --pendulum initial orion.totemInitial(c,true,true) --atk up e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetRange(LOCATION_PZONE) e1:SetTargetRange(LOCATION_MZONE,0) e1:SetValue(1000) c:RegisterEffect(e1) --nehibour atk up e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetRange(LOCATION_MZONE) e1:SetTargetRange(LOCATION_MZONE,0) e1:SetTarget(function(e,c) local seq=e:GetHandler():GetSequence() local tp=e:GetHandler():GetOwner() if seq<0 or seq>4 then return false end local g=Group.CreateGroup() if seq>0 and Duel.GetFieldCard(tp,LOCATION_MZONE,seq-1) then g:AddCard(Duel.GetFieldCard(tp,LOCATION_MZONE,seq-1)) end if seq<4 and Duel.GetFieldCard(tp,LOCATION_MZONE,seq+1) then g:AddCard(Duel.GetFieldCard(tp,LOCATION_MZONE,seq+1)) end return g:IsContains(c) end) e1:SetValue(2000) c:RegisterEffect(e1) --effect reg e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_BE_MATERIAL) e1:SetOperation(orion.totemFlameReg) c:RegisterEffect(e1) end
gpl-3.0
SHIELDPOWER/Shield-Team
bot/utils.lua
646
23489
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0