repo_name
stringlengths
6
78
path
stringlengths
4
206
copies
stringclasses
281 values
size
stringlengths
4
7
content
stringlengths
625
1.05M
license
stringclasses
15 values
FailcoderAddons/supervillain-ui
SVUI_Skins/components/addons/TradeSkillDW.lua
2
5779
--[[ ########################################################## S V U I By: Failcoder ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; local pairs = _G.pairs; local string = _G.string; --[[ STRING METHODS ]]-- local format = string.format; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = _G['SVUI']; local L = SV.L; local MOD = SV.Skins; local Schema = MOD.Schema; --[[ ########################################################## TSDW ########################################################## ]]-- local function StyleTradeSkillDW() assert(TradeSkillDW_QueueFrame, "AddOn Not Loaded") TradeSkillFrame:SetStyle("Frame", "Window2") TradeSkillListScrollFrameScrollBar:RemoveTextures(true) TradeSkillDetailScrollFrameScrollBar:RemoveTextures(true) TradeSkillFrameInset:RemoveTextures(true) TradeSkillExpandButtonFrame:RemoveTextures(true) TradeSkillDetailScrollChildFrame:RemoveTextures(true) TradeSkillListScrollFrameScrollBar:RemoveTextures(true) SV.API:Set("Frame", TradeSkillGuildFrame,"Transparent") SV.API:Set("Frame", TradeSkillGuildFrameContainer,"Transparent") TradeSkillGuildFrame:SetPoint("BOTTOMLEFT", TradeSkillFrame, "BOTTOMRIGHT", 3, 19) SV.API:Set("CloseButton", TradeSkillGuildFrameCloseButton) TradeSkillFrame:HookScript("OnShow", function() SV.API:Set("Frame", TradeSkillFrame) TradeSkillListScrollFrameScrollBar:RemoveTextures() if not TradeSkillDWExpandButton then return end if not TradeSkillDWExpandButton.styled then SV.API:Set("PageButton", TradeSkillDWExpandButton) TradeSkillDWExpandButton.styled = true end end) TradeSkillFrame:SetHeight(TradeSkillFrame:GetHeight() + 12) TradeSkillRankFrame:SetStyle("Frame", 'Transparent') TradeSkillRankFrame:SetStatusBarTexture(SV.media.statusbar.default) TradeSkillCreateButton:SetStyle("Button") TradeSkillCancelButton:SetStyle("Button") TradeSkillFilterButton:SetStyle("Button") TradeSkillCreateAllButton:SetStyle("Button") TradeSkillViewGuildCraftersButton:SetStyle("Button") TradeSkillLinkButton:GetNormalTexture():SetTexCoord(0.25, 0.7, 0.37, 0.75) TradeSkillLinkButton:GetPushedTexture():SetTexCoord(0.25, 0.7, 0.45, 0.8) TradeSkillLinkButton:GetHighlightTexture():Die() SV.API:Set("Frame", TradeSkillLinkButton,"Transparent") TradeSkillLinkButton:SetSize(17, 14) TradeSkillLinkButton:SetPoint("LEFT", TradeSkillLinkFrame, "LEFT", 5, -1) TradeSkillFrameSearchBox:SetStyle("Editbox") TradeSkillInputBox:SetStyle("Editbox") TradeSkillIncrementButton:SetPoint("RIGHT", TradeSkillCreateButton, "LEFT", -13, 0) SV.API:Set("CloseButton", TradeSkillFrameCloseButton) SV.API:Set("ScrollBar", TradeSkillDetailScrollFrameScrollBar) local once = false hooksecurefunc("TradeSkillFrame_SetSelection", function(id) TradeSkillSkillIcon:SetStyle("Button") if TradeSkillSkillIcon:GetNormalTexture() then TradeSkillSkillIcon:GetNormalTexture():SetTexCoord(0.1,0.9,0.1,0.9) TradeSkillSkillIcon:GetNormalTexture():ClearAllPoints() TradeSkillSkillIcon:GetNormalTexture():SetPoint("TOPLEFT", 2, -2) TradeSkillSkillIcon:GetNormalTexture():SetPoint("BOTTOMRIGHT", -2, 2) end for i = 1, MAX_TRADE_SKILL_REAGENTS do local button = _G["TradeSkillReagent"..i] local icon = _G["TradeSkillReagent"..i.."IconTexture"] local count = _G["TradeSkillReagent"..i.."Count"] icon:SetTexCoord(0.1,0.9,0.1,0.9) icon:SetDrawLayer("OVERLAY") if not icon.backdrop then icon.backdrop = CreateFrame("Frame", nil, button) icon.backdrop:SetFrameLevel(button:GetFrameLevel() - 1) SV.API:Set("Frame", icon.backdrop,"Transparent") icon.backdrop:SetPoint("TOPLEFT", icon, "TOPLEFT", -2, 2) icon.backdrop:SetPoint("BOTTOMRIGHT", icon, "BOTTOMRIGHT", 2, -2) end icon:SetParent(icon.backdrop) count:SetParent(icon.backdrop) count:SetDrawLayer("OVERLAY") if i > 2 and once == false then local point, anchoredto, point2, x, y = button:GetPoint() button:ClearAllPoints() button:SetPoint(point, anchoredto, point2, x, y - 3) once = true end _G["TradeSkillReagent"..i.."NameFrame"]:Die() end end) TradeSkillDW_QueueFrame:HookScript("OnShow", function() SV.API:Set("Frame", TradeSkillDW_QueueFrame,"Transparent") end) SV.API:Set("CloseButton", TradeSkillDW_QueueFrameCloseButton) TradeSkillDW_QueueFrameInset:RemoveTextures() TradeSkillDW_QueueFrameClear:SetStyle("Button") TradeSkillDW_QueueFrameDown:SetStyle("Button") TradeSkillDW_QueueFrameUp:SetStyle("Button") TradeSkillDW_QueueFrameDo:SetStyle("Button") TradeSkillDW_QueueFrameDetailScrollFrameScrollBar:RemoveTextures() TradeSkillDW_QueueFrameDetailScrollFrameChildFrame:RemoveTextures() TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent1:RemoveTextures() TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent2:RemoveTextures() TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent3:RemoveTextures() TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent4:RemoveTextures() TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent5:RemoveTextures() TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent6:RemoveTextures() TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent7:RemoveTextures() TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent8:RemoveTextures() SV.API:Set("ScrollBar", TradeSkillDW_QueueFrameDetailScrollFrameScrollBar) TradeSkillListScrollFrameScrollBar:RemoveTextures() end --[[#################################################]]-- MOD:SaveAddonStyle("TradeSkillDW", StyleTradeSkillDW)
mit
nesstea/darkstar
scripts/globals/mobskills/Chains_of_Rage.lua
18
1157
--------------------------------------------- -- Chains of Apathy -- --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/keyitems"); require("scripts/zones/Empyreal_Paradox/TextIDs"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local targets = mob:getEnmityList(); for i,v in pairs(targets) do if (v:isPC()) then local race = v:getRace() if (race == 8) and not v:hasKeyItem(LIGHT_OF_ALTAIEU) then mob:showText(mob, PROMATHIA_TEXT + 4); return 0; end end end return 1; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_TERROR; local power = 30; local duration = 30; if target:isPC() and ((target:getRace() == 8) and not target:hasKeyItem(LIGHT_OF_ALTAIEU)) then skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, power, 0, duration)); else skill:setMsg(MSG_NO_EFFECT); end return typeEffect; end;
gpl-3.0
nesstea/darkstar
scripts/zones/Lower_Jeuno/npcs/Tuh_Almobankha.lua
27
4090
----------------------------------- -- Area: Lower Jeuno -- NPC: Tuh Almobankha -- Title Change NPC -- @pos -14 0 -61 245 ----------------------------------- require("scripts/globals/titles"); local title2 = { BROWN_MAGE_GUINEA_PIG , BROWN_MAGIC_BYPRODUCT , RESEARCHER_OF_CLASSICS , TORCHBEARER , FORTUNETELLER_IN_TRAINING , CHOCOBO_TRAINER , CLOCK_TOWER_PRESERVATIONIST , LIFE_SAVER , CARD_COLLECTOR , TWOS_COMPANY , TRADER_OF_ANTIQUITIES , GOBLINS_EXCLUSIVE_FASHION_MANNEQUIN , TENSHODO_MEMBER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { ACTIVIST_FOR_KINDNESS , ENVOY_TO_THE_NORTH , EXORCIST_IN_TRAINING , FOOLS_ERRAND_RUNNER , STREET_SWEEPER , MERCY_ERRAND_RUNNER , BELIEVER_OF_ALTANA , TRADER_OF_MYSTERIES , WANDERING_MINSTREL , ANIMAL_TRAINER , HAVE_WINGS_WILL_FLY , ROD_RETRIEVER , DESTINED_FELLOW , TROUPE_BRILIOTH_DANCER , PROMISING_DANCER , STARDUST_DANCER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { TIMEKEEPER , BRINGER_OF_BLISS , PROFESSIONAL_LOAFER , TRADER_OF_RENOWN , HORIZON_BREAKER , SUMMIT_BREAKER , BROWN_BELT , DUCAL_DUPE , CHOCOBO_LOVE_GURU , PICKUP_ARTIST , WORTHY_OF_TRUST , A_FRIEND_INDEED , CHOCOROOKIE , CRYSTAL_STAKES_CUPHOLDER , WINNING_OWNER , VICTORIOUS_OWNER , TRIUMPHANT_OWNER , HIGH_ROLLER , FORTUNES_FAVORITE , CHOCOCHAMPION , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { PARAGON_OF_BEASTMASTER_EXCELLENCE , PARAGON_OF_BARD_EXCELLENCE , SKY_BREAKER , BLACK_BELT , GREEDALOX , CLOUD_BREAKER , STAR_BREAKER , ULTIMATE_CHAMPION_OF_THE_WORLD , DYNAMISJEUNO_INTERLOPER , DYNAMISBEAUCEDINE_INTERLOPER , DYNAMISXARCABARD_INTERLOPER , DYNAMISQUFIM_INTERLOPER , CONQUEROR_OF_FATE , SUPERHERO , SUPERHEROINE , ELEGANT_DANCER , DAZZLING_DANCE_DIVA , GRIMOIRE_BEARER , FELLOW_FORTIFIER , BUSHIN_ASPIRANT , BUSHIN_RYU_INHERITOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { GRAND_GREEDALOX , SILENCER_OF_THE_ECHO , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title7 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x271E,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); 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==0x271E) then if (option > 0 and option <29) then if (player:delGil(400)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(500)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(600)) then player:setTitle( title4[option - 512] ) end elseif (option > 768 and option <797) then if (player:delGil(700)) then player:setTitle( title5[option - 768] ) end elseif (option > 1024 and option < 1053) then if (player:delGil(800)) then player:setTitle( title6[option - 1024] ) end end end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Yorcia_Weald_U/Zone.lua
19
1065
----------------------------------- -- -- Zone: Yorcia Weald U -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Yorcia_Weald_U/TextIDs"] = nil; require("scripts/zones/Yorcia_Weald_U/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; 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
FailcoderAddons/supervillain-ui
SVUI_UnitFrames/libs/oUF_1.6.9/elements/combat.lua
7
1931
--[[ Element: Combat Icon Toggles the visibility of `self.Combat` based on the player's combat status. Widget Combat - Any UI widget. Notes The default assistant icon will be applied if the UI widget is a texture and doesn't have a texture or color defined. Examples -- Position and size local Combat = self:CreateTexture(nil, "OVERLAY") Combat:SetSize(16, 16) Combat:SetPoint('TOP', self) -- Register it with oUF self.Combat = Combat Hooks Override(self) - Used to completely override the internal update function. Removing the table key entry will make the element fall-back to its internal function again. ]] local parent, ns = ... local oUF = ns.oUF local Update = function(self, event) local combat = self.Combat if(combat.PreUpdate) then combat:PreUpdate() end local inCombat = UnitAffectingCombat('player') if(inCombat) then combat:Show() else combat:Hide() end if(combat.PostUpdate) then return combat:PostUpdate(inCombat) end end local Path = function(self, ...) return (self.Combat.Override or Update) (self, ...) end local ForceUpdate = function(element) return Path(element.__owner, 'ForceUpdate') end local Enable = function(self, unit) local combat = self.Combat if(combat and unit == 'player') then combat.__owner = self combat.ForceUpdate = ForceUpdate self:RegisterEvent("PLAYER_REGEN_DISABLED", Path, true) self:RegisterEvent("PLAYER_REGEN_ENABLED", Path, true) if(combat:IsObjectType"Texture" and not combat:GetTexture()) then combat:SetTexture[[Interface\CharacterFrame\UI-StateIcon]] combat:SetTexCoord(.5, 1, 0, .49) end return true end end local Disable = function(self) if(self.Combat) then self.Combat:Hide() self:UnregisterEvent("PLAYER_REGEN_DISABLED", Path) self:UnregisterEvent("PLAYER_REGEN_ENABLED", Path) end end oUF:AddElement('Combat', Path, Enable, Disable)
mit
UnfortunateFruit/darkstar
scripts/globals/spells/bio_iv.lua
7
2047
----------------------------------------- -- Spell: Bio IV -- Deals dark damage that weakens an enemy's attacks and gradually reduces its HP. ----------------------------------------- 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) --calculate raw damage local basedmg = caster:getSkillLevel(DARK_MAGIC_SKILL) / 4; local dmg = calculateMagicDamage(basedmg,3,caster,spell,target,DARK_MAGIC_SKILL,MOD_INT,false); -- Softcaps at 32, should always do at least 1 if(dmg > 80) then dmg = 80; end if(dmg < 1) then dmg = 1; end --get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),DARK_MAGIC_SKILL,1.0); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg); --add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); --add in final adjustments including the actual damage dealt local final = finalMagicAdjustments(caster,target,spell,dmg); -- Calculate duration. local duration = 180; -- Check for Dia. local dia = target:getStatusEffect(EFFECT_DIA); -- Calculate DoT (rough, though fairly accurate) local dotdmg = 5 + math.floor(caster:getSkillLevel(DARK_MAGIC_SKILL) / 60); -- Do it! if(dia == nil or (BIO_OVERWRITE == 0 and dia:getPower() <= 4) or (BIO_OVERWRITE == 1 and dia:getPower() < 4)) then target:delStatusEffect(EFFECT_BIO); -- delete old bio target:addStatusEffect(EFFECT_BIO,dotdmg,3,duration,FLAG_ERASABLE, 20); end --Try to kill same tier Dia (default behavior) if(DIA_OVERWRITE == 1 and dia ~= nil) then if(dia:getPower() <= 4) then target:delStatusEffect(EFFECT_DIA); end end return final; end;
gpl-3.0
nesstea/darkstar
scripts/zones/RuLude_Gardens/npcs/Albiona.lua
13
1382
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Albiona -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/zones/RuLude_Gardens/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,0) == false) then player:startEvent(10089); else player:startEvent(0x0092); 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 == 10089) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",0,true); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/LaLoff_Amphitheater/npcs/qm1_2.lua
13
2440
----------------------------------- -- Area: LaLoff_Amphitheater -- NPC: Shimmering Circle (BCNM Entrances) ------------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; package.loaded["scripts/globals/bcnm"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/LaLoff_Amphitheater/TextIDs"); -- Death cutscenes: -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,0,0); -- hume -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,1,0); -- taru -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,2,0); -- mithra -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,3,0); -- elvaan -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,4,0); -- galka -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,5,0); -- divine might -- param 1: entrance # -- param 2: fastest time -- param 3: unknown -- param 4: clear time -- param 5: zoneid -- param 6: exit cs (0-4 AA, 5 DM, 6-10 neo AA, 11 neo DM) -- param 7: skip (0 - no skip, 1 - prompt, 2 - force) -- param 8: 0 ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option,2)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
Spartan322/finalfrontier
gamemode/sgui/shields.lua
3
6607
-- Copyright (c) 2014 James King [metapyziks@gmail.com] -- -- This file is part of Final Frontier. -- -- Final Frontier is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of -- the License, or (at your option) any later version. -- -- Final Frontier 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 Lesser General Public License -- along with Final Frontier. If not, see <http://www.gnu.org/licenses/>. local BASE = "page" local ICON_SIZE = 48 local ICON_PADDING = 16 GUI.BaseName = BASE GUI._shipview = nil GUI._curroom = nil GUI._roomelems = nil GUI._powerbar = nil function GUI:GetCurrentRoom() return self._curroom end function GUI:SetCurrentRoom(room) self._curroom = room if self._roomelems then for _, elem in pairs(self._roomelems) do elem:Remove() end self._roomelems = nil end if room then if self._powerbar then self._powerbar:Remove() self._powerbar = nil end self._roomelems = {} self._roomelems.slider = sgui.Create(self, "slider") self._roomelems.slider:SetOrigin(ICON_PADDING, self:GetHeight() - ICON_SIZE - ICON_PADDING) self._roomelems.slider:SetSize(self:GetWidth() / 2 - ICON_PADDING, ICON_SIZE) self._roomelems.slider.Color = Color(45, 51, 172, 191) if SERVER then self._roomelems.slider.Value = self:GetSystem():GetDistrib(room) function self._roomelems.slider.OnValueChanged(slider, value) self:GetSystem():SetDistrib(room, value) self:GetScreen():UpdateLayout() end end self._roomelems.supplied = sgui.Create(self, "label") self._roomelems.supplied:SetOrigin(self._roomelems.slider:GetRight() + ICON_PADDING, self._roomelems.slider:GetTop()) self._roomelems.supplied:SetSize(self:GetWidth() - self._roomelems.supplied:GetLeft() - ICON_PADDING * 2 - ICON_SIZE, ICON_SIZE) if CLIENT then self._roomelems.supplied.AlignX = TEXT_ALIGN_CENTER self._roomelems.supplied.AlignY = TEXT_ALIGN_CENTER self._roomelems.supplied.Text = "" end self._roomelems.close = sgui.Create(self, "button") self._roomelems.close:SetOrigin(self:GetWidth() - ICON_PADDING - ICON_SIZE, self._roomelems.slider:GetTop()) self._roomelems.close:SetSize(ICON_SIZE, ICON_SIZE) self._roomelems.close.Text = "X" if SERVER then function self._roomelems.close.OnClick(btn) self:SetCurrentRoom(nil) return true end end else if not self._powerbar then self._powerbar = sgui.Create(self, "powerbar") self._powerbar:SetOrigin(ICON_PADDING, self:GetHeight() - ICON_SIZE - ICON_PADDING) self._powerbar:SetSize(self:GetWidth() - ICON_PADDING * 2, ICON_SIZE) end end if SERVER then self:GetScreen():UpdateLayout() end end function GUI:Enter() self.Super[BASE].Enter(self) self._shipview = sgui.Create(self, "shipview") self._shipview:SetCurrentShip(self:GetShip()) self._shipview:SetBounds(Bounds( ICON_PADDING, ICON_PADDING * 0.5, self:GetWidth() - ICON_PADDING * 2, self:GetHeight() - ICON_PADDING * 2.5 - ICON_SIZE )) for _, room in pairs(self._shipview:GetRoomElements()) do room.CanClick = true room.shieldDial = sgui.Create(self, "dualdial") if SERVER then function room.OnClick(room) if self._curroom == room:GetCurrentRoom() then self:SetCurrentRoom(nil) else self:SetCurrentRoom(room:GetCurrentRoom()) end return true end room.shieldDial:SetTargetValue(self:GetSystem():GetDistrib(room:GetCurrentRoom())) room.shieldDial:SetCurrentValue(room:GetCurrentRoom():GetUnitShields() / room:GetCurrentRoom():GetSurfaceArea()) elseif CLIENT then function room.GetRoomColor(room) if room:GetCurrentRoom() == self._curroom then local glow = Pulse(0.5) * 32 + 32 return Color(glow, glow, glow, 255) else return Color(32, 32, 32, 255) end end room.shieldDial:SetGlobalBounds(room:GetIconBounds()) local w, h = room.shieldDial:GetSize() room.shieldDial:SetSize(w * 2, h * 2) room.shieldDial:SetInnerRatio(0.625) room.shieldDial:SetCentre(room.shieldDial:GetLeft() + w / 2, room.shieldDial:GetTop() + h / 2) room.shieldDial.TargetColour = Color(45, 51, 172, 32) room.shieldDial.CurrentColour = Color(45, 51, 172, 127) end end self._powerbar = nil self:SetCurrentRoom(nil) end if SERVER then function GUI:UpdateLayout(layout) self.Super[BASE].UpdateLayout(self, layout) for _, room in pairs(self._shipview:GetRoomElements()) do room.shieldDial:SetTargetValue(self:GetSystem():GetDistrib(room:GetCurrentRoom())) end if self._curroom then layout.room = self._curroom:GetName() else layout.room = nil end end elseif CLIENT then function GUI:UpdateLayout(layout) if layout.room and (not self._curroom or self._curroom:GetName() ~= layout.room) then self:SetCurrentRoom(ships.GetRoomByName(layout.room)) elseif self._curroom and not layout.room then self:SetCurrentRoom(nil) end if layout.room then self._roomelems.supplied.Text = FormatNum(self._curroom:GetUnitShields(), 1, 2) .. "kT / " .. FormatNum(self._curroom:GetSurfaceArea(), 1, 2) .. "kT" end self.Super[BASE].UpdateLayout(self, layout) for _, room in pairs(self._shipview:GetRoomElements()) do if room.shieldDial then room.shieldDial:SetCurrentValue(room:GetCurrentRoom():GetUnitShields() / room:GetCurrentRoom():GetSurfaceArea()) end end end end
lgpl-3.0
trilastiko/keys
VSCOKeys.lrdevplugin/ActivateKeys.lua
11
1463
--[[---------------------------------------------------------------------------- VSCO Keys for Adobe Lightroom Copyright (C) 2015 Visual Supply Company Licensed under GNU GPLv2 (or any later version). 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ------------------------------------------------------------------------------]] local logging = require "Logging.lua" local LrDialogs = import 'LrDialogs' -------------------------------------------------------------------------------- -- Display a modal information dialog. local function showModalDialog() logging:log( "Activate Keys LR3 requested." ) LrDialogs.message( "LR3 Activated", "VSCO Keys for LR3 has been activated.", "info" ) end -------------------------------------------------------------------------------- -- Display a dialog. showModalDialog()
gpl-2.0
NezzKryptic/Wire-Extras
lua/weapons/gmod_tool/stools/wire_useholoemitter.lua
2
4635
TOOL.Category = "Wire Extras/Visuals/Holographic" TOOL.Name = "Interactable Holography Emitter" TOOL.Command = nil TOOL.ConfigName = "" TOOL.Tab = "Wire" if CLIENT then language.Add( "Tool.wire_useholoemitter.name", "Interactable Holographic Emitter Tool (Wire)" ) language.Add( "Tool.wire_useholoemitter.desc", "The emitter required for interactable holographic projections" ) language.Add( "Tool.wire_useholoemitter.0", "Primary: Create emitter Secondary: Link emitter" ) language.Add( "Tool.wire_useholoemitter.1", "Select the emitter point to link to." ) language.Add( "Tool_wire_useholoemitter_showbeams", "Show beams" ) language.Add( "Tool_wire_useholoemitter_groundbeams", "Show Emitter->Point beams" ) language.Add( "Tool_wire_useholoemitter_size", "Point size" ) language.Add( "Tool_wire_useholoemitter_minimum_fade_rate", "CLIENT: Minimum Fade Rate - Applyed to all holoemitters" ) language.Add( "sboxlimit_wire_useholoemitters", "You've hit the holoemitters limit!" ) language.Add("Undone_gmod_wire_useholoemitter", "Undone Wire Interactable Holoemitter" ) end if SERVER then CreateConVar( "sbox_maxwire_useholoemitters", 5 ) end TOOL.Model = "models/jaanus/wiretool/wiretool_range.mdl" TOOL.Emitter = nil TOOL.NoGhostOn = { "gmod_wire_hologrid" } timer.Simple(0,function() function _my2(TOOL) setmetatable(TOOL, WireToolObj) end end) TOOL.WireClass = "gmod_wire_useholoemitter" TOOL.ClientConVar = { r = "255", g = "255", b = "255", a = "255", showbeams = "1", groundbeams = "0", size = "4" } function TOOL:RightClick( tr ) if( !tr.HitNonWorld || tr.Entity:GetClass() != "gmod_wire_useholoemitter" ) then return false end if CLIENT then return true end self.Emitter = tr.Entity return true end function TOOL.BuildCPanel( panel ) WireToolHelpers.MakePresetControl(panel, "wire_useholoemitter") panel:CheckBox("#Tool_wire_useholoemitter_showbeams", "wire_useholoemitter_showbeams") panel:CheckBox("#Tool_wire_useholoemitter_groundbeams", "wire_useholoemitter_groundbeams") panel:NumSlider("#Tool_wire_useholoemitter_size","wire_useholoemitter_size", 1, 32, 1) panel:AddControl( "Color", { Label = "Color", Red = "wire_useholoemitter_r", Green = "wire_useholoemitter_g", Blue = "wire_useholoemitter_b", Alpha = "wire_useholoemitter_a", ShowAlpha = "1", ShowHSV = "1", ShowRGB = "1", Multiplier = "255", }) if(not game.SinglePlayer()) then panel:NumSlider("#Tool_wire_useholoemitter_minimum_fade_rate", "cl_wire_useholoemitter_minfaderate", 0.1, 100, 1) end end if SERVER then function WireToolMakeUseEmitter( self, tr, pl ) local r = self:GetClientNumber( "r" ); local g = self:GetClientNumber( "g" ); local b = self:GetClientNumber( "b" ); local a = self:GetClientNumber( "a" ); local size = self:GetClientNumber( "size" ); local showbeams = util.tobool( self:GetClientNumber( "showbeams" ) ); local groundbeams = util.tobool( self:GetClientNumber( "groundbeams" ) ); // did we hit another holoemitter? if( tr.HitNonWorld && tr.Entity:GetClass() == "gmod_wire_useholoemitter" ) then // update it. tr.Entity:SetColor( Color(r, g, b, a) ); // update size and show states tr.Entity:SetNetworkedBool( "ShowBeam", showbeams ); tr.Entity:SetNetworkedBool( "GroundBeam", groundbeams ); tr.Entity:SetNetworkedFloat( "PointSize", size ); tr.Entity.r = r tr.Entity.g = g tr.Entity.b = b tr.Entity.a = a tr.Entity.showbeams = showbeams tr.Entity.groundbeams = groundbeams tr.Entity.size = size return true; end // we linking? if( tr.HitNonWorld && tr.Entity:IsValid() && tr.Entity:GetClass() == "gmod_wire_hologrid" ) then // link to this point. if( self.Emitter && self.Emitter:IsValid() ) then // link. self.Emitter:LinkToGrid( tr.Entity ); // reset selected emitter self.Emitter = nil; // return true; else // prevent effects return false; end end // create a holo emitter. if( !self:GetSWEP():CheckLimit( "wire_useholoemitters" ) ) then return false; end // fix angle local ang = tr.HitNormal:Angle(); ang.pitch = ang.pitch + 90; // create emitter local emitter = MakeWireUseHoloemitter( pl, tr.HitPos, ang, r, g, b, a, showbeams, groundbeams, size ); // pull it out of the spawn point local mins = emitter:OBBMins(); emitter:SetPos( tr.HitPos - tr.HitNormal * mins.z ); return emitter end TOOL.LeftClick_Make = WireToolMakeUseEmitter end
gpl-3.0
nesstea/darkstar
scripts/zones/Balgas_Dais/bcnms/saintly_invitation.lua
27
2028
----------------------------------- -- Area: Horlais Peak -- Name: Saintly Invitation -- @pos 299 -123 345 146 ----------------------------------- package.loaded["scripts/zones/Balgas_Dais/TextIDs"] = nil; ------------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Balgas_Dais/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasCompletedMission(WINDURST,SAINTLY_INVITATION)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then if (player:getCurrentMission(WINDURST) == SAINTLY_INVITATION) then player:addTitle(VICTOR_OF_THE_BALGA_CONTEST); player:addKeyItem(BALGA_CHAMPION_CERTIFICATE); player:messageSpecial(KEYITEM_OBTAINED,BALGA_CHAMPION_CERTIFICATE); player:setVar("MissionStatus",2); end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Mathlouq.lua
37
1029
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Mathlouq -- Type: Standard NPC -- @pos -92.892 -7 129.277 50 ----------------------------------- 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(0x021f); 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
PUMpITapp/instantpizza
src/Menu.lua
1
3294
--- Tells if the program shall be run on the box or not local onBox = false --- Checks if the file was called from a test file. -- @return true if called from a test file, indicating the file is being tested, else false function checkTestMode() runFile = debug.getinfo(2, "S").source:sub(2,3) if (runFile ~= './' ) then underGoingTest = false elseif (runFile == './') then underGoingTest = true end return underGoingTest end --- Chooses either the actual or the dummy gfx. -- @return tempGfx Returns dummy gfx if the file is being tested, returns actual gfx if the file is being run. function chooseGfx() if not checkTestMode() then tempGfx = require "gfx" elseif checkTestMode() then tempGfx = require "gfx_stub" end return tempGfx end --- Checks if the program is run on the box or not if onBox == true then package.path = package.path .. ';' .. sys.root_path() .. 'Images/MenuPics/?.png' dir = sys.root_path() else gfx = chooseGfx(checkTestMode()) sys = {} sys.root_path = function () return '' end dir = "" end --- Variable that is triggered if a user has edited or created an account local accountAction = ... --- Declare units in variables local xUnit = gfx.screen:get_width()/16 local yUnit = gfx.screen:get_height()/9 --- Function that builds the GUI function buildGUI() local backgroundPNG = gfx.loadpng("Images/MenuPics/menu.png") backgroundPNG:premultiply() gfx.screen:copyfrom(backgroundPNG, nil, {x=0 , y=0, w=gfx.screen:get_width(), h=gfx.screen:get_height()}) backgroundPNG:destroy() addNotification() gfx.update() end --- Gets input from user and re-directs according to input -- @param key The key that has been pressed -- @param state The state of the key-press -- @return pathName The path that the program shall be directed to function onKey(key,state) if(state == 'up') then if(key == 'red') then --Go to Create Account pathName = dir .. "ManageAccounts.lua" if checkTestMode() then return pathName else dofile(pathName) end elseif(key == 'yellow') then -- Go to About pathName = dir .. "Tutorial.lua" if checkTestMode() then return pathName else dofile(pathName) end elseif(key == 'blue') then -- Go to order steps pathName = dir .. "OrderStep1.lua" if checkTestMode() then return pathName else dofile(pathName) end end end end --- Function that is triggered when an account is edited or created that alerts the user about the action function addNotification() if accountAction == "Edit" then local backgroundPNG = gfx.loadpng("Images/MenuPics/editaccount.png") backgroundPNG:premultiply() gfx.screen:copyfrom(backgroundPNG, nil, {x=xUnit*3.08 , y=yUnit*4.66, w=xUnit*2.5, h=yUnit*3.75},true) backgroundPNG:destroy() elseif (accountAction == "Create") then local backgroundPNG = gfx.loadpng("Images/MenuPics/anewaccount.png") backgroundPNG:premultiply() gfx.screen:copyfrom(backgroundPNG, nil, {x=xUnit*3.08 , y=yUnit*4.66, w=xUnit*2.5, h=yUnit*3.75},true) backgroundPNG:destroy() end end --- Main method function onStart() buildGUI() end onStart()
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Konschtat_Highlands/npcs/qm1.lua
34
1376
----------------------------------- -- Area: Konschtat Highlands -- NPC: qm1 (???) -- Continues Quests: Past Perfect -- @pos -201 16 80 108 ----------------------------------- package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Konschtat_Highlands/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local PastPerfect = player:getQuestStatus(BASTOK,PAST_PERFECT); if (PastPerfect == QUEST_ACCEPTED) then player:addKeyItem(0x6d); player:messageSpecial(KEYITEM_OBTAINED,0x6d); -- Tattered Mission Orders else player:messageSpecial(FIND_NOTHING); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
johnmccabe/dockercraft
world/Plugins/Core/regen.lua
6
1937
-- regen.lua -- Implements the in-game and console commands for chunk regeneration function HandleRegenCommand(a_Split, a_Player) -- Check the params: local numParams = #a_Split if (numParams == 2) or (numParams > 3) then SendMessage(a_Player, "Usage: '" .. a_Split[1] .. "' or '" .. a_Split[1] .. " <chunk x> <chunk z>'" ) return true end -- Get the coords of the chunk to regen: local chunkX = a_Player:GetChunkX() local chunkZ = a_Player:GetChunkZ() if (numParams == 3) then chunkX = tonumber(a_Split[2]) chunkZ = tonumber(a_Split[3]) if (chunkX == nil) then SendMessageFailure(a_Player, "Not a number: '" .. a_Split[2] .. "'") return true end if (chunkZ == nil) then SendMessageFailure(a_Player, "Not a number: '" .. a_Split[3] .. "'") return true end end -- Regenerate the chunk: SendMessageSuccess(a_Player, "Regenerating chunk [" .. chunkX .. ", " .. chunkZ .. "]...") a_Player:GetWorld():RegenerateChunk(chunkX, chunkZ) return true end function HandleConsoleRegen(a_Split) -- Check the params: local numParams = #a_Split if ((numParams ~= 3) and (numParams ~= 4)) then return true, "Usage: " .. a_Split[1] .. " <chunk x> <chunk z> [world]" end -- Get the coords of the chunk to regen: local chunkX = tonumber(a_Split[2]) if (chunkX == nil) then return true, "Not a number: '" .. a_Split[2] .. "'" end local chunkZ = tonumber(a_Split[3]) if (chunkZ == nil) then return true, "Not a number: '" .. a_Split[3] .. "'" end -- Get the world to regen: local world if (a_Split[4] == nil) then world = cRoot:Get():GetDefaultWorld() else world = cRoot:Get():GetWorld(a_Split[4]) if (world == nil) then return true, "There's no world named '" .. a_Split[4] .. "'." end end -- Regenerate the chunk: world:RegenerateChunk(chunkX, chunkZ) return true, "Regenerating chunk [" .. chunkX .. ", " .. chunkZ .. "] in world " .. world:GetName() end
apache-2.0
UnfortunateFruit/darkstar
scripts/globals/pathfind.lua
19
2549
-- Util methods for pathfinding pathfind = {}; PATHFLAG_NONE = 0 PATHFLAG_RUN = 1 PATHFLAG_WALLHACK = 2 PATHFLAG_REVERSE = 4 -- returns the point at the given index function pathfind.get(points, index) local pos = {}; if(index < 0) then index = (#points + index - 2) / 3; end pos[1] = points[index*3-2]; pos[2] = points[index*3-1]; pos[3] = points[index*3]; return pos; end; function pathfind.length(points) return #points / 3; end function pathfind.first(points) return pathfind.get(points, 1); end; function pathfind.equal(point1, point2) return point1[1] == point2[1] and point1[2] == point2[2] and point1[3] == point2[3]; end; -- returns the last point function pathfind.last(points) local length = #points; return pathfind.get(points, length/3); end; -- returns a random point from given point array function pathfind.random(points) local length = #points; return pathfind.get(points, math.random(1, length)); end; -- returns the start path without the first element function pathfind.fromStart(points, start) start = start or 1; local t2 = {} local maxLength = 50; local length = pathfind.length(points); local count = 1; local pos = start + 1; local index = 1; while pos <= length and count <= maxLength do local pt = pathfind.get(points, pos); t2[index] = pt[1]; t2[index+1] = pt[2]; t2[index+2] = pt[3]; pos = pos + 1; count = count + 1; index = index + 3; end return t2 end; -- reverses the array and removes the first element function pathfind.fromEnd(points, start) start = start or 1 local t2 = {} -- do not add the last element local length = #points / 3; start = length - start; local index = 1; for i=start,1,-1 do local pt = pathfind.get(points, i); t2[index] = pt[1] t2[index+1] = pt[2] t2[index+2] = pt[3] index = index + 3 if(i > 50) then break; end end return t2 end; -- continusly runs the path function pathfind.patrol(npc, points, flags) if(npc:atPoint(pathfind.first(points)) or npc:atPoint(pathfind.last(points))) then npc:pathThrough(pathfind.fromStart(points), flags); else local length = #points / 3; local currentLength = 0; local i = 51; -- i'm some where inbetween while(i <= length) do if(npc:atPoint(pathfind.get(points, i))) then npc:pathThrough(pathfind.fromStart(points, i), flags); break; end i = i + 50; end end end;
gpl-3.0
dpino/snabbswitch
src/apps/lwaftr/ctable_wrapper.lua
3
2528
module(..., package.seeall) local ctable = require('lib.ctable') local math = require("math") local os = require("os") local S = require("syscall") local bit = require("bit") local bnot, bxor = bit.bnot, bit.bxor local floor, ceil = math.floor, math.ceil local HASH_MAX = 0xFFFFFFFF -- This is only called when the table is 'full'. -- Notably, it cannot be called on an empty table, -- so there is no risk of an infinite loop. local function evict_random_entry(ctab) local random_hash = math.random(0, HASH_MAX - 1) local index = floor(random_hash*ctab.scale + 0.5) local entries = ctab.entries while entries[index].hash == HASH_MAX do if index >= ctab.size + ctab.max_displacement then index = 0 -- Seems unreachable? else index = index + 1 end end local ptr = ctab.entries + index ctab:remove_ptr(ptr) end -- Behave exactly like insertion, except if the table is full: if it -- is, then evict a random entry instead of resizing. local function add_with_random_eviction(self, key, value, updates_allowed) local did_evict = false if self.occupancy + 1 > self.occupancy_hi then evict_random_entry(self) did_evict = true end return ctable.CTable.add(self, key, value, updates_allowed), did_evict end function new(params) local ctab = ctable.new(params) ctab.add = add_with_random_eviction return ctab end function selftest() print('selftest: apps.lwaftr.ctable_wrapper') local ffi = require("ffi") local occupancy = 4 -- 32-byte entries local params = { key_type = ffi.typeof('uint32_t'), value_type = ffi.typeof('int32_t[6]'), max_occupancy_rate = 0.4, initial_size = ceil(occupancy / 0.4) } local ctab = new(params) -- Fill table fully, to the verge of being resized. local v = ffi.new('int32_t[6]'); local i = 1 while ctab.occupancy + 1 <= ctab.occupancy_hi do for j=0,5 do v[j] = bnot(i) end ctab:add(i, v) i = i + 1 end local old_occupancy = ctab.occupancy for j=0,5 do v[j] = bnot(i) end local entry = ctab:add(i, v) local iterated = 0 for entry in ctab:iterate() do iterated = iterated + 1 end assert(old_occupancy == ctab.occupancy, "bad random eviction!") ctab:remove_ptr(entry, false) local iterated = 0 for entry in ctab:iterate() do iterated = iterated + 1 end assert(iterated == ctab.occupancy) assert(iterated == old_occupancy - 1) -- OK, all looking good with our ctab. print('selftest: ok') end
apache-2.0
nesstea/darkstar
scripts/zones/Gusgen_Mines/npcs/_5ge.lua
13
1340
----------------------------------- -- Area: Gusgen Mines -- NPC: _5ge (Lever E) -- @pos 20 -20.561 143.801 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --local nID = npc:getID(); --printf("id: %u", nID); local Lever = npc:getID(); npc:openDoor(2); -- Lever animation if (GetNPCByID(Lever-6):getAnimation() == 9) then GetNPCByID(Lever-7):setAnimation(9);--close door F GetNPCByID(Lever-6):setAnimation(8);--open door E GetNPCByID(Lever-5):setAnimation(9);--close door D 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
hussian/hell_iraq
plugins/short_link.lua
8
1185
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY(@AHMED_ALOBIDE) ▀▄ ▄▀ ▀▄ ▄▀ BY(@hussian_9) ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function DevPoint(msg, matches) local reza = URL.escape(matches[1]) url = "https://api-ssl.bitly.com/v3/shorten?access_token=f2d0b4eabb524aaaf22fbc51ca620ae0fa16753d&longUrl="..reza jstr, res = https.request(url) jdat = JSON.decode(jstr) if jdat.message then return 'تم اختصار الرابط 🆕✔️ \n___________\n\n'..jdat.message else return "تم اختصار الرابط 🆕✔️: \n___________\n"..jdat.data.url end end return { patterns = { "^[/!]shortlink (.*)$" }, run = DevPoint, }
gpl-2.0
UnfortunateFruit/darkstar
scripts/zones/RuLude_Gardens/npcs/Morlepiche.lua
28
3206
----------------------------------- -- Area: Rulude Gardens -- NPC: Morlepiche -- @pos -95 0 160 243 ------------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/conquest"); require("scripts/zones/RuLude_Gardens/TextIDs"); local guardnation = OTHER; -- SANDORIA, BASTOK, WINDURST, OTHER(Jeuno). local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Menu1 = getArg1(guardnation,player); local Menu3 = conquestRanking(); local Menu6 = getArg6(player); local Menu7 = player:getCP(); player:startEvent(0x7ffb,Menu1,0,Menu3,0,0,Menu6,Menu7,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); if (player:getNation() == 0) then inventory = SandInv; size = table.getn(SandInv); elseif (player:getNation() == 1) then inventory = BastInv; size = table.getn(BastInv); else inventory = WindInv; size = table.getn(WindInv); end if (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then CPVerify = 1; if (player:getCP() >= inventory[Item + 1]) then CPVerify = 0; end; player:updateEvent(2,CPVerify,inventory[Item + 2]); -- can't equip = 2 ? break; end; end; end; end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); if (option == 1) then duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then if (player:getFreeSlotsCount() >= 1) then -- Logic to impose limits on exp bands if (option >= 32933 and option <= 32935) then if (checkConquestRing(player) > 0) then player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]); break; else player:setVar("CONQUEST_RING_TIMER",getConquestTally()); end end itemCP = inventory[Item + 1]; player:delCP(itemCP); player:addItem(inventory[Item + 2],1); player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end; break; end; end; end; end;
gpl-3.0
ShaTelTeam/MegaZs
plugins/mute.lua
3
7669
do local function muteuser(user_id, channel_id) local hash = 'mute:'..channel_id redis:sadd(hash, user_id) end local function is_mute(user_id, channel_id) local hash = 'mute:'..channel_id local muted = redis:sismember(hash, user_id) return muted or false end local function muteuser_by_reply(extra, success, result) vardump(result) if result.to.peer_type == "channel" then local channel = "channel#"..result.to.peer_id if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot return "I won't silent myself" end local name = user_print_name(result.from) local hash = 'mute:'..result.to.peer_id if is_mute(result.from.peer_id, result.to.peer_id) then send_large_msg(channel, name.." ["..result.from.peer_id.."] removed from muted user list") redis:srem(hash, result.from.peer_id) else send_large_msg(channel, name.." ["..result.from.peer_id.."] added to muted user list") redis:sadd(hash, result.from.peer_id) end end end local function show_mute(msg, target) local text = "Mutes for:[ID:"..msg.to.id.."]:\n\nMute Documents: "..(redis:get("mute:document"..target) or 'no').."\nMute Contacts: "..(redis:get("mute:contact"..target) or 'no').."\nMute Audio: "..(redis:get("mute:audio"..target) or 'no').."\nMute Text: "..(redis:get("mute:text"..target) or 'no').."\nMute Video: "..(redis:get("mute:video"..target) or 'no').."\nMute Photo: "..(redis:get("mute:photo"..target) or "no").."\nMute Gifs: "..(redis:get("mute:gif"..target) or 'no').."\nMute All: "..(redis:get("mute:all"..target) or "no") return text end local function clean_mute(channel_id) local hash = 'mute:'..channel_id local list = redis:smembers(hash) for k,v in pairs(list) do redis:srem(hash, v) end return "Mutelist Cleaned" end local function mute_list(channel_id) local hash = 'mute:'..channel_id local list = redis:smembers(hash) local text = "Muted Users for: [ID:"..channel_id.."]:\n\n" local i = 1 for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end local function mute_res(extra, success, result) local member_id = result.peer_id local member = result.username local channel_id = extra.channel_id local mute_cmd = extra.mute_cmd local receiver = "channel#id"..channel_id if mute_cmd == "muteuser" then if is_mute(member_id, channel_id) then send_large_msg(receiver, "["..member_id.."] removed from muted user list") local hash = 'mute:'..channel_id redis:srem(hash, member_id) else send_large_msg(receiver, "["..member_id.."] added to muted user list") return muteuser(member_id, channel_id) end end end local function run(msg, matches) local target = msg.to.id if matches[1] == "muteuser" then if type(msg.reply_id)~= "nil" then msgreply = get_message(msg.reply_id, muteuser_by_reply, false) end if string.match(matches[2], '^%d+$') then local user_id = matches[2] local channel_id = msg.to.id muteuser(user_id, channel_id) else local cb_extra = { channel_id = msg.to.id, mute_cmd = 'muteuser', } local username = matches[2] local username = string.gsub(matches[2], "@", "") resolve_username(username, mute_res, cb_extra) end end if matches[1] == "mutelist" then local channel_id = msg.to.id return mute_list(channel_id) end if matches[1] == "mute" and is_momod(msg) then if matches[2]:lower() == "audio" then redis:set("mute:audio"..target, "yes") return "Mute Audio has been enabled" end if matches[2]:lower(0) == "text" then redis:set("mute:text"..target, "yes") return "Mute Text has been enabled" end if matches[2]:lower() == "video" then redis:set("mute:video"..target, "yes") return "Mute Video has been enabled" end if matches[2]:lower() == "photo" then redis:set("mute:photo"..target, "yes") return "Mute Photo has been enabled" end if matches[2]:lower() == "all" then redis:set("mute:all"..target, "yes") return "Mute All has been enabled" end if matches[2]:lower() == "gifs" then redis:set("mute:gif"..target, "yes") return "Gifs posting has been muted" end if matches[2]:lower() == "contacts" then redis:set("mute:contact"..target, "yes") return "Share contacts has been muted" end if matches[2]:lower() == "document" then redis:set("mute:document"..target, "yes") return "Mute Documents has been enabled" end end if matches[1] == "unmute" and is_momod(msg) then if matches[2]:lower() == "audio" then redis:del("mute:audio"..msg.to.id) return "Mute Audio has been disabled" end if matches[2]:lower() == "text" then redis:del("mute:text"..msg.to.id) return "Mute Text has been disabled" end if matches[2]:lower() == "photo" then redis:del("mute:photo"..msg.to.id) return "Mute Photo has been disabled" end if matches[2]:lower() == "video" then redis:del("mute:video"..msg.to.id) return "Mute Video has been disabled" end if matches[2]:lower() == "all" then redis:del("mute:all"..msg.to.id) return "Mute All has been disabled" end if matches[2]:lower() == "gifs" and is_momod(msg) then redis:del("mute:gif"..target) return "Gifs posting has been unmuted" end if matches[2]:lower() == "contacts" and is_momod(msg) then redis:del("mute:contact"..target) return "Share contacts has been unmuted" end if matches[2]:lower() == "document" then redis:del("mute:document"..target) return "Mute Documents has been disabled" end end if matches[1] == "muteslist" and is_momod(msg) then return show_mute(msg, target) end if matches[1] == "clean" then local channel_id = msg.to.id return clean_mute(channel_id) end end local function pre_process(msg) if msg.service then return msg end if redis:get("mute:all"..msg.to.id) and not is_momod(msg) then delete_msg(msg.id, ok_cb, true) end if msg.text then if redis:get("mute:text"..msg.to.id) == "yes" then delete_msg(msg.id, ok_cb, false) end end if msg.media then if msg.media.type == "photo" then if redis:get("mute:photo"..msg.to.id) == "yes" then delete_msg(msg.id, ok_cb, false) end end end if msg.media then if msg.media.type == "audio" then if redis:get("mute:audio"..msg.to.id) == "yes" and not is_momod(msg) then delete_msg(msg.id, ok_cb, true) end end end if msg.media then if msg.media.type == "video" then if redis:get("mute:video"..msg.to.id) == "yes" then delete_msg(msg.id, ok_cb, false) end end end if msg.media then if msg.media.caption == "giphy.mp4" and not is_momod(msg) then if redis:get("mute:gif"..msg.to.id) == "yes" then delete_msg(msg.id, ok_cb, true) end end if msg.media.type == "contact" and not is_momod(msg) then if redis:get("mute:contact"..msg.to.id) == "yes" then delete_msg(msg.id, ok_cb, true) end end end if msg.media then if msg.media.type == "document" and not msg.media.caption and not is_momod(msg) then if redis:get("mute:document"..msg.to.id) == "yes" then delete_msg(msg.id, ok_cb, true) end end end if is_mute(msg.from.id, msg.to.id) then delete_msg(msg.id, ok_cb, true) end return msg end return { patterns = { "^[/!#](muteuser)$", "^[!/#](mute) (.*)$", "^[/!#](unmute) (.*)$", "^[/!#](muteuser) (.*)$", "^[/!#](mutelist)$", "^[!/#](muteslist)$", "^[/!#](clean) mutelist$", '%[(audio)%]', '%[(photo)%]', '%[(video)%]', '%[(document)%]' }, run = run, pre_process = pre_process } end
gpl-2.0
AttacqueSuperior/Engine
mods/d2k/maps/harkonnen-02a/harkonnen02a.lua
2
2633
--[[ Copyright 2007-2021 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] AtreidesBase = { AConyard, APower1, APower2, ABarracks, AOutpost } AtreidesReinforcements = { easy = { { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" } }, normal = { { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" }, { "light_inf", "light_inf" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" } }, hard = { { "trike", "trike" }, { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" }, { "light_inf", "light_inf" }, { "trike", "trike" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" }, { "trike", "trike" } } } AtreidesAttackPaths = { { AtreidesEntry1.Location, AtreidesRally1.Location }, { AtreidesEntry1.Location, AtreidesRally4.Location }, { AtreidesEntry2.Location, AtreidesRally2.Location }, { AtreidesEntry2.Location, AtreidesRally3.Location } } AtreidesAttackDelay = { easy = DateTime.Minutes(5), normal = DateTime.Minutes(2) + DateTime.Seconds(40), hard = DateTime.Minutes(1) + DateTime.Seconds(20) } AtreidesAttackWaves = { easy = 3, normal = 6, hard = 9 } Tick = function() if player.HasNoRequiredUnits() then atreides.MarkCompletedObjective(KillHarkonnen) end if atreides.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillAtreides) then Media.DisplayMessage("The Atreides have been annihilated!", "Mentat") player.MarkCompletedObjective(KillAtreides) end end WorldLoaded = function() atreides = Player.GetPlayer("Atreides") player = Player.GetPlayer("Harkonnen") InitObjectives(player) KillHarkonnen = atreides.AddPrimaryObjective("Kill all Harkonnen units.") KillAtreides = player.AddPrimaryObjective("Destroy all Atreides forces.") Camera.Position = HConyard.CenterPosition Trigger.OnAllKilled(AtreidesBase, function() Utils.Do(atreides.GetGroundAttackers(), IdleHunt) end) local path = function() return Utils.Random(AtreidesAttackPaths) end SendCarryallReinforcements(atreides, 0, AtreidesAttackWaves[Difficulty], AtreidesAttackDelay[Difficulty], path, AtreidesReinforcements[Difficulty]) Trigger.AfterDelay(0, ActivateAI) end
gpl-3.0
Kthulupwns/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Morangeart.lua
38
1057
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Morangeart -- Type: ENM Quest Activator -- @zone: 26 -- @pos -74.308 -24.782 -28.475 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0208); 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
amin041/tele-dam-
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
ASHRAF97/ASHRAFKASPERV3
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
Kthulupwns/darkstar
scripts/globals/items/royal_omelette.lua
36
2710
----------------------------------------- -- ID: 4564 -- Item: royal_omelette -- Food Effect: 180Min, All Races ----------------------------------------- -- Strength 5 -- Dexterity 2 -- Intelligence -3 -- Mind 4 -- Attack % 22 -- Attack Cap 65 ----------------------------------------- -- IF ELVAAN ONLY -- HP 20 -- MP 20 -- Strength 6 -- Dexterity 2 -- Intelligence -2 -- Mind 5 -- Charisma 4 -- Attack % 22 -- Attack Cap 80 -- Ranged ATT % 22 -- Ranged ATT Cap 80 ----------------------------------------- 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,4564); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) if (target:getRace() == 3 or target:getRace() == 4) then target:addMod(MOD_HP, 20); target:addMod(MOD_MP, 20); target:addMod(MOD_STR, 6); target:addMod(MOD_DEX, 2); target:addMod(MOD_INT, -2); target:addMod(MOD_MND, 5); target:addMod(MOD_CHR, 4); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 80); target:addMod(MOD_FOOD_RATTP, 22); target:addMod(MOD_FOOD_RATT_CAP, 80); else target:addMod(MOD_STR, 5); target:addMod(MOD_DEX, 2); target:addMod(MOD_INT, -3); target:addMod(MOD_MND, 4); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 65); target:addMod(MOD_FOOD_RATTP, 22); target:addMod(MOD_FOOD_RATT_CAP, 65); end end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) if (target:getRace() == 3 or target:getRace() == 4) then target:delMod(MOD_HP, 20); target:delMod(MOD_MP, 20); target:delMod(MOD_STR, 6); target:delMod(MOD_DEX, 2); target:delMod(MOD_INT, -2); target:delMod(MOD_MND, 5); target:delMod(MOD_CHR, 4); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 80); target:delMod(MOD_FOOD_RATTP, 22); target:delMod(MOD_FOOD_RATT_CAP, 80); else target:delMod(MOD_STR, 5); target:delMod(MOD_DEX, 2); target:delMod(MOD_INT, -3); target:delMod(MOD_MND, 4); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 65); target:delMod(MOD_FOOD_RATTP, 22); target:delMod(MOD_FOOD_RATT_CAP, 65); end end;
gpl-3.0
Kthulupwns/darkstar
scripts/zones/Cloister_of_Tides/Zone.lua
32
1658
----------------------------------- -- -- Zone: Cloister_of_Tides (211) -- ----------------------------------- package.loaded["scripts/zones/Cloister_of_Tides/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Cloister_of_Tides/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(564.776,34.297,500.819,250); 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
rohanp/Algorithm-Implementations
Bellman_Ford_Search/Lua/Yonaba/bellmanford.lua
26
3025
-- Bellman Ford single source shortest path search algorithm implementation -- See : https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm -- Notes : this is a generic implementation of Bellman Ford search algorithm. -- It is devised to be used on waypoint graphs. -- The BellmanFord class expects a handler to be initialized. Roughly said, the handler -- is an interface between your graph and the search algorithm. -- The passed-in handler should implement those functions. -- handler.getNode(...) -> returns a Node (instance of node.lua) -- handler.getAllNodes() -> returns an array list of all nodes in the graph -- handler.getAllEdges() -> returns an array list of all edges in the graph -- See utils/graph.lua for reference -- The generic Node class provided (see utils/node.lua) should also be implemented -- through the handler. Basically, it should describe how nodes are labelled -- and tested for equality for a custom search space. -- The following functions should be implemented: -- function Node:initialize(...) -> creates a Node with custom attributes -- function Node:toString() -> returns a unique string representation of -- the node, for debug purposes -- Dependencies local class = require 'utils.class' -- Clears nodes data between consecutive path requests. local function resetForNextSearch(bellmanford) local nodes = bellmanford.handler.getAllNodes() for _, node in pairs(nodes) do node.parent = nil node.distance = math.huge end end -- Builds and returns the path to the goal node local function backtrace(node) local path = {} repeat table.insert(path, 1, node) node = node.parent until not node return path end -- Initializes Bellman Ford search with a custom handler local BellmanFord = class() function BellmanFord:initialize(handler) self.handler = handler end -- Processes the graph for shortest paths -- source : the starting node from which the search will spread. -- target : the goal node -- When done, the shortest path from one node to another can easily -- backtraced by indexing the parent field of a node. -- Return : if target supplied, returns the shortest path from source -- to target. function BellmanFord:process(source, target) resetForNextSearch(self) source.distance = 0 local nodes = self.handler.getAllNodes() local edges = self.handler.getAllEdges() -- Relaxing all edges |V| - 1 times for i = 1, #nodes - 1 do for i, edge in ipairs(edges) do local u, v, w = edge.from, edge.to, edge.weight local tempDistance = u.distance + w if tempDistance < v.distance then v.distance, v.parent = tempDistance, u end end end -- Checking for negative cycles for i, edge in ipairs(edges) do local u, v, w = edge.from, edge.to, edge.weight local tempDistance = u.distance + w assert(tempDistance >= v.distance, 'Negative cycle found!') end if target then return backtrace(target) end end return BellmanFord
mit
dpino/snabb
lib/pflua/src/pf/regalloc.lua
7
16379
-- Implements register allocation for pflua's native backend -- -- Follows the algorithm described in: -- "Linear scan register allocation" -- Poletto and Sarkar -- https://dl.acm.org/citation.cfm?id=330250 -- -- The result of register allocation is a table that describes -- the register allocated for the given virtual registers, e.g.: -- -- { v1 = 1, -- %rcx -- v2 = 2, -- %rdx -- r3 = 0, -- %rax -- len = 6, -- %rsi -- callee_saves = {}, -- spills = { v3 = 0, v4 = 1 }, -- spill_registers = { 3, 4 } -- } -- -- The callee_saves field lists the callee-save registers that are -- used in the allocation. This lets the code generation pass easily -- generate any push/pops that are needed. -- -- Register numbers are based on DynASM's Rq() register mapping. -- -- The following registers are reserved and not allocated: -- * %rdi to store the packet pointer argument -- -- The allocator should first prioritize using caller-save registers -- * %rax, %rcx, %rdx, %r8-%r11 -- -- before using callee-save registers -- * %rbx, %r12-%r15 -- -- The spills and spill_registers fields are used for spilling registers -- to memory if that becomes necessary. When the first register is spilled, -- two additional registers are spilled (and put into spill_registers) so -- that they can be used to move data from/to memory and registers. -- -- The spills field keeps track of the stack slots (numbered from 0) -- that are used for spilled registers. Variables should only be mapped -- in one of the main allocation table or in the spills table. module(...,package.seeall) local utils = require('pf.utils') local verbose = os.getenv("PF_VERBOSE"); -- returns the registers that a given instruction reads local function reads_from(instr) local itype = instr[1] local function maybe_reg(reg) if type(reg) == "number" then return nil else return reg end end if itype == "mov" or itype == "mov64" then return { maybe_reg(instr[3]) } elseif itype == "ntohs" or itype == "ntohl" or itype == "uint32" then return { instr[2] } elseif itype == "cjmp" or itype == "jmp" or itype == "ret-true" or itype == "ret-false" or itype == "nop" or itype == "label" then return {} else -- instructions don't have immediates in the first arg return { instr[2], maybe_reg(instr[3]) } end end -- Update the ends of intervals based on variable occurrences in -- the "control" ast local function find_live_in_control(label, control, intervals) -- the head of an ast is always an operation name, so skip for i = 2, #control do local ast_type = type(control[i]) if ast_type == "string" then for _, interval in ipairs(intervals) do if control[i] == interval.name then interval.finish = label end end elseif ast_type == "table" then find_live_in_control(label, control[i], intervals) end end end -- The lack of loops and unique register names for each load -- in the instruction IR makes finding live intervals easy. -- -- A live interval is a table -- { name = String, start = number, finish = number } -- -- The start and finish fields are indices into the instruction -- array -- local function live_intervals(instrs) local len = { name = "len", start = 1, finish = 1 } local order = { len } local intervals = { len = len } for idx, instr in ipairs(instrs) do local itype = instr[1] -- movs and loads are the only instructions that result in -- new live intervals if itype == "load" or itype == "mov" or itype == "mov64" then local name = instr[2] local interval = { name = name, start = idx, finish = idx } intervals[name] = interval table.insert(order, interval) end for _, reg in ipairs(reads_from(instr)) do intervals[reg].finish = idx end end -- we need the resulting allocations to be ordered by starting -- point, so we emit the ordered sequence rather than the map return order end -- All available registers, tied to unix x64 ABI local caller_regs = {11, 10, 9, 8, 6, 2, 1, 0} local callee_regs = {15, 14, 13, 12, 3} local num_regs = #caller_regs + #callee_regs -- Check if a register is free in the freelist local function is_free(seq, reg) for _, val in ipairs(seq) do if val == reg then return true end end return false end -- Remove the given register from the freelist local function remove_free(freelist, reg) for idx, reg2 in ipairs(freelist) do if reg2 == reg then table.remove(freelist, idx) return end end end -- Insert an interval sorted by increasing finish local function insert_active(active, interval) local finish = interval.finish for idx, interval2 in ipairs(active) do if interval2.finish > finish then table.insert(active, idx, interval) return end end table.insert(active, interval) end -- Optimize movs from a register to the same one local function delete_useless_movs(ir, alloc) for idx, instr in ipairs(ir) do if instr[1] == "mov" then if alloc[instr[2]] == alloc[instr[3]] then -- It's faster just to convert these to -- nops than to re-number the table ir[idx] = { "nop" } end end end end -- Do register allocation with the given IR -- Returns a register allocation and potentially mutates -- the ir for optimizations function allocate(ir) local intervals = live_intervals(ir) local active = {} local next_spill = 0 -- caller-save registers, use these first local free_caller = utils.dup(caller_regs) -- callee-save registers, if we have to local free_callee = utils.dup(callee_regs) local allocation = { len = 6, -- %rsi callee_saves = {}, spills = {} } remove_free(free_caller, 6) local function expire_old(interval) local to_expire = {} for idx, active_interval in ipairs(active) do if active_interval.finish > interval.start then break else local name = active_interval.name local reg = allocation[name] table.insert(to_expire, idx) -- figure out which free list this register is supposed to be on if is_free(caller_regs, reg) then table.insert(free_caller, reg) elseif is_free(callee_regs, reg) then table.insert(free_callee, reg) else error("unknown register") end end end for i=1, #to_expire do table.remove(active, to_expire[#to_expire - i + 1]) end end local function spill_at(interval) -- when there's a first spill, pick two additional variables -- to spill to the stack and reserve their registers for accessing -- spilled variables via movs if next_spill == 0 then local i1, i2 = active[#active], active[#active-1] local reg1 = allocation[i1.name] local reg2 = allocation[i2.name] table.remove(active); table.remove(active) allocation[i1.name] = nil allocation[i2.name] = nil allocation.spills[i1.name] = 0 allocation.spills[i2.name] = 1 allocation.spill_registers = { reg1, reg2 } next_spill = next_spill + 2 end local to_spill = active[#active] if to_spill.finish > interval.finish then allocation[interval.name] = allocation[to_spill.name] allocation[to_spill.name] = nil allocation.spills[to_spill.name] = next_spill table.remove(active) insert_active(active, interval) else allocation.spills[interval.name] = next_spill end next_spill = next_spill + 1 end for _, interval in pairs(intervals) do local name = interval.name expire_old(interval) -- because we prefill some registers, check first if -- we need to allocate for this interval if not allocation[name] then if #free_caller == 0 and #free_callee == 0 then spill_at(interval) -- newly freed registers are put at the end, so allocating from -- the end will tend to produce better results since we want to -- try eliminate movs with the same destination/source register elseif #free_caller ~= 0 then allocation[name] = free_caller[#free_caller] table.remove(free_caller) insert_active(active, interval) else local idx = #free_callee allocation[name] = free_callee[idx] allocation.callee_saves[free_callee[idx]] = true table.remove(free_callee) insert_active(active, interval) end else insert_active(active, interval) end end delete_useless_movs(ir, allocation) if verbose then utils.pp({ "register_allocation", allocation }) end return allocation end function selftest() local function test(instrs, expected) utils.assert_equals(expected, live_intervals(instrs)) end -- part of `tcp`, see pf.selection local example_1 = { { "label", 0 }, { "cmp", "len", 34 }, { "cjmp", "<", 4 }, { "label", 3 }, { "load", "v1", 12, 2 }, { "cmp", "v1", 8 }, { "cjmp", "!=", 6 }, { "label", 5 }, { "load", "r1", 23, 1 }, { "cmp", "r1", 6 }, { "cjmp", "=", "true-label" }, { "ret-false" }, { "label", 6 }, { "cmp", "len", 54 }, { "cjmp", "<", 8 }, { "label", 7 }, { "cmp", "v1", 56710 }, { "cjmp", "!=", 10 }, { "label", 9 }, { "load", "v2", 20, 1 }, { "cmp", "v2", 6 }, { "cjmp", "!=", 12 } } local example_2 = { { "label", 1 }, { "load", "r1", 12, 2 }, { "load", "r2", 14, 2 }, { "mov", "r3", "r1" }, { "mul", "r3", "r2" }, { "cmp", "r3", 1 }, { "cjmp", "!=", 4 }, { "cmp", "len", 1 } } -- this example isn't from real code, but tests what happens when -- there is higher register pressure local example_3 = { { "label", 1 }, { "load", "r1", 12, 2 }, { "load", "r2", 14, 2 }, { "load", "r3", 15, 2 }, { "load", "r4", 16, 2 }, { "load", "r5", 17, 2 }, { "load", "r6", 18, 2 }, { "load", "r7", 19, 2 }, { "load", "r8", 20, 2 }, { "load", "r9", 21, 2 }, { "cmp", "r1", 1 }, { "cmp", "r2", 1 }, { "cmp", "r3", 1 }, { "cmp", "r4", 1 }, { "cmp", "r5", 1 }, { "cmp", "r6", 1 }, { "cmp", "r7", 1 }, { "cmp", "r8", 1 }, { "cmp", "r9", 1 } } -- test that tries to make movs use same dst/src local example_4 = { { "label", 1 }, { "load", "v1", 12, 2 }, { "cmp", "v1", 1 }, { "load", "r1", 12, 2 }, { "mov", "r2", "r1" }, { "cmp", "r2", 1 }, { "cmp", "len", 1 } } -- full `tcp` example from more recent instruction selection local example_5 = { { "label", 0 }, { "cmp", "len", 34 }, { "cjmp", "<", 4 }, { "label", 3 }, { "load", "r1", 12, 2 }, { "mov", "v1", "r1" }, { "cmp", "v1", 8 }, { "cjmp", "!=", 6 }, { "label", 5 }, { "load", "r2", 23, 1 }, { "cmp", "r2", 6 }, { "cjmp", "=", "true-label" }, { "ret-false" }, { "label", 6 }, { "cmp", "len", 54 }, { "cjmp", "<", 8 }, { "label", 7 }, { "cmp", "v1", 56710 }, { "cjmp", "!=", 10 }, { "label", 9 }, { "load", "r3", 20, 1 }, { "mov", "v2", "r3" }, { "cmp", "v2", 6 }, { "cjmp", "!=", 12 }, { "label", 11 }, { "ret-true" }, { "label", 12 }, { "cmp", "len", 55 }, { "cjmp", "<", 14 }, { "label", 13 }, { "cmp", "v2", 44 }, { "cjmp", "!=", 16 }, { "label", 15 }, { "load", "r4", 54, 1 }, { "cmp", "r4", 6 }, { "cjmp", "=", "true-label" }, { "ret-false" }, { "label", 16 }, { "ret-false" }, { "label", 14 }, { "ret-false" }, { "label", 10 }, { "ret-false" }, { "label", 8 }, { "ret-false" }, { "label", 4 }, { "ret-false" } } -- test that variables in load offsets are properly accounted for local example_6 = { { "label", 0 }, { "mov", "r1", 5 }, { "load", "v2", 12, 2 }, { "load", "v1", "r1", 2 }, { "cmp", "v1", 1 }, { "cmp", "v2", 2 } } -- another test with high register pressure, should be high enough -- to require spilling local example_7 = { { "label", 1 }, { "load", "r1", 12, 2 }, { "load", "r2", 14, 2 }, { "load", "r3", 15, 2 }, { "load", "r4", 16, 2 }, { "load", "r5", 17, 2 }, { "load", "r6", 18, 2 }, { "load", "r7", 19, 2 }, { "load", "r8", 20, 2 }, { "load", "r9", 21, 2 }, { "load", "r10", 22, 2 }, { "load", "r11", 23, 2 }, { "load", "r12", 24, 2 }, { "load", "r13", 25, 2 }, { "load", "r14", 26, 2 }, { "cmp", "r1", 1 }, { "cmp", "r2", 1 }, { "cmp", "r3", 1 }, { "cmp", "r4", 1 }, { "cmp", "r5", 1 }, { "cmp", "r6", 1 }, { "cmp", "r7", 1 }, { "cmp", "r8", 1 }, { "cmp", "r9", 1 }, { "cmp", "r10", 1 }, { "cmp", "r11", 1 }, { "cmp", "r12", 1 }, { "cmp", "r13", 1 }, { "cmp", "r14", 1 } } test(example_1, { { name = "len", start = 1, finish = 14 }, { name = "v1", start = 5, finish = 17 }, { name = "r1", start = 9, finish = 10 }, { name = "v2", start = 20, finish = 21 } }) test(example_2, { { name = "len", start = 1, finish = 8 }, { name = "r1", start = 2, finish = 4 }, { name = "r2", start = 3, finish = 5 }, { name = "r3", start = 4, finish = 6 } }) test(example_5, { { name = "len", start = 1, finish = 28 }, { name = "r1", start = 5, finish = 6 }, { name = "v1", start = 6, finish = 18 }, { name = "r2", start = 10, finish = 11 }, { name = "r3", start = 21, finish = 22 }, { name = "v2", start = 22, finish = 31 }, { name = "r4", start = 34, finish = 35 } }) test(example_6, { { name = "len", start = 1, finish = 1 }, { name = "r1", start = 2, finish = 4 }, { name = "v2", start = 3, finish = 6 }, { name = "v1", start = 4, finish = 5 } }) local function test(instrs, expected) utils.assert_equals(expected, allocate(instrs)) end test(example_1, { v1 = 0, r1 = 1, len = 6, v2 = 0, callee_saves = {}, spills = {} }) -- mutates example_2 test(example_2, { r1 = 0, r2 = 1, r3 = 0, len = 6, callee_saves = {}, spills = {} }) utils.assert_equals(example_2, { { "label", 1 }, { "load", "r1", 12, 2 }, { "load", "r2", 14, 2 }, { "nop" }, { "mul", "r3", "r2" }, { "cmp", "r3", 1 }, { "cjmp", "!=", 4 }, { "cmp", "len", 1 } }) test(example_3, { r1 = 6, r2 = 0, r3 = 1, r4 = 2, r5 = 8, r6 = 9, r7 = 10, r8 = 11, r9 = 3, len = 6, callee_saves = utils.set(3), spills = {} }) test(example_4, { v1 = 0, r1 = 0, len = 6, r2 = 0, callee_saves = {}, spills = {} }) test(example_5, { len = 6, r1 = 0, v1 = 0, r2 = 1, r3 = 0, v2 = 0, r4 = 0, callee_saves = {}, spills = {} }) test(example_7, { r1 = 6, r2 = 0, r3 = 1, r4 = 2, r5 = 8, r6 = 9, r7 = 10, r8 = 11, r9 = 3, r10 = 12, r11 = 13, spills = { r12 = 1, r13 = 0, r14 = 2 }, len = 6, callee_saves = utils.set(3, 12, 13, 14, 15), spill_registers = { 15, 14 } }) end
apache-2.0
Kthulupwns/darkstar
scripts/globals/items/galkan_sausage_-1.lua
35
1586
----------------------------------------- -- ID: 5862 -- Item: galkan_sausage_-1 -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength -3 -- Dexterity -3 -- Vitality -3 -- Agility -3 -- Mind -3 -- Intelligence -3 -- Charisma -3 ----------------------------------------- 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,5862); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -3); target:addMod(MOD_DEX, -3); target:addMod(MOD_VIT, -3); target:addMod(MOD_AGI, -3); target:addMod(MOD_MND, -3); target:addMod(MOD_INT, -3); target:addMod(MOD_CHR, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -3); target:delMod(MOD_DEX, -3); target:delMod(MOD_VIT, -3); target:delMod(MOD_AGI, -3); target:delMod(MOD_MND, -3); target:delMod(MOD_INT, -3); target:delMod(MOD_CHR, -3); end;
gpl-3.0
LuaDist/lzmq
test/test_req_relaxed.lua
16
3251
--- -- Test ZMQ_REQ_RELAXED mode and reconnect socket -- This test requires [lua-llthreads2](https://github.com/moteus/lua-llthreads2) library local zmq = require "lzmq" local ztimer = require "lzmq.timer" local zthreads = require "lzmq.threads" local zassert = zmq.assert local ENDPOINT = "tcp://127.0.0.1:5555" local CLIENT_SOCKET_TYPE = zmq.REQ ----------------------------------------------------------------------------- -- START - start server thread -- FINISH - stop server thread and wait until it stopped -- ECHO - send echo msg to server, wait and check response local START, FINISH, ECHO, RECONNECT, WAIT do local proc local ctx = zmq.context() local pipe if CLIENT_SOCKET_TYPE == zmq.REQ then pipe = zassert(ctx:socket{zmq.REQ, sndtimeo = 1000, rcvtimeo = 1000, linger = 0, req_relaxed = 1, req_correlate = 1, connect = ENDPOINT, }) else assert(zmq.DEALER == CLIENT_SOCKET_TYPE) pipe = zassert(ctx:socket{zmq.DEALER, sndtimeo = 1000, rcvtimeo = 1000, linger = 0, connect = ENDPOINT, }) end local SERVER = string.dump(function(ENDPOINT) local zmq = require "lzmq" local ztimer = require "lzmq.timer" local zthreads = require "lzmq.threads" local zassert = zmq.assert local ctx = zthreads.get_parent_ctx() or zmq.context() local srv = zassert(ctx:socket{zmq.ROUTER, bind = ENDPOINT}) print("== SERVER START: ") local msg, err while true do msg, err = srv:recv_all() if not msg then print('== SERVER RECV: ' .. tostring(err)) if err:mnemo() ~= 'EAGAIN' then break end else print('== SERVER RECV: ' .. msg[#msg]) local ok, err = srv:send_all(msg) print('== SERVER SEND: ' .. (ok and msg[#msg] or tostring(err))) if msg[#msg] == 'FINISH' then break end end end print("== SERVER FINISH: ") end) function START() local thread = assert(zthreads.run(ctx, SERVER, ENDPOINT)):start(true, true) ztimer.sleep(1000) local ok, err = thread:join(0) assert(err == 'timeout') proc = thread end function FINISH() zassert(pipe:send('FINISH')) zassert(pipe:recvx()) for i = 1, 100 do local ok, err = proc:join(0) if ok then return end ztimer.sleep(500) end assert(false) end local echo_no = 0 local function ECHO_() echo_no = echo_no + 1 local msg = "hello:" .. echo_no local ok, err = pipe:send(msg) print("== CLIENT SEND:", (ok and msg or tostring(err))) if not ok then return end while true do ok, err = pipe:recvx() print("== CLIENT RECV:", ok or err) if zmq.REQ == CLIENT_SOCKET_TYPE then if ok then assert(ok == msg) end break end if ok then if(ok == msg) then break end else break end end end function ECHO(N) for i = 1, (N or 1) do ECHO_() end end function RECONNECT() pipe:disconnect(ENDPOINT) zassert(pipe:connect(ENDPOINT)) print("== CLIENT RECONNECT") end function WAIT(n) ztimer.sleep(n or 100) end end ----------------------------------------------------------------------------- print("==== ZeroMQ version " .. table.concat(zmq.version(), '.') .. " ===") START() ECHO(2) FINISH() ECHO(2) START() ECHO(2) -- With reconnect test pass -- RECONNECT() ECHO(2) FINISH()
mit
billypu/lua-lab
anapurna/anapurna.lua
1
2625
module("anapurna", package.seeall) package.cpath = package.cpath .. ";./?.so;./lib/?.so" local core = require("anapurna.core") TCP = function (ip, port, isserver) local server_ip = ip local server_port = port local isserver = (isserver == nil or isserver == false) and false or true local listen_fd = core.create("TCP") local commu_fd = 0 -- return the listening fd local start = function () assert(isserver, "only server can start") local ret = core.bind(listen_fd, server_ip, server_port) if ret < 0 then return ret end return core.listen(listen_fd) end -- for server, return the connected fd local accept = function () commu_fd = core.accept(listen_fd) return commu_fd end -- for client local connect = function () commu_fd = core.connect(server_ip, server_port, "TCP") return commu_fd end local send = function (buffer, size) assert(commu_fd > 0, "illegal fd") return core.origin_send(commu_fd, buffer, size) end local recv = function () assert(commu_fd > 0, "illegal fd") return core.origin_recv(commu_fd) end local close = function () core.close(listen_fd) core.close(commu_fd) end return { start = start, accept = accept, connect = connect, send = send, recv = recv, close = close, } end UDP = function (ip, port, isserver) local server_ip = ip local server_port = port local sockfd = core.create("UDP") local isserver = (isserver == nil or isserver == false) and false or true local start = function () assert(isserver, "only server can start") core.bind(sockfd, server_ip, server_port) end local sendto = function (destip, destport, buff, size) return core.sendto(sockfd, destip, destport, buff, size) end local recvfrom = function () return core.recvfrom(sockfd) end local close = function () core.close(sockfd) end return { start = start, sendto = sendto, recvfrom = recvfrom, close = close, } end anapurna.process = function (process) -- body end anapurna.encode = function (encode_handler) -- body end anapurna.decode = function (decode_handler) -- body end -------------- anapurna.process(function ( ... ) -- body -- do process logic end) anapurna.encode(function ( ... ) -- body -- encode logic end) anapurna.decode(function ( ... ) -- body -- decode logic end)
mit
Kthulupwns/darkstar
scripts/zones/Metalworks/npcs/relic.lua
42
1834
----------------------------------- -- Area: Metalworks -- NPC: <this space intentionally left blank> -- @pos -20 -11 33 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Metalworks/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") == 18335 and trade:getItemCount() == 4 and trade:hasItemQty(18335,1) and trade:hasItemQty(1585,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1457,1)) then player:startEvent(843,18336); 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 == 843) then if (player:getFreeSlotsCount() < 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18336); player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1456); else player:tradeComplete(); player:addItem(18336); player:addItem(1456,30); player:messageSpecial(ITEM_OBTAINED,18336); player:messageSpecial(ITEMS_OBTAINED,1456,30); player:setVar("RELIC_IN_PROGRESS",0); end end end;
gpl-3.0
Kthulupwns/darkstar
scripts/zones/Port_San_dOria/npcs/HomePoint#1.lua
12
1262
----------------------------------- -- Area: Port San dOria -- NPC: HomePoint#1 -- @pos -67.963 -4.000 -105.023 232 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 6); 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
AGTMADCAT/naev
dat/factions/spawn/sirius.lua
6
3074
include("dat/factions/spawn/common.lua") include("dat/factions/spawn/mercenary_helper.lua") -- @brief Spawns a small patrol fleet. function spawn_patrol () local pilots = {} local r = rnd.rnd() if r < pbm then pilots = spawnLtMerc("Sirius") elseif r < 0.5 then scom.addPilot( pilots, "Sirius Fidelity", 20 ); elseif r < 0.8 then scom.addPilot( pilots, "Sirius Fidelity", 20 ); scom.addPilot( pilots, "Sirius Fidelity", 20 ); else scom.addPilot( pilots, "Sirius Fidelity", 20 ); scom.addPilot( pilots, "Sirius Shaman", 25 ); end return pilots end -- @brief Spawns a medium sized squadron. function spawn_squad () local pilots = {} local r = rnd.rnd() if r < pbm then pilots = spawnMdMerc("Sirius") elseif r < 0.5 then scom.addPilot( pilots, "Sirius Fidelity", 20 ); scom.addPilot( pilots, "Sirius Shaman", 25 ); scom.addPilot( pilots, "Sirius Preacher", 45 ); elseif r < 0.8 then scom.addPilot( pilots, "Sirius Preacher", 45 ); scom.addPilot( pilots, "Sirius Preacher", 45 ); else scom.addPilot( pilots, "Sirius Fidelity", 20 ); scom.addPilot( pilots, "Sirius Fidelity", 20 ); scom.addPilot( pilots, "Sirius Shaman", 25 ); scom.addPilot( pilots, "Sirius Preacher", 45 ); end return pilots end -- @brief Spawns a capship with escorts. function spawn_capship () local pilots = {} if rnd.rnd() < pbm then pilots = spawnBgMerc("Sirius") else local r = rnd.rnd() -- Generate the capship if r < 0.5 then scom.addPilot( pilots, "Sirius Dogma", 140 ) else scom.addPilot( pilots, "Sirius Divinity", 120 ); end -- Generate the escorts r = rnd.rnd() if r < 0.5 then scom.addPilot( pilots, "Sirius Fidelity", 20 ); scom.addPilot( pilots, "Sirius Fidelity", 20 ); scom.addPilot( pilots, "Sirius Shaman", 25 ); else scom.addPilot( pilots, "Sirius Fidelity", 20 ); scom.addPilot( pilots, "Sirius Preacher", 45 ); end end return pilots end -- @brief Creation hook. function create ( max ) local weights = {} -- Create weights for spawn table weights[ spawn_patrol ] = 100 weights[ spawn_squad ] = math.max(1, -80 + 0.80 * max) weights[ spawn_capship ] = math.max(1, -500 + 1.70 * max) -- Create spawn table base on weights spawn_table = scom.createSpawnTable( weights ) -- Calculate spawn data spawn_data = scom.choose( spawn_table ) return scom.calcNextSpawn( 0, scom.presence(spawn_data), max ) end -- @brief Spawning hook function spawn ( presence, max ) local pilots -- Over limit if presence > max then return 5 end -- Actually spawn the pilots pilots = scom.spawn( spawn_data ) -- Calculate spawn data spawn_data = scom.choose( spawn_table ) return scom.calcNextSpawn( presence, scom.presence(spawn_data), max ), pilots end
gpl-3.0
telbbs/luci-0.12
libs/px5g/lua/px5g/util.lua
170
1148
--[[ * px5g - Embedded x509 key and certificate generator based on PolarSSL * * Copyright (C) 2009 Steven Barth <steven@midlink.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License, version 2.1 as published by the Free Software Foundation. ]]-- local nixio = require "nixio" local table = require "table" module "px5g.util" local preamble = { key = "-----BEGIN RSA PRIVATE KEY-----", cert = "-----BEGIN CERTIFICATE-----", request = "-----BEGIN CERTIFICATE REQUEST-----" } local postamble = { key = "-----END RSA PRIVATE KEY-----", cert = "-----END CERTIFICATE-----", request = "-----END CERTIFICATE REQUEST-----" } function der2pem(data, type) local b64 = nixio.bin.b64encode(data) local outdata = {preamble[type]} for i = 1, #b64, 64 do outdata[#outdata + 1] = b64:sub(i, i + 63) end outdata[#outdata + 1] = postamble[type] outdata[#outdata + 1] = "" return table.concat(outdata, "\n") end function pem2der(data) local b64 = data:gsub({["\n"] = "", ["%-%-%-%-%-.-%-%-%-%-%-"] = ""}) return nixio.bin.b64decode(b64) end
apache-2.0
Kthulupwns/darkstar
scripts/globals/items/messhikimaru.lua
21
1033
----------------------------------------- -- ID: 17826 -- Item: Messhikimaru -- Enchantment: Arcana Killer -- Durration: 10 Mins ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) if(target:hasStatusEffect(EFFECT_ENCHANTMENT) == false) then target:addStatusEffect(EFFECT_ENCHANTMENT,0,0,600,17826); end; end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_ARCANA_KILLER, 20); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_ARCANA_KILLER, 20); end;
gpl-3.0
Mleaf/mleaf_luci
modules/base/luasrc/sgi/cgi.lua
87
2260
--[[ LuCI - SGI-Module for CGI Description: Server Gateway Interface for CGI FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> 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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- exectime = os.clock() module("luci.sgi.cgi", package.seeall) local ltn12 = require("luci.ltn12") require("nixio.util") require("luci.http") require("luci.sys") require("luci.dispatcher") -- Limited source to avoid endless blocking local function limitsource(handle, limit) limit = limit or 0 local BLOCKSIZE = ltn12.BLOCKSIZE return function() if limit < 1 then handle:close() return nil else local read = (limit > BLOCKSIZE) and BLOCKSIZE or limit limit = limit - read local chunk = handle:read(read) if not chunk then handle:close() end return chunk end end end function run() local r = luci.http.Request( luci.sys.getenv(), limitsource(io.stdin, tonumber(luci.sys.getenv("CONTENT_LENGTH"))), ltn12.sink.file(io.stderr) ) local x = coroutine.create(luci.dispatcher.httpdispatch) local hcache = "" local active = true while coroutine.status(x) ~= "dead" do local res, id, data1, data2 = coroutine.resume(x, r) if not res then print("Status: 500 Internal Server Error") print("Content-Type: text/plain\n") print(id) break; end if active then if id == 1 then io.write("Status: " .. tostring(data1) .. " " .. data2 .. "\r\n") elseif id == 2 then hcache = hcache .. data1 .. ": " .. data2 .. "\r\n" elseif id == 3 then io.write(hcache) io.write("\r\n") elseif id == 4 then io.write(tostring(data1 or "")) elseif id == 5 then io.flush() io.close() active = false elseif id == 6 then data1:copyz(nixio.stdout, data2) data1:close() end end end end
apache-2.0
Kthulupwns/darkstar
scripts/zones/Yuhtunga_Jungle/npcs/Mupia_RK.lua
30
3052
----------------------------------- -- Area: Yuhtunga Jungle -- NPC: Mupia, R.K. -- Border Conquest Guards -- @pos -241.334 -1 478.602 123 ----------------------------------- package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Yuhtunga_Jungle/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ELSHIMOLOWLANDS; local csid = 0x7ffa; ----------------------------------- -- 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
Kthulupwns/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Gigirk.lua
34
1031
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Gigirk -- 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(0x0298); 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
agaran/protector
init.lua
1
16202
-- older privelage for admins to rbypass protected nodes, do not use anymore -- instead grant admin 'protection_bypass' privelage. -- 'delprotect' priv removed, use 'protection_bypass' instead --minetest.register_privilege("delprotect","Ignore player protection") -- get minetest.conf settings protector = {} protector.mod = "redo" protector.radius = tonumber(minetest.setting_get("protector_radius")) or 5 protector.drop = minetest.setting_getbool("protector_drop") or false protector.flip = minetest.setting_getbool("protector_flip") or false protector.hurt = tonumber(minetest.setting_get("protector_hurt")) or 0 protector.spawn = tonumber(minetest.setting_get("protector_spawn") or minetest.setting_get("protector_pvp_spawn")) or 0 -- get static spawn position local statspawn = minetest.setting_get_pos("static_spawnpoint") or {x = 0, y = 2, z = 0} -- Intllib local S if minetest.get_modpath("intllib") then S = intllib.Getter() else S = function(s, a, ...) if a == nil then return s end a = {a, ...} return s:gsub("(@?)@(%(?)(%d+)(%)?)", function(e, o, n, c) if e == ""then return a[tonumber(n)] .. (o == "" and c or "") else return "@" .. o .. n .. c end end) end end protector.intllib = S -- return list of members as a table protector.get_member_list = function(meta) return meta:get_string("members"):split(" ") end -- write member list table in protector meta as string protector.set_member_list = function(meta, list) meta:set_string("members", table.concat(list, " ")) end -- check if player name is a member protector.is_member = function (meta, name) for _, n in pairs(protector.get_member_list(meta)) do if n == name then return true end end return false end -- add player name to table as member protector.add_member = function(meta, name) if protector.is_member(meta, name) then return end local list = protector.get_member_list(meta) table.insert(list, name) protector.set_member_list(meta, list) end -- remove player name from table protector.del_member = function(meta, name) local list = protector.get_member_list(meta) for i, n in pairs(list) do if n == name then table.remove(list, i) break end end protector.set_member_list(meta, list) end -- protector interface protector.generate_formspec = function(meta) local formspec = "size[8,7]" .. default.gui_bg .. default.gui_bg_img .. default.gui_slots .. "label[2.5,0;" .. S("-- Protector interface --") .. "]" .. "label[0,1;" .. S("PUNCH node to show protected area or USE for area check") .. "]" .. "label[0,2;" .. S("Members:") .. "]" .. "button_exit[2.5,6.2;3,0.5;close_me;" .. S("Close") .. "]" local members = protector.get_member_list(meta) local npp = 12 -- max users added to protector list local i = 0 for n = 1, #members do if i < npp then -- show username formspec = formspec .. "button[" .. (i % 4 * 2) .. "," .. math.floor(i / 4 + 3) .. ";1.5,.5;protector_member;" .. members[n] .. "]" -- username remove button .. "button[" .. (i % 4 * 2 + 1.25) .. "," .. math.floor(i / 4 + 3) .. ";.75,.5;protector_del_member_" .. members[n] .. ";X]" end i = i + 1 end if i < npp then -- user name entry field formspec = formspec .. "field[" .. (i % 4 * 2 + 1 / 3) .. "," .. (math.floor(i / 4 + 3) + 1 / 3) .. ";1.433,.5;protector_add_member;;]" -- username add button .."button[" .. (i % 4 * 2 + 1.25) .. "," .. math.floor(i / 4 + 3) .. ";.75,.5;protector_submit;+]" end return formspec end -- check if pos is inside a protected spawn area local function inside_spawn(pos, radius) if protector.spawn <= 0 then return false end if pos.x < statspawn.x + radius and pos.x > statspawn.x - radius and pos.y < statspawn.y + radius and pos.y > statspawn.y - radius and pos.z < statspawn.z + radius and pos.z > statspawn.z - radius then return true end return false end -- Infolevel: -- 0 for no info -- 1 for "This area is owned by <owner> !" if you can't dig -- 2 for "This area is owned by <owner>. -- 3 for checking protector overlaps protector.can_dig = function(r, pos, digger, onlyowner, infolevel) if not digger or not pos then return false end -- delprotect and protector_bypass privileged users can override protection if ( minetest.check_player_privs(digger, {delprotect = true}) or minetest.check_player_privs(digger, {protection_bypass = true}) ) and infolevel == 1 then return true end -- infolevel 3 is only used to bypass priv check, change to 1 now if infolevel == 3 then infolevel = 1 end -- is spawn area protected ? if inside_spawn(pos, protector.spawn) then minetest.chat_send_player(digger, S("Spawn @1 has been protected up to a @2 block radius.", minetest.pos_to_string(statspawn), protector.spawn)) return false end -- find the protector nodes local pos = minetest.find_nodes_in_area( {x = pos.x - r, y = pos.y - r, z = pos.z - r}, {x = pos.x + r, y = pos.y + r, z = pos.z + r}, {"protector:protect", "protector:protect2"}) local meta, owner, members for n = 1, #pos do meta = minetest.get_meta(pos[n]) owner = meta:get_string("owner") or "" members = meta:get_string("members") or "" -- node change and digger isn't owner if owner ~= digger and infolevel == 1 then -- and you aren't on the member list if onlyowner or not protector.is_member(meta, digger) then minetest.chat_send_player(digger, S("This area is owned by @1!", owner)) return false end end -- when using protector as tool, show protector information if infolevel == 2 then minetest.chat_send_player(digger, S("This area is owned by @1.", owner)) minetest.chat_send_player(digger, S("Protection located at: @1", minetest.pos_to_string(pos[n]))) if members ~= "" then minetest.chat_send_player(digger, S("Members: @1.", members)) end return false end end -- show when you can build on unprotected area if infolevel == 2 then if #pos < 1 then minetest.chat_send_player(digger, S("This area is not protected.")) end minetest.chat_send_player(digger, S("You can build here.")) end return true end protector.old_is_protected = minetest.is_protected -- check for protected area, return true if protected and digger isn't on list function minetest.is_protected(pos, digger) -- is area protected against digger? if not protector.can_dig(protector.radius, pos, digger, false, 1) then local player = minetest.get_player_by_name(digger) -- hurt player if protection violated if protector.hurt > 0 and player then player:set_hp(player:get_hp() - protector.hurt) end -- flip player when protection violated if protector.flip and player then -- yaw + 180° --local yaw = player:get_look_horizontal() + math.pi local yaw = player:get_look_yaw() + math.pi if yaw > 2 * math.pi then yaw = yaw - 2 * math.pi end --player:set_look_horizontal(yaw) player:set_look_yaw(yaw) -- invert pitch --player:set_look_vertical(-player:get_look_vertical()) player:set_look_pitch(-player:get_look_pitch()) -- if digging below player, move up to avoid falling through hole local pla_pos = player:getpos() if pos.y < pla_pos.y then player:setpos({ x = pla_pos.x, y = pla_pos.y + 0.8, z = pla_pos.z }) end end -- drop tool/item if protection violated if protector.drop == true and player then local holding = player:get_wielded_item() if holding:to_string() ~= "" then -- take stack local sta = holding:take_item(holding:get_count()) player:set_wielded_item(holding) -- incase of lag, reset stack minetest.after(0.1, function() player:set_wielded_item(holding) -- drop stack local obj = minetest.add_item(player:getpos(), sta) if obj then obj:setvelocity({x = 0, y = 5, z = 0}) end end) end end return true end -- otherwise can dig or place return protector.old_is_protected(pos, digger) end -- make sure protection block doesn't overlap another protector's area function protector.check_overlap(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end local pos = pointed_thing.above -- make sure protector doesn't overlap onto protected spawn area if inside_spawn(pos, protector.spawn + protector.radius) then minetest.chat_send_player(placer:get_player_name(), S("Spawn @1 has been protected up to a @2 block radius.", minetest.pos_to_string(statspawn), protector.spawn)) return itemstack end -- make sure protector doesn't overlap any other player's area if not protector.can_dig(protector.radius * 2, pos, placer:get_player_name(), true, 3) then minetest.chat_send_player(placer:get_player_name(), S("Overlaps into above players protected area")) return itemstack end return minetest.item_place(itemstack, placer, pointed_thing) end -- protection node minetest.register_node("protector:protect", { description = S("Protection Block"), drawtype = "nodebox", tiles = { "moreblocks_circle_stone_bricks.png", "moreblocks_circle_stone_bricks.png", "moreblocks_circle_stone_bricks.png^protector_logo.png" }, sounds = default.node_sound_stone_defaults(), groups = {dig_immediate = 2, unbreakable = 1}, is_ground_content = false, paramtype = "light", light_source = 4, node_box = { type = "fixed", fixed = { {-0.5 ,-0.5, -0.5, 0.5, 0.5, 0.5}, } }, on_place = protector.check_overlap, after_place_node = function(pos, placer) local meta = minetest.get_meta(pos) meta:set_string("owner", placer:get_player_name() or "") meta:set_string("infotext", S("Protection (owned by @1)", meta:get_string("owner"))) meta:set_string("members", "") end, on_use = function(itemstack, user, pointed_thing) if pointed_thing.type ~= "node" then return end protector.can_dig(protector.radius, pointed_thing.under, user:get_player_name(), false, 2) end, on_rightclick = function(pos, node, clicker, itemstack) local meta = minetest.get_meta(pos) if meta and protector.can_dig(1, pos,clicker:get_player_name(), true, 1) then minetest.show_formspec(clicker:get_player_name(), "protector:node_" .. minetest.pos_to_string(pos), protector.generate_formspec(meta)) end end, on_punch = function(pos, node, puncher) if minetest.is_protected(pos, puncher:get_player_name()) then return end minetest.add_entity(pos, "protector:display") end, can_dig = function(pos, player) return protector.can_dig(1, pos, player:get_player_name(), true, 1) end, on_blast = function() end, }) minetest.register_craft({ output = "protector:protect", recipe = { {"default:stone", "default:stone", "default:stone"}, {"default:stone", "default:steel_ingot", "default:stone"}, {"default:stone", "default:stone", "default:stone"}, } }) -- protection logo minetest.register_node("protector:protect2", { description = S("Protection Logo"), tiles = {"protector_logo.png"}, wield_image = "protector_logo.png", inventory_image = "protector_logo.png", sounds = default.node_sound_stone_defaults(), groups = {dig_immediate = 2, unbreakable = 1}, paramtype = 'light', paramtype2 = "wallmounted", legacy_wallmounted = true, light_source = 4, drawtype = "nodebox", sunlight_propagates = true, walkable = true, node_box = { type = "wallmounted", wall_top = {-0.375, 0.4375, -0.5, 0.375, 0.5, 0.5}, wall_bottom = {-0.375, -0.5, -0.5, 0.375, -0.4375, 0.5}, wall_side = {-0.5, -0.5, -0.375, -0.4375, 0.5, 0.375}, }, selection_box = {type = "wallmounted"}, on_place = protector.check_overlap, after_place_node = function(pos, placer) local meta = minetest.get_meta(pos) meta:set_string("owner", placer:get_player_name() or "") meta:set_string("infotext", S("Protection (owned by @1)", meta:get_string("owner"))) meta:set_string("members", "") end, on_use = function(itemstack, user, pointed_thing) if pointed_thing.type ~= "node" then return end protector.can_dig(protector.radius, pointed_thing.under, user:get_player_name(), false, 2) end, on_rightclick = function(pos, node, clicker, itemstack) local meta = minetest.get_meta(pos) if protector.can_dig(1, pos, clicker:get_player_name(), true, 1) then minetest.show_formspec(clicker:get_player_name(), "protector:node_" .. minetest.pos_to_string(pos), protector.generate_formspec(meta)) end end, on_punch = function(pos, node, puncher) if minetest.is_protected(pos, puncher:get_player_name()) then return end minetest.add_entity(pos, "protector:display") end, can_dig = function(pos, player) return protector.can_dig(1, pos, player:get_player_name(), true, 1) end, on_blast = function() end, }) minetest.register_craft({ output = "protector:protect2", recipe = { {"default:stone", "default:stone", "default:stone"}, {"default:stone", "default:copper_ingot", "default:stone"}, {"default:stone", "default:stone", "default:stone"}, } }) -- check formspec buttons or when name entered minetest.register_on_player_receive_fields(function(player, formname, fields) -- protector formspec found if string.sub(formname, 0, string.len("protector:node_")) == "protector:node_" then local pos_s = string.sub(formname, string.len("protector:node_") + 1) local pos = minetest.string_to_pos(pos_s) local meta = minetest.get_meta(pos) -- only owner can add names if not protector.can_dig(1, pos, player:get_player_name(), true, 1) then return end -- add member [+] if fields.protector_add_member then for _, i in pairs(fields.protector_add_member:split(" ")) do protector.add_member(meta, i) end end -- remove member [x] for field, value in pairs(fields) do if string.sub(field, 0, string.len("protector_del_member_")) == "protector_del_member_" then protector.del_member(meta, string.sub(field,string.len("protector_del_member_") + 1)) end end -- reset formspec until close button pressed if not fields.close_me then minetest.show_formspec(player:get_player_name(), formname, protector.generate_formspec(meta)) end end end) -- display entity shown when protector node is punched minetest.register_entity("protector:display", { physical = false, collisionbox = {0, 0, 0, 0, 0, 0}, visual = "wielditem", -- wielditem seems to be scaled to 1.5 times original node size visual_size = {x = 1.0 / 1.5, y = 1.0 / 1.5}, textures = {"protector:display_node"}, timer = 0, on_step = function(self, dtime) self.timer = self.timer + dtime -- remove after 5 seconds if self.timer > 5 then self.object:remove() end end, }) -- Display-zone node, Do NOT place the display as a node, -- it is made to be used as an entity (see above) local x = protector.radius minetest.register_node("protector:display_node", { tiles = {"protector_display.png"}, use_texture_alpha = true, walkable = false, drawtype = "nodebox", node_box = { type = "fixed", fixed = { -- sides {-(x+.55), -(x+.55), -(x+.55), -(x+.45), (x+.55), (x+.55)}, {-(x+.55), -(x+.55), (x+.45), (x+.55), (x+.55), (x+.55)}, {(x+.45), -(x+.55), -(x+.55), (x+.55), (x+.55), (x+.55)}, {-(x+.55), -(x+.55), -(x+.55), (x+.55), (x+.55), -(x+.45)}, -- top {-(x+.55), (x+.45), -(x+.55), (x+.55), (x+.55), (x+.55)}, -- bottom {-(x+.55), -(x+.55), -(x+.55), (x+.55), -(x+.45), (x+.55)}, -- middle (surround protector) {-.55,-.55,-.55, .55,.55,.55}, }, }, selection_box = { type = "regular", }, paramtype = "light", groups = {dig_immediate = 3, not_in_creative_inventory = 1}, drop = "", }) local path = minetest.get_modpath("protector") dofile(path .. "/doors_chest.lua") dofile(path .. "/pvp.lua") dofile(path .. "/admin.lua") dofile(path .. "/tool.lua") dofile(path .. "/lucky_block.lua") -- stop mesecon pistons from pushing protectors if minetest.get_modpath("mesecons_mvps") then mesecon.register_mvps_stopper("protector:protect") mesecon.register_mvps_stopper("protector:protect2") mesecon.register_mvps_stopper("protector:chest") end print (S("[MOD] Protector Redo loaded"))
mit
AGTMADCAT/naev
dat/missions/flf/flf_pre02.lua
3
18115
--[[ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. 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. -- This is the second "prelude" mission leading to the FLF campaign. stack variable flfbase_intro: 1 - The player has turned in the FLF agent or rescued the Dvaered crew. Conditional for dv_antiflf02 2 - The player has rescued the FLF agent. Conditional for flf_pre02 3 - The player has found the FLF base for the Dvaered, or has betrayed the FLF after rescuing the agent. Conditional for dv_antiflf03 --]] include "fleethelper.lua" include "dat/missions/flf/flf_patrol.lua" -- localization stuff, translators would work here lang = naev.lang() if lang == "es" then else -- default english title = {} text = {} DVtitle = {} DVtext = {} osd_desc = {} DVosd = {} refuelmsg = {} title[1] = "A chance to prove yourself" text[1] = [[The FLF officer doesn't seem at all surprised that you approached her. On the contrary, she looks like she expected you to do so all along. "Greetings," she says, nodding at you in curt greeting. "I am Corporal Benito. And you must be %s, the one who got Lt. Fletcher back here in one piece." Benito's expression becomes a little more severe. "I'm not here to exchange pleasantries, however. You probably noticed, but people here are a little uneasy about your presence. They don't know what to make of you, see. You helped us once, it is true, but that doesn't tell us much. We don't know you."]] text[2] = [[Indeed, you are constantly aware of the furtive glances the other people in this bar are giving you. They don't seem outright hostile, but you can tell that if you don't watch your step and choose your words carefully, things might quickly take a turn for the worse. Benito waves her hand to indicate you needn't pay them any heed. "That said, the upper ranks have decided that if you are truly sympathetic to our cause, you will be given an opportunity to prove yourself. Of course, if you'd rather not get involved in our struggle, that's understandable. But if you're in for greater things, if you stand for justice... Perhaps you'll consider joining with us?"]] title[3] = "Patrol-B-gone" text[3] = [["I'm happy to hear that. It's good to know we still have the support from the common man. Anyway, let me fill you in on what it is we want you to do. As you may be aware, the Dvaered have committed a lot of resources to finding us and flushing us out lately. And while our base is well hidden, those constant patrols are certainly not doing anything to make us feel more secure! I think you can see where this is going. You will go out there and eliminate one of those patrols in the %s system." You object, asking the Corporal if all recruits have to undertake dangerous missions like this to be accepted into the FLF ranks. Benito chuckles, and makes a pacifying gesture. "Calm down, it's not as bad as it sounds. You only have to take out one small patrol; I don't think you will have to fight more than 3 ships, 4 if you're really unlucky. If you think that's too much for you, you can abort the mission for now and come to me again later. Otherwise, good luck!"]] title[4] = "Breaking the ice" text[4] = [[When you left Sindbad Station, it was a cold, lonely place for you. The FLF soldiers on the station avoided you whenever they could, and basic services were harder to get than they should have been. But now that you have returned victorious over the Dvaered, the place has become considerably more hospitable. There are more smiles on people's faces, and some even tell you you did a fine job. Among them is Corporal Benito. She walks up to you and offers you her hand.]] text[5] = [["Welcome back, %s, and congratulations. I didn't expect the Dvaered to send reinforcements, much less a Vigilance. I certainly wouldn't have sent you alone if I did, and I might not have sent you at all. But then, you're still in one piece, so maybe I shouldn't worry so much, eh?"]] text[6] = [[Benito takes you to the station's bar, and buys you what for lack of a better word must be called a drink. "We will of course reward you for your service," she says once you are seated. "Though you must understand the FLF doesn't have that big a budget. Financial support is tricky, and the Frontier doesn't have that much to spare themselves to begin with. Nevertheless, we are willing to pay for good work, and your work is nothing but. What's more, you've ingratiated yourself with many of us, as you've undoubtedly noticed. Our top brass are among those you've impressed, so from today on, you can call yourself one of us! How about that, huh?"]] text[7] = [["Of course, our work is only just beginning. No rest for the weary; we must continue the fight against the oppressors. I'm sure the road is still long, but I'm encouraged by the fact that we gained another valuable ally today. Check the mission computer for more tasks you can help us with. I'm sure you'll play an important role in our eventual victory over the Dvaered!" That last part earns a cheer from the assembled FLF soldiers. You decide to raise your glass with them, making a toast to the fortune of battle in the upcoming campaign - and the sweet victory that lies beyond.]] refusetitle = "Some other time perhaps" refusetext = [["I see. That's a fair answer, I'm sure you have your reasons. But if you ever change your mind, I'll be around on Sindbad. You won't have trouble finding me, I'm sure."]] DVtitle[1] = "A tempting offer" DVtext[1] = [[Your viewscreen shows a Dvaered Colonel. He looks tense. Normally, a tense Dvaered would be bad news, but then this one bothered to hail you in the heat of battle, so perhaps there is more here than meets the eye.]] DVtext[2] = [["I am Colonel Urnus of the Dvaered Fleet, anti-terrorism division. I would normally never contact an enemy of House Dvaered, but my intelligence officer has looked through our records and found that you were recently a law-abiding citizen, doing honest freelance missions."]] DVtext[3] = [["I know your type, %s. You take jobs where profit is to be had, and you side with the highest bidder. There are many like you in the galaxy, though admittedly not so many with your talent. That's why I'm willing to make you this offer: you will provide us with information on their base of operations and their combat strength. In return, I will convince my superiors that you were working for me all along, so you won't face any repercussions for assaulting Dvaered ships. Furthermore, I will transfer a considerable amount of credits in your account, as well as put you into a position to make an ally out of House Dvaered. If you refuse, however, I guarantee you that you will never again be safe in Dvaered space. What say you? Surely this proposition beats anything that rabble can do for you?"]] DVchoice1 = "Accept the offer" DVchoice2 = "Remain loyal to the FLF" DVtitle[4] = "Opportunism is an art" DVtext[4] = [[Colonel Urnus smiles broadly. "I knew you'd make the right choice, citizen!" He addresses someone on his bridge, out of the view of the camera. "Notify the flight group. This ship is now friendly. Cease fire." Then he turns back to you. "Proceed to %s in the %s system, citizen. I will personally meet you there."]] DVtitle[5] = "End of negotiations" DVtext[5] = [[Colonel Urnus is visibly annoyed by your response. "Very well then," he bites at you. "In that case you will be destroyed along with the rest of that terrorist scum. Helm, full speed ahead! All batteries, fire at will!"]] DVtitle[6] = "A reward for a job well botched" DVtext[6] = [[Soon after docking, you are picked up by a couple of soldiers, who escort you to Colonel Urnus' office. Urnus greets you warmly, and offers you a seat and a cigar. You take the former, not the latter. "I am most pleased with the outcome of this situation, citizen," Urnus begins. "To be absolutely frank with you, I was beginning to get frustrated. My superiors have been breathing down my neck, demanding results on those blasted FLF, but they are as slippery as eels. Just when you think you've cornered them, poof! They're gone, lost in that nebula. Thick as soup, that thing. I don't know how they can even find their own way home!"]] DVtext[7] = [[Urnus takes a puff of his cigar and blows out a ring of smoke. It doesn't take a genius to figure out you're the best thing that's happened to him in a long time. "Anyway. I promised you money, status and opportunities, and I intend to make good on those promises. Your money is already in your account. Check your balance sheet later. As for status, I can assure you that no Dvaered will find out what you've been up to. As far as the military machine is concerned, you have nothing to do with the FLF. In fact, you're known as an important ally in the fight against them! Finally, opportunities. We're analyzing the data from your flight recorder as we speak, and you'll be asked a few questions after we're done here. Based on that, we can form a new strategy against the FLF. Unless I miss my guess by a long shot, we'll be moving against them in force very soon, and I will make sure you'll be given the chance to be part of that. I'm sure it'll be worth your while."]] DVtext[8] = [[Urnus stands up, a sign that this meeting is drawing to a close. "Keep your eyes open for one of our liaisons, citizen. He'll be your ticket into the upcoming battle. Now, I'm a busy man so I'm going to have to ask you to leave. But I hope we'll meet again, and if you continue to build your career like you have today, I'm sure we will. Good day to you!" You leave the Colonel's office. You are then taken to an interrogation room, where Dvaered petty officers question you politely yet persistently about your brief stay with the FLF. Once their curiosity is satisfied, they let you go, and you are free to return to your ship.]] flfcomm = {} flfcomm[1] = "We have your back, %s!" flfcomm[2] = "%s is selling us out! Eliminate the traitor!" flfcomm[3] = "Let's get out of here, %s! We'll meet you back at the base." misn_title = "FLF: Small Dvaered Patrol in %s" misn_desc = "To prove yourself to the FLF, you must take out one of the Dvaered security patrols." misn_rwrd = "A chance to make friends with the FLF." osd_title = "Dvaered Patrol" osd_desc[1] = "Fly to the %s system" osd_desc[2] = "Eliminate the Dvaered patrol" osd_desc[3] = "Return to the FLF base" osd_desc["__save"] = true DVosd[1] = "Fly to the %s system and land on %s" DVosd["__save"] = true npc_name = "FLF petty officer" npc_desc = "There is a low-ranking officer of the Frontier Liberation Front sitting at one of the tables. She seems somewhat more receptive than most people in the bar." end function create () missys = patrol_getTargetSystem() if not misn.claim( missys ) then misn.finish( false ) end misn.setNPC( npc_name, "flf/unique/benito" ) misn.setDesc( npc_desc ) end function accept () tk.msg( title[1], text[1]:format( player.name() ) ) if tk.yesno( title[1], text[2] ) then tk.msg( title[3], text[3]:format( missys:name() ) ) osd_desc[1] = osd_desc[1]:format( missys:name() ) misn.accept() misn.osdCreate( osd_title, osd_desc ) misn.setDesc( misn_desc ) misn.setTitle( misn_title:format( missys:name() ) ) marker = misn.markerAdd( missys, "low" ) misn.setReward( misn_rwrd ) DVplanet = "Raelid Outpost" DVsys = "Raelid" reinforcements_arrived = false dv_ships_left = 0 job_done = false hook.enter( "enter" ) hook.jumpout( "leave" ) hook.land( "leave" ) else tk.msg( refusetitle, refusetext ) misn.finish( false ) end end function enter () if not job_done then if system.cur() == missys then misn.osdActive( 2 ) patrol_spawnDV( 3, nil ) else misn.osdActive( 1 ) end end end function leave () if spawner ~= nil then hook.rm( spawner ) end if hailer ~= nil then hook.rm( hailer ) end if rehailer ~= nil then hook.rm( rehailer ) end reinforcements_arrived = false dv_ships_left = 0 end function spawnDVReinforcements () reinforcements_arrived = true local dist = 1500 local x local y if rnd.rnd() < 0.5 then x = dist else x = -dist end if rnd.rnd() < 0.5 then y = dist else y = -dist end local pos = player.pos() + vec2.new( x, y ) local reinforcements = pilot.add( "Dvaered Big Patrol", "dvaered_norun", pos ) for i, j in ipairs( reinforcements ) do if j:ship():class() == "Destroyer" then boss = j end hook.pilot( j, "death", "pilot_death_dv" ) j:setHostile() j:setVisible( true ) j:setHilight( true ) fleetDV[ #fleetDV + 1 ] = j dv_ships_left = dv_ships_left + 1 end -- Check for defection possibility if faction.playerStanding( "Dvaered" ) >= -5 then hailer = hook.timer( 30000, "timer_hail" ) else spawner = hook.timer( 30000, "timer_spawnFLF" ) end end function timer_hail () if hailer ~= nil then hook.rm( hailer ) end if boss ~= nil and boss:exists() then timer_rehail() hailer = hook.pilot( boss, "hail", "hail" ) end end function timer_rehail () if rehailer ~= nil then hook.rm( rehailer ) end if boss ~= nil and boss:exists() then boss:hailPlayer() rehailer = hook.timer( 8000, "timer_rehail" ) end end function hail () if hailer ~= nil then hook.rm( hailer ) end if rehailer ~= nil then hook.rm( rehailer ) end player.commClose() tk.msg( DVtitle[1], DVtext[1] ) tk.msg( DVtitle[1], DVtext[2] ) choice = tk.choice( DVtitle[1], DVtext[3]:format( player.name() ), DVchoice1, DVchoice2 ) if choice == 1 then tk.msg( DVtitle[4], DVtext[4]:format( DVplanet, DVsys ) ) faction.get("FLF"):setPlayerStanding( -100 ) local standing = faction.get("Dvaered"):playerStanding() if standing < 0 then faction.get("Dvaered"):setPlayerStanding( 0 ) end for i, j in ipairs( fleetDV ) do if j:exists() then j:setFriendly() j:changeAI( "dvaered" ) end end job_done = true osd_desc[1] = DVosd[1]:format( DVsys, DVplanet ) osd_desc[2] = nil misn.osdActive( 1 ) misn.osdCreate( misn_title, osd_desc ) misn.markerRm( marker ) marker = misn.markerAdd( system.get(DVsys), "high" ) spawner = hook.timer( 3000, "timer_spawnHostileFLF" ) hook.land( "land_dv" ) else tk.msg( DVtitle[5], DVtext[5] ) timer_spawnFLF() end end function spawnFLF () local dist = 1500 local x local y if rnd.rnd() < 0.5 then x = dist else x = -dist end if rnd.rnd() < 0.5 then y = dist else y = -dist end local pos = player.pos() + vec2.new( x, y ) fleetFLF = addShips( { "FLF Vendetta", "FLF Lancelot" }, "flf_norun", pos, 8 ) end function timer_spawnFLF () if boss ~= nil and boss:exists() then spawnFLF() for i, j in ipairs( fleetFLF ) do j:setFriendly() j:setVisplayer( true ) end fleetFLF[1]:broadcast( flfcomm[1]:format( player.name() ) ) end end function timer_spawnHostileFLF () spawnFLF() for i, j in ipairs( fleetFLF ) do j:setHostile() j:control() j:attack( player.pilot() ) end hook.pilot( player.pilot(), "death", "returnFLFControl" ) fleetFLF[1]:broadcast( flfcomm[2]:format( player.name() ) ) end function returnFLFControl() for i, j in ipairs( fleetFLF ) do j:control( false ) end end function pilot_death_dv () dv_ships_left = dv_ships_left - 1 if dv_ships_left <= 0 then if spawner ~= nil then hook.rm( spawner ) end if hailer ~= nil then hook.rm( hailer ) end if rehailer ~= nil then hook.rm( rehailer ) end job_done = true local standing = faction.get("Dvaered"):playerStanding() if standing >= 0 then faction.get("Dvaered"):setPlayerStanding( -1 ) end misn.osdActive( 3 ) misn.markerRm( marker ) marker = misn.markerAdd( system.get( var.peek( "flfbase_sysname" ) ), "high" ) hook.land( "land_flf" ) pilot.toggleSpawn( true ) local hailed = false if fleetFLF ~= nil then for i, j in ipairs( fleetFLF ) do if j:exists() then j:control() j:hyperspace() if not hailed then hailed = true j:comm( player.pilot(), flfcomm[3]:format( player.name() ) ) end end end end elseif dv_ships_left <= 1 and not reinforcements_arrived then spawnDVReinforcements() end end function land_flf () leave() if planet.cur():name() == "Sindbad" then tk.msg( title[4], text[4] ) tk.msg( title[4], text[5]:format( player.name() ) ) tk.msg( title[4], text[6] ) tk.msg( title[4], text[7] ) player.pay( 100000 ) var.push( "_fcap_flf", 20 ) faction.get("FLF"):modPlayer( 15 ) var.pop( "flfbase_sysname" ) var.pop( "flfbase_intro" ) misn.finish( true ) end end function land_dv () leave() if planet.cur():name() == DVplanet then tk.msg( DVtitle[6], DVtext[6] ) tk.msg( DVtitle[6], DVtext[7] ) tk.msg( DVtitle[6], DVtext[8] ) player.pay( 70000 ) var.push( "flfbase_intro", 3 ) if diff.isApplied( "FLF_base" ) then diff.remove( "FLF_base" ) end misn.finish( true ) end end
gpl-3.0
Kthulupwns/darkstar
scripts/zones/Cloister_of_Frost/bcnms/class_reunion.lua
13
1526
----------------------------------- -- Area: Cloister of Tremors -- BCNM: Class Reunion ----------------------------------- package.loaded["scripts/zones/Cloister_of_Frost/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Cloister_of_Frost/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,2); elseif(leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01 and player:getVar("ClassReunionProgress") == 5) then player:setVar("ClassReunionProgress",6); end; end;
gpl-3.0
junrw/ember-gsoc2012
src/components/ogre/widgets/Give.lua
2
2932
----------------------------------------- --A widget for giving something from the inventory to someone. Right now just shows a list of stuff that can be given. This will need to be extended to something much nicer. Perhaps even something which interacts with other inventory widgets. ----------------------------------------- Give = {} function Give:buildWidget(avatar) self.widget = guiManager:createWidget() self.widget:loadMainSheet("Give.layout", "Give/") self.widget:hide() connect(self.connectors, avatar.EventAddedEntityToInventory, self.addedEntity, self) connect(self.connectors, avatar.EventRemovedEntityFromInventory, self.removedEntity, self) giveButton = self.widget:getWindow("Give") giveButton:subscribeEvent("Clicked", self.Give_Click, self) cancelButton = self.widget:getWindow("Cancel") cancelButton:subscribeEvent("Clicked", self.Cancel_Click, self) connect(self.connectors, guiManager.EventEntityAction, self.handleAction, self) local widget = self.widget:getWindow("ListBox") self.listbox = CEGUI.toListbox(widget) end function Give:addedEntity(entity) local name = entity:getType():getName() .. " (" .. entity:getId() .. " : " .. entity:getName() .. ")" local item = Ember.OgreView.Gui.ColouredListItem:new(name, entity:getId(), entity) self.listboxMap[entity] = item --we need to cast it down self.listbox:addItem(item) end function Give:removedEntity(entity) local item = self.listboxMap[entity]; if item ~= nil then self.listbox:removeItem(tolua.cast(item, "CEGUI::ListboxItem")) self.listboxMap[entity] = nil end end function Give:Give_Click(args) local item = self.listbox:getFirstSelectedItem() while (item ~= nil) do local entityId = item:getID() local entity = emberOgre:getWorld():getEmberEntity(entityId); if (entity ~= nil) then emberOgre:doWithEntity(self.targetEntityId, function (targetEntity) emberServices:getServerService():place(entity, targetEntity) end) end item = self.listbox:getNextSelected(item) end end function Give:Cancel_Click(args) self.widget:hide() end function Give:handleAction(action, entity) if action == "give" then self:show(entity) end end function Give:show(entity) self.targetEntityId = entity:getId() self.widget:show() local textWidget = self.widget:getWindow("Text") local text = "Give to " .. entity:getName() .. " ( a " .. entity:getType():getName() .. ")" textWidget:setText(text) end function Give:shutdown() disconnectAll(self.connectors) guiManager:destroyWidget(self.widget) end Give.startConnector = createConnector(emberOgre.EventCreatedAvatarEntity):connect(function() local give = {connectors={}, listbox = nil, targetEntityId = nil, listboxMap = {}} setmetatable(give, {__index = Give}) give:buildWidget(emberOgre:getWorld():getAvatar()) connect(give.connectors, emberOgre.EventWorldDestroyed, function() give:shutdown() give = nil end ) end )
gpl-3.0
MmxBoy/Metal-bot-V.2
plugins/inv.lua
46
1079
do local function callbackres(extra, success, result) local user = 'user#id'..result.id local chat = 'chat#id'..extra.chatid if is_banned(result.id, extra.chatid) then send_large_msg(chat, 'User is banned.') elseif is_gbanned(result.id) then send_large_msg(chat, 'User is globaly banned.') else chat_add_user(chat, user, ok_cb, false) end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' then return end if not is_momod(msg) then return end if not is_admin(msg) then return 'Only admins can invite.' end local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") res_user(username, callbackres, cbres_extra) end return { patterns = { "^[!/$&#@]invite (.*)$", "^([Ii]nvite (.*)$" }, run = run } end
gpl-2.0
Kthulupwns/darkstar
scripts/zones/Stellar_Fulcrum/Zone.lua
15
2251
----------------------------------- -- -- Zone: Stellar_Fulcrum -- ----------------------------------- package.loaded["scripts/zones/Stellar_Fulcrum/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Stellar_Fulcrum/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) zone:registerRegion(1, -522, -2, -49, -517, -1, -43); -- To Upper Delkfutt's Tower zone:registerRegion(2, 318, -3, 2, 322, 1, 6); -- Exit BCNM to ? 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:getCurrentMission(ZILART) == RETURN_TO_DELKFUTTS_TOWER and player:getVar("ZilartStatus") == 2) then cs = 0x0000; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) player:startEvent(8); end, [2] = function (x) player:startEvent(8); end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(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); if(csid == 8 and option == 1) then player:setPos(-370, -178, -40, 243, 0x9e); elseif(csid == 0x0000) then player:setVar("ZilartStatus",3); end end;
gpl-3.0
Kthulupwns/darkstar
scripts/zones/Stellar_Fulcrum/npcs/_4z0.lua
12
1593
----------------------------------- -- Area: Stellar Fulcrum -- Door: Qe'Lov Gate -- @pos -520 -4 17 179 ------------------------------------- package.loaded["scripts/zones/Stellar_Fulcrum/TextIDs"] = nil; package.loaded["scripts/globals/bcnm"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/missions"); require("scripts/zones/Stellar_Fulcrum/TextIDs"); -- events: -- 7D00 : BC menu -- Param 4 is a bitmask for the choice of battlefields in the menu: -- 1/0: Zilart Mission 8 -- 2/1: -- 3/2: ----------------------------------- -- onTrigger Action ----------------------------------- function onTrade(player,npc,trade) if(TradeBCNM(player,player:getZoneID(),trade,npc))then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(EventTriggerBCNM(player,npc))then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if(EventUpdateBCNM(player,csid,option))then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if(EventFinishBCNM(player,csid,option))then return; end end;
gpl-3.0
Kthulupwns/darkstar
scripts/globals/mobskills/Thundris_Shriek.lua
6
1047
--------------------------------------------- -- Thundris Shriek -- -- Description: Deals heavy lightning damage to targets in area of effect. Additional effect: Terror -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: Unknown -- Notes: Players will begin to be intimidated by the dvergr after this attack. --------------------------------------------- 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) local typeEffect = EFFECT_TERROR; MobStatusEffectMove(mob, target, typeEffect, 1, 0, 60); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_THUNDER,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_THUNDER,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
mlody1039/ModernOts
data/npc/scripts/Training Assistant.lua
1
2123
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) -- OTServ event handling functions start function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end -- OTServ event handling functions end -- Don"t forget npcHandler = npcHandler in the parameters. It is required for all StdModule functions! local travelNode = keywordHandler:addKeyword({"training"}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "Do you want to sail to Treiner " .. (getConfigInfo("freeTravel") and "free?" or "?")}) travelNode:addChildKeyword({"yes"}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 0, cost = 0, destination = {x=32557, y=32384, z=7} }) travelNode:addChildKeyword({"no"}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = "We would like to serve you some time."}) local travelNode = keywordHandler:addKeyword({"treiner"}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "Do you want to sail to Treiner " .. (getConfigInfo("freeTravel") and "free?" or "?")}) travelNode:addChildKeyword({"yes"}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 0, cost = 0, destination = {x=32557, y=32384, z=7} }) travelNode:addChildKeyword({"no"}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = "We would like to serve you some time."}) keywordHandler:addKeyword({"sail"}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "Where do you want to go? To Treiner."}) keywordHandler:addKeyword({"job"}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "I am the captain of this ship."}) keywordHandler:addKeyword({"captain"}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "I am the captain of this ship."}) npcHandler:addModule(FocusModule:new())
gpl-3.0
CCAAHH/x
bot/utils.lua
356
14963
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 superuser 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 -- user has admins privileges 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 -- user has moderator privileges 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['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 -- 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) -- Berfungsi utk mengecek user jika plugin moderated = true if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers return false end end end -- Berfungsi mengecek user jika plugin privileged = true 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
gpl-2.0
pmachowski/growl-lua
growl.lua
1
2725
-- -- Code by Piotr Machowski <piotr@machowski.co> -- local Growl = {} Growl.__n = 'GrowlNotifications' Growl.set = {} Growl.isAnimating = false --global config Growl.SHOW_TIME = 5000 Growl.FONT_SIZE = 8 Growl.NOTIFICATION_WIDTH = display.contentWidth*.25 --private functions function Growl:_removeNotification( _n ) for i,v in ipairs(self.set) do if _n == v then table.remove( self.set, i ) end end end function Growl:_moveNotifications( ) if self.isAnimating then -- speed move transition.cancel( Growl.__n ) for i,v in ipairs(self.set) do v.x, v.y = v.nx, v.ny end end self.isAnimating=true --remove those not in the viewport for i=#self.set,1 do if self.set[i].y > display.contentHeight then self.set[i]:removeSelf() end end --animate self.set[1].tween = transition.to( self.set[1], {tag=Growl.__n, x=self.set[1].nx, time=200, easing=easing.outExpo, onComplete=function( ) Growl.isAnimating=false end } ) if #self.set>1 then for i=2,#self.set do self.set[i].ny = self.set[i-1].ny+self.set[i-1].height+5 self.set[i].tween = transition.to( self.set[i], {tag=Growl.__n, y=self.set[i].ny, time=150, easing=easing.inExpo } ) end end end --Public methods function Growl:removeAllNotifications() for i=#self.set,1 do self.set[i]:removeSelf() end self.isAnimating=false end function Growl.new( _msg, _type, _width, _fontSize ) local w,h = _width or Growl.NOTIFICATION_WIDTH local fontSize = _fontSize or Growl.FONT_SIZE local m = display.newGroup( ) local function init( ) m.txt = display.newText( {parent=m, text=_msg, x=0,y=0,width=w-10, fontSize=fontSize, align='left'}) h = m.txt.height+10 m.bg = display.newRoundedRect(m, 0, 0, w, h, 4 ) if _type == 'error' then m.bg:setFillColor( 244/255, 122/255, 102/255, .9 ) elseif _type == 'info' then m.bg:setFillColor( 111/255, 169/255, 228/255, .9 ) else m.bg:setFillColor( 67/255, 172/255, 102/255, .9 ) end m.bg.strokeWidth=1 m.bg:setStrokeColor( 1,1,1,.2 ) m.txt:toFront( ) --config m.alpha=.8 m.anchorChildren=true m.anchorX, m.anchorY = 1,0 m.x, m.y = display.contentWidth+10+w, 10 m.nx, m.ny= display.contentWidth-10, m.y table.insert( Growl.set, 1, m ) end local function initRemove( ) function m:timer ( ) self:removeSelf() end m.removeTimer = timer.performWithDelay( Growl.SHOW_TIME, m) end m._removeSelf = m.removeSelf function m:removeSelf( ) if self.removeTimer then timer.cancel( self.removeTimer ) end self.removeTimer=nil if self.tween then transition.cancel( self.tween ) end self.tween=nil Growl:_removeNotification(self) self:_removeSelf() end init() initRemove() Growl:_moveNotifications() return m end return Growl
mit
dios-game/dios-cocos-samples
src/lua-coin-tree/Resources/src/cocos/framework/device.lua
57
3841
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local device = {} device.platform = "unknown" device.model = "unknown" local app = cc.Application:getInstance() local target = app:getTargetPlatform() if target == cc.PLATFORM_OS_WINDOWS then device.platform = "windows" elseif target == cc.PLATFORM_OS_MAC then device.platform = "mac" elseif target == cc.PLATFORM_OS_ANDROID then device.platform = "android" elseif target == cc.PLATFORM_OS_IPHONE or target == cc.PLATFORM_OS_IPAD then device.platform = "ios" local director = cc.Director:getInstance() local view = director:getOpenGLView() local framesize = view:getFrameSize() local w, h = framesize.width, framesize.height if w == 640 and h == 960 then device.model = "iphone 4" elseif w == 640 and h == 1136 then device.model = "iphone 5" elseif w == 750 and h == 1334 then device.model = "iphone 6" elseif w == 1242 and h == 2208 then device.model = "iphone 6 plus" elseif w == 768 and h == 1024 then device.model = "ipad" elseif w == 1536 and h == 2048 then device.model = "ipad retina" end elseif target == cc.PLATFORM_OS_WINRT then device.platform = "winrt" elseif target == cc.PLATFORM_OS_WP8 then device.platform = "wp8" end local language_ = app:getCurrentLanguage() if language_ == cc.LANGUAGE_CHINESE then language_ = "cn" elseif language_ == cc.LANGUAGE_FRENCH then language_ = "fr" elseif language_ == cc.LANGUAGE_ITALIAN then language_ = "it" elseif language_ == cc.LANGUAGE_GERMAN then language_ = "gr" elseif language_ == cc.LANGUAGE_SPANISH then language_ = "sp" elseif language_ == cc.LANGUAGE_RUSSIAN then language_ = "ru" elseif language_ == cc.LANGUAGE_KOREAN then language_ = "kr" elseif language_ == cc.LANGUAGE_JAPANESE then language_ = "jp" elseif language_ == cc.LANGUAGE_HUNGARIAN then language_ = "hu" elseif language_ == cc.LANGUAGE_PORTUGUESE then language_ = "pt" elseif language_ == cc.LANGUAGE_ARABIC then language_ = "ar" else language_ = "en" end device.language = language_ device.writablePath = cc.FileUtils:getInstance():getWritablePath() device.directorySeparator = "/" device.pathSeparator = ":" if device.platform == "windows" then device.directorySeparator = "\\" device.pathSeparator = ";" end printInfo("# device.platform = " .. device.platform) printInfo("# device.model = " .. device.model) printInfo("# device.language = " .. device.language) printInfo("# device.writablePath = " .. device.writablePath) printInfo("# device.directorySeparator = " .. device.directorySeparator) printInfo("# device.pathSeparator = " .. device.pathSeparator) printInfo("#") return device
mit
Kthulupwns/darkstar
scripts/zones/Phomiuna_Aqueducts/npcs/_0rt.lua
17
1603
----------------------------------- -- Area: Phomiuna_Aqueducts -- NPC: Oil lamp -- @pos -60 -23 60 27 ----------------------------------- package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Phomiuna_Aqueducts/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorOffset = npc:getID(); player:messageSpecial(LAMP_OFFSET+3); -- wind lamp npc:openDoor(7); -- lamp animation local element = VanadielDayElement(); --printf("element: %u",element); if(element == 3)then -- winday if(GetNPCByID(DoorOffset-1):getAnimation() == 8)then -- lamp earth open? GetNPCByID(DoorOffset-8):openDoor(15); -- Open Door _0rk end elseif(element == 4)then -- iceday if(GetNPCByID(DoorOffset-5):getAnimation() == 8)then -- lamp ice open? GetNPCByID(DoorOffset-8):openDoor(15); -- Open Door _0rk 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); end;
gpl-3.0
shayanchabok555/tigerantispam007
plugins/vote.lua
615
2128
do local _file_votes = './data/votes.lua' function read_file_votes () local f = io.open(_file_votes, "r+") if f == nil then print ('Created voting file '.._file_votes) serialize_to_file({}, _file_votes) else print ('Values loaded: '.._file_votes) f:close() end return loadfile (_file_votes)() end function clear_votes (chat) local _votes = read_file_votes () _votes [chat] = {} serialize_to_file(_votes, _file_votes) end function votes_result (chat) local _votes = read_file_votes () local results = {} local result_string = "" if _votes [chat] == nil then _votes[chat] = {} end for user,vote in pairs (_votes[chat]) do if (results [vote] == nil) then results [vote] = user else results [vote] = results [vote] .. ", " .. user end end for vote,users in pairs (results) do result_string = result_string .. vote .. " : " .. users .. "\n" end return result_string end function save_vote(chat, user, vote) local _votes = read_file_votes () if _votes[chat] == nil then _votes[chat] = {} end _votes[chat][user] = vote serialize_to_file(_votes, _file_votes) end function run(msg, matches) if (matches[1] == "ing") then if (matches [2] == "reset") then clear_votes (tostring(msg.to.id)) return "Voting statistics reset.." elseif (matches [2] == "stats") then local votes_result = votes_result (tostring(msg.to.id)) if (votes_result == "") then votes_result = "[No votes registered]\n" end return "Voting statistics :\n" .. votes_result end else save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2]))) return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2])) end end return { description = "Plugin for voting in groups.", usage = { "!voting reset: Reset all the votes.", "!vote [number]: Cast the vote.", "!voting stats: Shows the statistics of voting." }, patterns = { "^!vot(ing) (reset)", "^!vot(ing) (stats)", "^!vot(e) ([0-9]+)$" }, run = run } end
gpl-2.0
Kthulupwns/darkstar
scripts/zones/Leujaoam_Sanctum/Zone.lua
8
1492
----------------------------------- -- -- Zone: Leujaoam_Sanctum -- ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Leujaoam_Sanctum/IDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; local pos = player:getPos(); if (pos.x == 0 and pos.y == 0 and pos.z == 0) then player:setPos(player:getInstance():getEntryPos()); end player:addTempItem(5343); 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); if (csid == 0x66) then player:setPos(0,0,0,0,79); end end; ----------------------------------- -- onInstanceFailure ----------------------------------- function onInstanceLoadFailed() return 79; end;
gpl-3.0
AGTMADCAT/naev
dat/missions/common.lua
13
4395
--[[ Common Lua Mission framework --]] -- The common function table. common = {} --[[ COMBAT TIER STUFF --]] --[[ @brief Calculates the mission combat tier. Calculations are done with ally and enemy values at the instance where they are highest. To calculate the enemy/ally ratings you use the following table: - Lone Fighter/Bomber: +1 - Fighter/Bomber Squadron: +3 - Corvette: +4 - Destroyer: +6 - Cruiser: +10 - Carrier: +12 - Small Fleet: +10 (equivalent to small fleet in fleet.xml) - Medium Fleet: +20 (equivalent to medium fleet in fleet.xml) - Large Fleet: +30 (equivalent to heavy fleet in fleet.xml) @param enemy_value Peak enemy value. @param ally_value Ally value for peak enemy value. @param must_destroy Whether or not player must destroy the enemies (default: false) @param bkg_combat Whether or not combat is in the background without player as target (default: false) @luareturn The combat tier level (also stores it internally). --]] common.calcMisnCombatTier = function( enemy_value, ally_value, must_destroy, bkg_combat ) -- Set defaults must_destroy = must_destroy or true bkg_combat = bkg_combat or false -- Calculate modifiers local mod = 0 if not must_destroy then mod = mod * 0.5 end if bkg_combat then mod = mod * 0.75 end -- Calculate rating value local rating = mod * (enemy_value - ally_value/3) -- Get Tier from rating local tier if rating <= 0 then tier = 0 elseif rating <= 2 then tier = 1 elseif rating <= 4 then tier = 2 elseif rating <= 8 then tier = 3 elseif rating <= 12 then tier = 4 elseif rating <= 17 then tier = 5 elseif rating <= 22 then tier = 6 else tier = 7 end -- Set tier common.setCombatTier( tier ) -- Return tier return tier end --[[ @brief Calculates the player combat tier @return The player's equivalent combat tier. --]] common.calcPlayerCombatTier = function () local crating = player.getRating() local tier -- Calculate based off of combat rating if crating <= 5 then tier = 0 elseif crating <= 10 then tier = 1 elseif crating <= 20 then tier = 2 elseif crating <= 40 then tier = 3 elseif crating <= 80 then tier = 4 elseif crating <= 160 then tier = 5 elseif creating <= 320 then tier = 6 else tier = 7 end return tier end --[[ @brief Sets the combat tier @param tier Tier to set mission combat tier to. --]] common.setTierCombat = function( tier ) common["__tierCombat"] = tier end --[[ @brief Gets the combat tier @return The combat tier of the mission. --]] common.getTierCombat = function () return common["__tierCombat"] end --[[ @brief Checks to see if the player meets a minum tier @param tier Tier to check for (if nil tries to use the mission tier) --]] common.checkTierCombat = function( tier ) tier = tier or common.getTierCombat() -- No tier set so it always matches if tier == nil then return true end -- Check against mission tier return common.calcPlayerCombatTier() >= tier end --[[ REWARD STUFF --]] function _calcTierReward( tier ) local low, high if tier <= 0 then low = 0 high = 0 elseif tier == 1 then low = 0 high = 50 elseif tier == 2 then low = 50 high = 100 elseif tier == 3 then low = 100 high = 150 elseif tier == 4 then low = 150 high = 200 elseif tier == 5 then low = 200 high = 250 elseif tier == 6 then low = 250 high = 275 else low = 275 high = 300 end return low, high end --[[ @brief Calculates the monetary reward based on the tiers of the mission @usage low, high = common.calcMonetaryReward() @return The amount of money the player should be paid as an interval. --]] common.calcMonetaryReward = function () local low = 0 local high = 0 local l,h local tiers = {} -- Get tiers tiers[ #tiers+1 ] = common.getTierCombat() -- Calculate money for k,v in ipairs(tiers) do l, h = _calcTierReward( v ) low = low + l high = high + h end -- Return total amount return low, high end
gpl-3.0
dpino/snabb
lib/ljsyscall/syscall/netbsd/c.lua
24
2452
-- This sets up the table of C functions for BSD -- We need to override functions that are versioned as the old ones selected otherwise local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" local version = require "syscall.netbsd.version".version local ffi = require "ffi" local function inlibc_fn(k) return ffi.C[k] end -- Syscalls that just return ENOSYS but are in libc. local nosys_calls if version == 6 then nosys_calls = { openat = true, faccessat = true, symlinkat = true, mkdirat = true, unlinkat = true, renameat = true, fstatat = true, fchmodat = true, fchownat = true, mkfifoat = true, mknodat = true, } end local C = setmetatable({}, { __index = function(C, k) if nosys_calls and nosys_calls[k] then return nil end if pcall(inlibc_fn, k) then C[k] = ffi.C[k] -- add to table, so no need for this slow path again return C[k] else return nil end end }) -- for NetBSD we use libc names not syscalls, as assume you will have libc linked or statically linked with all symbols exported. -- this is so we can use NetBSD libc even where syscalls have been redirected to rump calls. -- use new versions C.mount = C.__mount50 C.stat = C.__stat50 C.fstat = C.__fstat50 C.lstat = C.__lstat50 C.getdents = C.__getdents30 C.socket = C.__socket30 C.select = C.__select50 C.pselect = C.__pselect50 C.fhopen = C.__fhopen40 C.fhstat = C.__fhstat50 C.fhstatvfs1 = C.__fhstatvfs140 C.utimes = C.__utimes50 C.posix_fadvise = C.__posix_fadvise50 C.lutimes = C.__lutimes50 C.futimes = C.__futimes50 C.getfh = C.__getfh30 C.kevent = C.__kevent50 C.mknod = C.__mknod50 C.pollts = C.__pollts50 C.gettimeofday = C.__gettimeofday50 C.settimeofday = C.__settimeofday50 C.adjtime = C.__adjtime50 C.setitimer = C.__setitimer50 C.getitimer = C.__getitimer50 C.clock_gettime = C.__clock_gettime50 C.clock_settime = C.__clock_settime50 C.clock_getres = C.__clock_getres50 C.nanosleep = C.__nanosleep50 C.timer_settime = C.__timer_settime50 C.timer_gettime = C.__timer_gettime50 -- use underlying syscall not wrapper C.getcwd = C.__getcwd C.sigaction = C.__libc_sigaction14 -- TODO not working I think need to use tramp_sigaction, see also netbsd pause() return C
apache-2.0
Kthulupwns/darkstar
scripts/zones/Grand_Palace_of_HuXzoi/npcs/_iyb.lua
19
1231
----------------------------------- -- Area: Grand Palace of Hu'Xzoi -- NPC: Particle Gate -- @pos 1 0.1 -320 34 ----------------------------------- package.loaded["scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(COP) == A_FATE_DECIDED and player:getVar("PromathiaStatus")==0)then player:startEvent(0x0002); else player:startEvent(0x0038); 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(csid == 0x0002)then player:setVar("PromathiaStatus",1); end end;
gpl-3.0
FPtje/DarkRP
gamemode/modules/fadmin/fadmin/access/sv_init.lua
1
20448
--Immunity cvars.AddChangeCallback("_FAdmin_immunity", function(Cvar, Previous, New) FAdmin.SetGlobalSetting("Immunity", (tonumber(New) == 1 and true) or false) FAdmin.SaveSetting("_FAdmin_immunity", tonumber(New)) end) hook.Add("DatabaseInitialized", "InitializeFAdminGroups", function() MySQLite.query("CREATE TABLE IF NOT EXISTS FADMIN_GROUPS(NAME VARCHAR(40) NOT NULL PRIMARY KEY, ADMIN_ACCESS INTEGER NOT NULL);") MySQLite.query("CREATE TABLE IF NOT EXISTS FAdmin_PlayerGroup(steamid VARCHAR(40) NOT NULL, groupname VARCHAR(40) NOT NULL, PRIMARY KEY(steamid));") MySQLite.query("CREATE TABLE IF NOT EXISTS FAdmin_Immunity(groupname VARCHAR(40) NOT NULL, immunity INTEGER NOT NULL, PRIMARY KEY(groupname));") MySQLite.query("CREATE TABLE IF NOT EXISTS FAdmin_CAMIPrivileges(privname VARCHAR(255) NOT NULL PRIMARY KEY);") MySQLite.query("CREATE TABLE IF NOT EXISTS FADMIN_GROUPS_SRC(NAME VARCHAR(40) NOT NULL PRIMARY KEY REFERENCES FADMIN_GROUPS(NAME) ON DELETE CASCADE, SRC VARCHAR(40));") MySQLite.query([[CREATE TABLE IF NOT EXISTS FADMIN_PRIVILEGES( NAME VARCHAR(40), PRIVILEGE VARCHAR(100), PRIMARY KEY(NAME, PRIVILEGE), FOREIGN KEY(NAME) REFERENCES FADMIN_GROUPS(NAME) ON UPDATE CASCADE ON DELETE CASCADE );]], function() -- Remove SetAccess workaround MySQLite.query([[DELETE FROM FADMIN_PRIVILEGES WHERE NAME = "user" AND PRIVILEGE = "SetAccess";]]) MySQLite.query("SELECT g.NAME, g.ADMIN_ACCESS, p.PRIVILEGE, i.immunity, s.src FROM FADMIN_GROUPS g LEFT OUTER JOIN FADMIN_PRIVILEGES p ON g.NAME = p.NAME LEFT OUTER JOIN FAdmin_Immunity i ON g.NAME = i.groupname LEFT OUTER JOIN FADMIN_GROUPS_SRC s ON g.NAME = s.NAME;", function(data) if not data then return end for _, v in pairs(data) do FAdmin.Access.Groups[v.NAME] = FAdmin.Access.Groups[v.NAME] or {ADMIN = tonumber(v.ADMIN_ACCESS), PRIVS = {}} if v.PRIVILEGE and v.PRIVILEGE ~= "NULL" then FAdmin.Access.Groups[v.NAME].PRIVS[v.PRIVILEGE] = true end if v.immunity and v.immunity ~= "NULL" then FAdmin.Access.Groups[v.NAME].immunity = tonumber(v.immunity) end if CAMI.GetUsergroup(v.NAME) then continue end CAMI.RegisterUsergroup({ Name = v.NAME, Inherits = FAdmin.Access.ADMIN[v.ADMIN_ACCESS] or "user" }, v.SRC) end -- Send groups to early joiners and listen server hosts for _, v in ipairs(player.GetAll()) do FAdmin.Access.SendGroups(v) end -- See if there are any CAMI usergroups that FAdmin doesn't know about yet. -- FAdmin doesn't start listening immediately because the database might not have initialised. -- Besides, other admin mods might add usergroups before FAdmin's Lua files are even run for _, v in pairs(CAMI.GetUsergroups()) do if FAdmin.Access.Groups[v.Name] then continue end FAdmin.Access.OnUsergroupRegistered(v,"") end -- Start listening for CAMI usergroup registrations. hook.Add("CAMI.OnUsergroupRegistered", "FAdmin", FAdmin.Access.OnUsergroupRegistered) hook.Add("CAMI.OnUsergroupUnregistered", "FAdmin", FAdmin.Access.OnUsergroupUnregistered) FAdmin.Access.RegisterCAMIPrivileges() end) local function createGroups(privs) FAdmin.Access.AddGroup("superadmin", 2, privs.superadmin, 100) FAdmin.Access.AddGroup("admin", 1, privs.admin, 50) FAdmin.Access.AddGroup("user", 0, privs.user, 10) FAdmin.Access.AddGroup("noaccess", 0, privs.noaccess, 0) end MySQLite.query("SELECT DISTINCT PRIVILEGE FROM FADMIN_PRIVILEGES;", function(privTbl) local privs = {} local hasPrivs = {"noaccess", "user", "admin", "superadmin"} -- No privileges registered to anyone. Reset everything if not privTbl or table.IsEmpty(privTbl) then for priv, access in pairs(FAdmin.Access.Privileges) do for i = access + 1, #hasPrivs, 1 do privs[hasPrivs[i]] = privs[hasPrivs[i]] or {} privs[hasPrivs[i]][priv] = true end end createGroups(privs) return end -- Check for newly created privileges and assign them to the default usergroups -- No privilege can be revoke from every group local privSet = {} for _, priv in ipairs(privTbl) do privSet[priv.PRIVILEGE] = true end for priv, access in pairs(FAdmin.Access.Privileges) do if privSet[priv] then continue end for i = access + 1, #hasPrivs do MySQLite.query(("REPLACE INTO FADMIN_PRIVILEGES VALUES(%s, %s);"):format(MySQLite.SQLStr(hasPrivs[i]), MySQLite.SQLStr(priv))) end end createGroups(privs) end) end) end) -- Assign a privilege to its respective usergroups when they are seen for the first time function FAdmin.Access.RegisterCAMIPrivilege(priv) -- Privileges haven't been loaded yet or has already been seen if not FAdmin.CAMIPrivs or FAdmin.CAMIPrivs[priv.Name] then return end FAdmin.CAMIPrivs[priv.Name] = true for groupName, groupdata in pairs(FAdmin.Access.Groups) do if FAdmin.Access.Privileges[priv.Name] - 1 > groupdata.ADMIN then continue end groupdata.PRIVS[priv.Name] = true MySQLite.query(string.format([[REPLACE INTO FADMIN_PRIVILEGES VALUES(%s, %s);]], MySQLite.SQLStr(groupName), MySQLite.SQLStr(priv.Name))) end MySQLite.query(string.format([[REPLACE INTO FAdmin_CAMIPrivileges VALUES(%s);]], MySQLite.SQLStr(priv.Name))) end -- Assign privileges to their respective usergroups when they are seen for the first time function FAdmin.Access.RegisterCAMIPrivileges() MySQLite.query([[SELECT privname FROM FAdmin_CAMIPrivileges]], function(data) FAdmin.CAMIPrivs = {} for _, row in ipairs(data or {}) do FAdmin.CAMIPrivs[row.privname] = true end for privName, _ in pairs(CAMI.GetPrivileges()) do if FAdmin.CAMIPrivs[privName] then continue end FAdmin.CAMIPrivs[privName] = true for groupName, groupdata in pairs(FAdmin.Access.Groups) do if FAdmin.Access.Privileges[privName] - 1 > groupdata.ADMIN then continue end groupdata.PRIVS[privName] = true MySQLite.query(string.format([[REPLACE INTO FADMIN_PRIVILEGES VALUES(%s, %s);]], MySQLite.SQLStr(groupName), MySQLite.SQLStr(privName))) end MySQLite.query(string.format([[REPLACE INTO FAdmin_CAMIPrivileges VALUES(%s);]], MySQLite.SQLStr(privName))) end end) end function FAdmin.Access.PlayerSetGroup(ply, group) if not FAdmin.Access.Groups[group] then return end ply = isstring(ply) and FAdmin.FindPlayer(ply) and FAdmin.FindPlayer(ply)[1] or ply if not isstring(ply) and IsValid(ply) then ply:SetUserGroup(group) end end hook.Remove("PlayerInitialSpawn", "PlayerAuthSpawn") -- Remove Garry's usergroup setter. -- Update the database only when an end users indicates that a player's usergroup is to be changed. hook.Add("CAMI.PlayerUsergroupChanged", "FAdmin", function(ply, old, new, source) MySQLite.query("REPLACE INTO FAdmin_PlayerGroup VALUES(" .. MySQLite.SQLStr(ply:SteamID()) .. ", " .. MySQLite.SQLStr(new) .. ");") end) hook.Add("CAMI.SteamIDUsergroupChanged", "FAdmin", function(steamId, old, new, source) MySQLite.query("REPLACE INTO FAdmin_PlayerGroup VALUES(" .. MySQLite.SQLStr(steamId) .. ", " .. MySQLite.SQLStr(new) .. ");") end) function FAdmin.Access.SetRoot(ply, cmd, args) -- FAdmin setroot player. Sets the player to superadmin if not FAdmin.Access.PlayerHasPrivilege(ply, "SetAccess") then FAdmin.Messages.SendMessage(ply, 5, "No access!") FAdmin.Messages.SendMessage(ply, 5, "Please use RCon to set yourself to superadmin if you are the owner of the server") return false end local group = FAdmin.Access.Groups["superadmin"] local plyGroup = FAdmin.Access.Groups[ply:EntIndex() == 0 and "superadmin" or ply:GetUserGroup()] -- Setting a group with a higher rank than one's own if (not plyGroup or group.immunity > plyGroup.immunity) and not FAdmin.Access.PlayerIsHost(ply) then FAdmin.Messages.SendMessage(ply, 5, "You're not allowed to assign anyone a usergroup with a higher rank than your own") FAdmin.Messages.SendMessage(ply, 5, "Please use RCon to set yourself to superadmin if you are the owner of the server") return false end local targets = FAdmin.FindPlayer(args[1]) if not targets or #targets == 1 and not IsValid(targets[1]) then FAdmin.Messages.SendMessage(ply, 1, "Player not found") return false end for _, target in pairs(targets) do if not IsValid(target) then continue end local target_previous_group = target:GetUserGroup() FAdmin.Access.PlayerSetGroup(target, "superadmin") -- An end user changed the usergroup. Register with CAMI CAMI.SignalUserGroupChanged(target, target_previous_group, "superadmin", "FAdmin") FAdmin.Messages.SendMessage(ply, 2, "User set to superadmin!") end FAdmin.Messages.FireNotification("setaccess", ply, targets, {"superadmin"}) return true, targets, "superadmin" end -- AddGroup <Groupname> <Adminstatus> <Privileges> local function AddGroup(ply, cmd, args) if not FAdmin.Access.PlayerHasPrivilege(ply, "ManageGroups") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end local admin = tonumber(args[2]) if not args[1] or not admin then FAdmin.Messages.SendMessage(ply, 5, "Incorrect arguments!") return false end local privs = {} for priv, am in SortedPairs(FAdmin.Access.Privileges) do -- The user cannot create groups with privileges they don't have if not FAdmin.Access.PlayerHasPrivilege(ply, priv) then continue end if am <= admin + 1 then privs[priv] = true end end local immunity = FAdmin.Access.Groups[FAdmin.Access.ADMIN[admin + 1]].immunity local plyGroup = FAdmin.Access.Groups[ply:EntIndex() == 0 and "superadmin" or ply:GetUserGroup()] if (not plyGroup or immunity > plyGroup.immunity) and not FAdmin.Access.PlayerIsHost(ply) then FAdmin.Messages.SendMessage(ply, 5, "You're not allowed to create usergroups with a higher rank than your own") return false end FAdmin.Access.AddGroup(args[1], admin, privs, immunity) -- Add new group FAdmin.Messages.SendMessage(ply, 4, "Group created") FAdmin.Access.SendGroups() return true, args[1] end local function AddPrivilege(ply, cmd, args) if not FAdmin.Access.PlayerHasPrivilege(ply, "ManagePrivileges") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end local group, priv = args[1], args[2] if not FAdmin.Access.Groups[group] or not FAdmin.Access.Privileges[priv] then FAdmin.Messages.SendMessage(ply, 5, "Invalid arguments") return false end -- The player cannot add privileges that they themselves do not have if not FAdmin.Access.PlayerHasPrivilege(ply, priv) then FAdmin.Messages.SendMessage(ply, 5, "You're not allowed to assign privileges that you don't have yourself") return false end local plyGroup = FAdmin.Access.Groups[ply:EntIndex() == 0 and "superadmin" or ply:GetUserGroup()] -- Setting a group with a higher rank than one's own if (not plyGroup or FAdmin.Access.Groups[group].immunity > plyGroup.immunity) and not FAdmin.Access.PlayerIsHost(ply) then FAdmin.Messages.SendMessage(ply, 5, "You're not allowed to manage the privileges of a usergroup with a higher rank than your own") return false end FAdmin.Access.Groups[group].PRIVS[priv] = true MySQLite.query("REPLACE INTO FADMIN_PRIVILEGES VALUES(" .. MySQLite.SQLStr(group) .. ", " .. MySQLite.SQLStr(priv) .. ");") SendUserMessage("FAdmin_AddPriv", player.GetAll(), group, priv) FAdmin.Messages.SendMessage(ply, 4, "Privilege Added!") return true, group, priv end local function RemovePrivilege(ply, cmd, args) if not FAdmin.Access.PlayerHasPrivilege(ply, "ManagePrivileges") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end local group, priv = args[1], args[2] if not FAdmin.Access.Groups[group] or not FAdmin.Access.Privileges[priv] then FAdmin.Messages.SendMessage(ply, 5, "Invalid arguments") return false end local plyGroup = FAdmin.Access.Groups[ply:EntIndex() == 0 and "superadmin" or ply:GetUserGroup()] -- Setting a group with a higher rank than one's own if (not plyGroup or FAdmin.Access.Groups[group].immunity > plyGroup.immunity) and not FAdmin.Access.PlayerIsHost(ply) then FAdmin.Messages.SendMessage(ply, 5, "You're not allowed to manage the privileges of a usergroup with a higher rank than your own") return false end FAdmin.Access.Groups[group].PRIVS[priv] = nil MySQLite.query("DELETE FROM FADMIN_PRIVILEGES WHERE NAME = " .. MySQLite.SQLStr(group) .. " AND PRIVILEGE = " .. MySQLite.SQLStr(priv) .. ";") SendUserMessage("FAdmin_RemovePriv", player.GetAll(), group, priv) FAdmin.Messages.SendMessage(ply, 4, "Privilege Removed!") return true, group, priv end function FAdmin.Access.SendGroups(ply) if not FAdmin.Access.Groups then return end net.Start("FADMIN_SendGroups") net.WriteTable(FAdmin.Access.Groups) net.Send(IsValid(ply) and ply or player.GetAll()) end -- FAdmin SetAccess <player> <groupname> [new_groupadmin, new_groupprivs] function FAdmin.Access.SetAccess(ply, cmd, args) if not FAdmin.Access.PlayerHasPrivilege(ply, "SetAccess") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end local targets = FAdmin.FindPlayer(args[1]) local admin = tonumber(args[3]) local group = FAdmin.Access.Groups[args[2]] local plyGroup = FAdmin.Access.Groups[ply:EntIndex() == 0 and "superadmin" or ply:GetUserGroup()] if not args[2] or not group and not admin then FAdmin.Messages.SendMessage(ply, 1, "Group not found") return false elseif args[2] and not group and admin then local privs = {} for priv, am in SortedPairs(FAdmin.Access.Privileges) do if am <= admin + 1 then privs[priv] = true end end local immunity = FAdmin.Access.Groups[FAdmin.Access.ADMIN[admin + 1]].immunity -- Creating and setting a group with a higher rank than one's own if (not plyGroup or immunity > plyGroup.immunity) and not FAdmin.Access.PlayerIsHost(ply) then FAdmin.Messages.SendMessage(ply, 5, "You're not allowed to assign anyone a usergroup with a higher rank than your own") return false end FAdmin.Access.AddGroup(args[2], tonumber(args[3]), privs, immunity) -- Add new group FAdmin.Messages.SendMessage(ply, 4, "Group created") FAdmin.Access.SendGroups() end -- Setting a group with a higher rank than one's own if group and (not plyGroup or group.immunity > plyGroup.immunity) and not FAdmin.Access.PlayerIsHost(ply) then FAdmin.Messages.SendMessage(ply, 5, "You're not allowed to assign anyone a usergroup with a higher rank than your own") return false end if not targets and (string.find(args[1], "^STEAM_[0-9]:[01]:[0-9]+$") or args[1] == "BOT" or (string.find(args[1], "STEAM_") and #args == 6)) then local target, groupname = args[1], args[2] -- The console splits arguments on colons. Very annoying. if args[1] == "STEAM_0" then target = table.concat(args, "", 1, 5) groupname = args[6] end FAdmin.Access.PlayerSetGroup(target, groupname) MySQLite.queryValue(string.format("SELECT groupname FROM FAdmin_PlayerGroup WHERE steamid = %s", MySQLite.SQLStr(target)), function(val) CAMI.SignalSteamIDUserGroupChanged(target, val or "user", groupname, "FAdmin") end) FAdmin.Messages.SendMessage(ply, 4, "User access set!") return true, target, groupname elseif not targets then FAdmin.Messages.SendMessage(ply, 1, "Player not found") return false end for _, target in pairs(targets) do if not IsValid(target) then continue end local target_previous_group = target:GetUserGroup() FAdmin.Access.PlayerSetGroup(target, args[2]) -- An end user changed the usergroup. Register with CAMI CAMI.SignalUserGroupChanged(target, target_previous_group, args[2], "FAdmin") end FAdmin.Messages.SendMessage(ply, 4, "User access set!") FAdmin.Messages.FireNotification("setaccess", ply, targets, {args[2]}) return true, targets, args[2] end --hooks and stuff hook.Add("PlayerInitialSpawn", "FAdmin_SetAccess", function(ply) MySQLite.queryValue("SELECT groupname FROM FAdmin_PlayerGroup WHERE steamid = " .. MySQLite.SQLStr(ply:SteamID()) .. ";", function(Group) if not Group then return end ply:SetUserGroup(Group) if FAdmin.Access.Groups[Group] then ply:FAdmin_SetGlobal("FAdmin_admin", FAdmin.Access.Groups[Group].ADMIN_ACCESS) end end, function(err) ErrorNoHalt(err) MsgN() end) FAdmin.Access.SendGroups(ply) end) local function toggleImmunity(ply, cmd, args) -- ManageGroups privilege because they can handle immunity settings if not FAdmin.Access.PlayerHasPrivilege(ply, "ManageGroups") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end if not args[1] then FAdmin.Messages.SendMessage(ply, 5, "Invalid argument!") return false end RunConsoleCommand("_FAdmin_immunity", args[1]) local OnOff = (tonumber(args[1]) == 1 and "on") or "off" FAdmin.Messages.ActionMessage(ply, player.GetAll(), ply:Nick() .. " turned " .. OnOff .. " admin immunity!", "Admin immunity has been turned " .. OnOff, "Turned admin immunity " .. OnOff) return true, OnOff end local function setImmunity(ply, cmd, args) if not FAdmin.Access.PlayerHasPrivilege(ply, "ManageGroups") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end local group, immunity = args[1], tonumber(args[2]) if not FAdmin.Access.Groups[group] or not immunity then return false end local plyGroup = FAdmin.Access.Groups[ply:EntIndex() == 0 and "superadmin" or ply:GetUserGroup()] -- Setting a group with a higher rank than one's own if (not plyGroup or FAdmin.Access.Groups[group].immunity > plyGroup.immunity) and not FAdmin.Access.PlayerIsHost(ply) then FAdmin.Messages.SendMessage(ply, 5, "You're not allowed to change the immunity of a group with a higher rank than your") return false end if immunity > plyGroup.immunity and not FAdmin.Access.PlayerIsHost(ply) then FAdmin.Messages.SendMessage(ply, 5, "You're not allowed to set the immunity to any value higher than your own group's immunity") return false end FAdmin.Access.Groups[group].immunity = immunity MySQLite.query("REPLACE INTO FAdmin_Immunity VALUES(" .. MySQLite.SQLStr(group) .. ", " .. tonumber(immunity) .. ");") FAdmin.Access.SendGroups(ply) return true, group, immunity end FAdmin.StartHooks["Access"] = function() --Run all functions that depend on other plugins FAdmin.Commands.AddCommand("setroot", FAdmin.Access.SetRoot) FAdmin.Commands.AddCommand("setaccess", FAdmin.Access.SetAccess) FAdmin.Commands.AddCommand("AddGroup", AddGroup) FAdmin.Commands.AddCommand("AddPrivilege", AddPrivilege) FAdmin.Commands.AddCommand("RemovePrivilege", RemovePrivilege) FAdmin.Commands.AddCommand("immunity", toggleImmunity) FAdmin.Commands.AddCommand("SetImmunity", setImmunity) FAdmin.SetGlobalSetting("Immunity", GetConVar("_FAdmin_immunity"):GetBool()) end
mit
AttacqueSuperior/Engine
mods/d2k/maps/harkonnen-09a/harkonnen09a-AI.lua
2
5792
--[[ Copyright 2007-2021 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] AttackGroupSize = { easy = 6, normal = 8, hard = 10 } AttackDelays = { easy = { DateTime.Seconds(4), DateTime.Seconds(7) }, normal = { DateTime.Seconds(2), DateTime.Seconds(5) }, hard = { DateTime.Seconds(1), DateTime.Seconds(3) } } EnemyInfantryTypes = { "light_inf", "light_inf", "light_inf", "trooper", "trooper" } EnemyVehicleTypes = { "trike", "trike", "quad" } AtreidesMainTankTypes = { "combat_tank_a", "combat_tank_a", "siege_tank", "missile_tank", "sonic_tank" } AtreidesSmallTankTypes = { "combat_tank_a", "combat_tank_a", "siege_tank" } AtreidesStarportTypes = { "trike.starport", "trike.starport", "quad.starport", "combat_tank_a.starport", "combat_tank_a.starport", "siege_tank.starport", "missile_tank.starport" } CorrinoMainInfantryTypes = { "light_inf", "light_inf", "trooper", "sardaukar" } CorrinoMainTankTypes = { "combat_tank_h", "combat_tank_h", "siege_tank", "missile_tank" } CorrinoSmallTankTypes = { "combat_tank_h", "combat_tank_h", "siege_tank" } CorrinoStarportTypes = { "trike.starport", "trike.starport", "quad.starport", "combat_tank_h.starport", "combat_tank_h.starport", "siege_tank.starport", "missile_tank.starport" } ActivateAI = function() IdlingUnits[atreides_main] = Reinforcements.Reinforce(atreides_main, InitialAtreidesReinforcements[1], InitialAtreidesPaths[1]), Reinforcements.Reinforce(atreides_main, InitialAtreidesReinforcements[2], InitialAtreidesPaths[2]), Reinforcements.Reinforce(atreides_main, InitialAtreidesReinforcements[3], InitialAtreidesPaths[3]) IdlingUnits[atreides_small_1] = Reinforcements.Reinforce(atreides_small_1, InitialAtreidesReinforcements[4], InitialAtreidesPaths[4]), Reinforcements.Reinforce(atreides_small_1, InitialAtreidesReinforcements[5], InitialAtreidesPaths[5]) IdlingUnits[atreides_small_2] = Reinforcements.Reinforce(atreides_small_2, InitialAtreidesReinforcements[6], InitialAtreidesPaths[6]) IdlingUnits[corrino_main] = Reinforcements.Reinforce(corrino_main, InitialCorrinoReinforcements, InitialCorrinoPaths[1]) IdlingUnits[corrino_small] = Reinforcements.Reinforce(corrino_main, InitialCorrinoReinforcements, InitialCorrinoPaths[2]) DefendAndRepairBase(atreides_main, AtreidesMainBase, 0.75, AttackGroupSize[Difficulty]) DefendAndRepairBase(atreides_small_1, AtreidesSmall1Base, 0.75, AttackGroupSize[Difficulty]) DefendAndRepairBase(atreides_small_2, AtreidesSmall2Base, 0.75, AttackGroupSize[Difficulty]) DefendAndRepairBase(corrino_main, CorrinoMainBase, 0.75, AttackGroupSize[Difficulty]) DefendAndRepairBase(corrino_small, CorrinoSmallBase, 0.75, AttackGroupSize[Difficulty]) local delay = function() return Utils.RandomInteger(AttackDelays[Difficulty][1], AttackDelays[Difficulty][2] + 1) end local infantryToBuild = function() return { Utils.Random(EnemyInfantryTypes) } end local infantryToBuildCorrinoMain = function() return { Utils.Random(CorrinoMainInfantryTypes) } end local vehilcesToBuild = function() return { Utils.Random(EnemyVehicleTypes) } end local tanksToBuildAtreidesMain = function() return { Utils.Random(AtreidesMainTankTypes) } end local tanksToBuildAtreidesSmall = function() return { Utils.Random(AtreidesSmallTankTypes) } end local tanksToBuildCorrinoMain = function() return { Utils.Random(CorrinoMainTankTypes) } end local tanksToBuildCorrinoSmall = function() return { Utils.Random(CorrinoSmallTankTypes) } end local unitsToBuyAtreides = function() return { Utils.Random(AtreidesStarportTypes) } end local unitsToBuyCorrino = function() return { Utils.Random(CorrinoStarportTypes) } end local attackThresholdSize = AttackGroupSize[Difficulty] * 2.5 ProduceUnits(atreides_main, ABarracks1, delay, infantryToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(atreides_main, ALightFactory1, delay, vehilcesToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(atreides_main, AHeavyFactory1, delay, tanksToBuildAtreidesMain, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(atreides_main, AStarport, delay, unitsToBuyAtreides, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(atreides_small_1, ABarracks3, delay, infantryToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(atreides_small_1, ALightFactory2, delay, vehilcesToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(atreides_small_1, AHeavyFactory2, delay, tanksToBuildAtreidesSmall, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(atreides_small_2, ABarracks4, delay, infantryToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(corrino_main, CBarracks1, delay, infantryToBuildCorrinoMain, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(corrino_main, CLightFactory1, delay, vehilcesToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(corrino_main, CHeavyFactory1, delay, tanksToBuildCorrinoMain, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(corrino_main, CStarport, delay, unitsToBuyCorrino, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(corrino_small, CBarracks2, delay, infantryToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(corrino_small, CLightFactory2, delay, vehilcesToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(corrino_small, CHeavyFactory2, delay, tanksToBuildCorrinoSmall, AttackGroupSize[Difficulty], attackThresholdSize) end
gpl-3.0
Kthulupwns/darkstar
scripts/globals/mobskills/Pelagic_Tempest.lua
6
1136
--------------------------------------------- -- Pelagic Tempest -- -- Description: Delivers an area attack that inflicts Shock and Terror. -- Type: Physical? -- Utsusemi/Blink absorb: Ignores shadows -- Range: 10' cone -- Notes: Used by Murex affiliated with lightning element. Shock effect is fairly strong (28/tick). --------------------------------------------- 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) local numhits = 1; local accmod = 2; 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_BLUNT,info.hitslanded); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_SHOCK, 28, 3, 180); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_TERROR, 1, 0, 180); target:delHP(dmg); return dmg; end;
gpl-3.0
GreenFaith/Topics
controller/reply.lua
1
3636
local json = require "cjson" local Reply = require "model.reply" local Topic = require "model.topic" local rid = tonumber(ngx.var.id) local respon = {} if ngx.var.request_method == "GET" then --read reply list if not rid then local tid = tonumber(ngx.var.arg_topic_id) print(tid) local r_list = Reply:read_list({topic_id=tid}) if r_list then respon.data = {items = r_list} respon.data.kind = "reply" ngx.say(json.encode(respon)) else respon.error = {code=404, message="Reply List Not Found"} ngx.say(json.encode(respon)) end return end local t = Reply:read(rid) if next(t) == nil then respon.error = { code = 404, message = "Not Found" } ngx.say(json.encode(respon)) return end respon.data = { kind = "reply", items = t } ngx.say(json.encode(respon)) return end if ngx.var.request_method == "DELETE" then local res = Reply:destroy(rid) local respon = {} if res then respon.data = {} respon.data.kind = "Reply" respon.data.message = "deleted" respon.data.id = rid end ngx.say(json.encode(respon)) return end if ngx.var.request_method == "POST" then local args = ngx.req.get_post_args() local r = Reply.new() local tid = tonumber(args.topic_id) local respon = {} local now = os.time() --form vaild if tid == nil or args.content == nil then respon.error = {} respon.error.code = 400 respon.error.message = "missing topic_id or content" ngx.say(json.encode(respon)) return end local t = Topic:read(tid) if t==nil or next(t)==nil then respon.error = {} respon.error.code = 404 respon.error.message = "topic not found by given topic id!" ngx.say(json.encode(respon)) return end --not safe [floor] --r.floor = t.reply_count.value + 1 r.topic_id:set(tid) r.content:set(args.content) r.created_at:set(now) r.updated_at:set(now) -- create reply local res = r:create() if not res then respon.error = {} respon.error.code = 500 respon.error.message = "create faild" ngx.say(json.encode(respon)) return end local rid = res.insert_id --update topic if Topic:exe("update Topic,Reply set ".. "Topic.reply_count=Topic.reply_count+1,".. "Topic.last_reply_date="..now.. ",Reply.floor=Topic.reply_count".. " where Topic.id="..tid.. " and Reply.id="..rid..";") then respon.data = {} respon.data.kind = "reply" respon.data.items = r:record() end respon.data = {kind="reply"} ngx.say(json.encode(respon)) return end if ngx.var.request_method == "PUT" then local args = ngx.req.get_post_args() local d = {} local respon = {} d.id = rid d.content = args.content --form check if not (d.id and d.content) then respon.error = {} respon.error.code = 400 respon.error.message = "no id give or nothing to update" ngx.say(json.encode(respon)) return end if Reply:update(d) then respon.data = {} respon.data.kind = "Reply" respon.data.id = d.id else respon.error = {} respon.error.code = 500 respon.error.message = "update faild" end ngx.say(json.encode(respon)) return end
mit
morteza1185/tele-red-bot
plugins/inrealm.lua
114
25001
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' 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 get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end 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 set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end 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 set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" 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 '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_name(msg, data, target) if not is_admin(msg) then return "For admins only!" 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 '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 --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" 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 return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_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' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(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, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) 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] 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 end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_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 if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
shkan/telebot
plugins/channels.lua
45
1681
-- Checks if bot was disabled on specific chat local function is_channel_disabled( receiver ) if not _config.disabled_channels then return false end if _config.disabled_channels[receiver] == nil then return false end return _config.disabled_channels[receiver] end local function enable_channel(receiver) if not _config.disabled_channels then _config.disabled_channels = {} end if _config.disabled_channels[receiver] == nil then return 'Channel isn\'t disabled' end _config.disabled_channels[receiver] = false save_config() return "Channel re-enabled" end local function disable_channel( receiver ) if not _config.disabled_channels then _config.disabled_channels = {} end _config.disabled_channels[receiver] = true save_config() return "Channel disabled" end local function pre_process(msg) local receiver = get_receiver(msg) -- If sender is sudo then re-enable the channel if is_sudo(msg) then if msg.text == "!channel enable" then enable_channel(receiver) end end if is_channel_disabled(receiver) then msg.text = "" end return msg end local function run(msg, matches) local receiver = get_receiver(msg) -- Enable a channel if matches[1] == 'enable' then return enable_channel(receiver) end -- Disable a channel if matches[1] == 'disable' then return disable_channel(receiver) end end return { description = "Plugin to manage channels. Enable or disable channel.", usage = { "!channel enable: enable current channel", "!channel disable: disable current channel" }, patterns = { "^!channel? (enable)", "^!channel? (disable)" }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
Kthulupwns/darkstar
scripts/globals/effects/light_arts.lua
37
1963
----------------------------------- -- -- -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:recalculateAbilitiesTable(); local bonus = effect:getPower(); local regen = effect:getSubPower(); target:addMod(MOD_WHITE_MAGIC_COST, -bonus); target:addMod(MOD_WHITE_MAGIC_CAST, -bonus); target:addMod(MOD_WHITE_MAGIC_RECAST, -bonus); if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then target:addMod(MOD_WHITE_MAGIC_COST, -10); target:addMod(MOD_WHITE_MAGIC_CAST, -10); target:addMod(MOD_WHITE_MAGIC_RECAST, -10); target:addMod(MOD_BLACK_MAGIC_COST, 20); target:addMod(MOD_BLACK_MAGIC_CAST, 20); target:addMod(MOD_BLACK_MAGIC_RECAST, 20); target:addMod(MOD_REGEN_EFFECT, regen); target:addMod(MOD_REGEN_DURATION, regen*2); end target:recalculateSkillsTable(); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:recalculateAbilitiesTable(); local bonus = effect:getPower(); local regen = effect:getSubPower(); target:delMod(MOD_WHITE_MAGIC_COST, -bonus); target:delMod(MOD_WHITE_MAGIC_CAST, -bonus); target:delMod(MOD_WHITE_MAGIC_RECAST, -bonus); if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then target:delMod(MOD_WHITE_MAGIC_COST, -10); target:delMod(MOD_WHITE_MAGIC_CAST, -10); target:delMod(MOD_WHITE_MAGIC_RECAST, -10); target:delMod(MOD_BLACK_MAGIC_COST, 20); target:delMod(MOD_BLACK_MAGIC_CAST, 20); target:delMod(MOD_BLACK_MAGIC_RECAST, 20); target:delMod(MOD_REGEN_EFFECT, regen); target:delMod(MOD_REGEN_DURATION, regen*2); end target:recalculateSkillsTable(); end;
gpl-3.0
Kthulupwns/darkstar
scripts/zones/Port_Bastok/npcs/Ehrhard.lua
34
1432
----------------------------------- -- Area: Port Bastok -- NPC: Ehrhard -- Involved in Quest: Stamp Hunt ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local StampHunt = player:getQuestStatus(BASTOK,STAMP_HUNT); if (StampHunt == QUEST_ACCEPTED and player:getMaskBit(player:getVar("StampHunt_Mask"),5) == false) then player:startEvent(0x0079); 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 == 0x0079) then player:setMaskBit(player:getVar("StampHunt_Mask"),"StampHunt_Mask",5,true); end end;
gpl-3.0
reekoheek/dotfiles
nvim/.config/nvim/lua/config/lsp.lua
1
5674
local lspconfig = require 'lspconfig' local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true -- capabilities.textDocument.completion.completionItem.documentationFormat = { 'markdown' } -- capabilities.textDocument.completion.completionItem.preselectSupport = true -- capabilities.textDocument.completion.completionItem.insertReplaceSupport = true -- capabilities.textDocument.completion.completionItem.labelDetailsSupport = true -- capabilities.textDocument.completion.completionItem.deprecatedSupport = true -- capabilities.textDocument.completion.completionItem.commitCharactersSupport = true -- capabilities.textDocument.completion.completionItem.tagSupport = { valueSet = { 1 } } -- capabilities.textDocument.completion.completionItem.resolveSupport = { -- properties = { -- 'documentation', -- 'detail', -- 'additionalTextEdits', -- }, -- } -- capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()); local servers = { jdtls = { cmd = { 'jdtls' }, root_dir = function(fname) return lspconfig.util.root_pattern('pom.xml', 'gradle.build', '.git')(fname) or vim.fn.getcwd() end, }, tsserver = { on_attach = function(client) client.resolved_capabilities.document_formatting = false end }, eslint = {}, jsonls = { filetypes = { 'json', 'jsonc' }, settings = { json = { schemas = { { fileMatch = { 'package.json' }, url = 'https://json.schemastore.org/package.json', }, { fileMatch = { 'jsconfig*.json' }, url = 'https://json.schemastore.org/jsconfig.json', }, { fileMatch = { 'tsconfig*.json' }, url = 'https://json.schemastore.org/tsconfig.json', }, { fileMatch = { '.prettierrc', '.prettierrc.json', 'prettier.config.json', }, url = 'https://json.schemastore.org/prettierrc.json', }, { fileMatch = { '.eslintrc', '.eslintrc.json' }, url = 'https://json.schemastore.org/eslintrc.json', }, { fileMatch = { 'nodemon.json' }, url = 'https://json.schemastore.org/nodemon.json', }, }, }, }, }, html = {}, cssls = {}, intelephense = { root_dir = vim.loop.cwd }, gopls = { on_attach = function(client) client.resolved_capabilities.document_formatting = false function goimports(timeoutms) local context = { source = { organizeImports = true } } vim.validate { context = { context, "t", true } } local params = vim.lsp.util.make_range_params() params.context = context local method = "textDocument/codeAction" local resp = vim.lsp.buf_request_sync(0, method, params, timeoutms) if resp and resp[1] then local result = resp[1].result if result and result[1] then local edit = result[1].edit vim.lsp.util.apply_workspace_edit(edit) end end vim.lsp.buf.formatting() end vim.cmd[[ augroup roh_goimports au! autocmd BufWritePre *.go lua goimports(1000) augroup END ]] end, settings = { gopls = { codelenses = { references = true, test = true, tidy = true, upgrade_dependency = true, generate = true, }, gofumpt = true, }, }, }, vimls = {}, pyright = {}, -- ['null-ls'] = { -- pre_init = function(client) -- end, -- }, } for name, opts in pairs(servers) do if type(opts) == 'function' then opts() else local on_attach = function(client, bufnr) if opts.on_attach then opts.on_attach(client, bufnr) end if client.resolved_capabilities.code_lens then vim.cmd [[ augroup roh_codelens au! au InsertEnter,InsertLeave * lua vim.lsp.codelens.refresh() augroup END ]] end local options = { noremap = true, silent = true } vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<cr>', options) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gd', '<cmd>lua vim.lsp.buf.definition()<cr>', options) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gD', '<cmd>lua vim.lsp.buf.type_definition()<cr>', options) vim.api.nvim_buf_set_keymap(bufnr, 'n', ']g', '<cmd>lua vim.diagnostic.goto_next()<cr>', options) vim.api.nvim_buf_set_keymap(bufnr, 'n', '[g', '<cmd>lua vim.diagnostic.goto_prev()<cr>', options) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'K', '<cmd>lua vim.lsp.buf.hover()<cr>', options) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<cr>', options) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<cr>', options) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gr', ':<C-u>lua require[[telescope.builtin]].lsp_references()<CR>', options) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gi', '<cmd>lua require[[telescope.builtin]].lsp_implementations()<cr>', options) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader><cr>', '<cmd>lua require("telescope.builtin").lsp_code_actions()<cr>', options) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>r', '<cmd>lua vim.lsp.buf.rename()<cr>', options) -- require 'lsp_signature'.on_attach() end local on_init = function(client) if opts.on_init then opts.on_init(client) end -- vim.notify('Language Server Client successfully started!', 'info', { -- title = client.name, -- }) end if opts.pre_init then opts.pre_init() end local client = lspconfig[name] client.setup(vim.tbl_extend('force', { -- flags = { debounce_text_changes = 150 }, on_attach = on_attach, on_init = on_init, capabilities = capabilities, }, opts)) end end
mit
Lsty/ygopro-scripts
c28573958.lua
5
3473
--奇跡の代行者 ジュピター function c28573958.initial_effect(c) --atkup local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(28573958,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetCountLimit(1) e1:SetRange(LOCATION_MZONE) e1:SetCost(c28573958.atcost) e1:SetTarget(c28573958.attg) e1:SetOperation(c28573958.atop) c:RegisterEffect(e1) --spsummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(28573958,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCondition(c28573958.spcon) e2:SetCost(c28573958.spcost) e2:SetTarget(c28573958.sptg) e2:SetOperation(c28573958.spop) c:RegisterEffect(e2) end function c28573958.cfilter1(c) return c:IsSetCard(0x44) and c:IsAbleToRemoveAsCost() end function c28573958.atcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c28573958.cfilter1,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c28573958.cfilter1,tp,LOCATION_GRAVE,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c28573958.filter1(c) return c:IsFaceup() and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsRace(RACE_FAIRY) end function c28573958.attg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c28573958.filter1(chkc) end if chk==0 then return Duel.IsExistingTarget(c28573958.filter1,tp,LOCATION_MZONE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c28573958.filter1,tp,LOCATION_MZONE,0,1,1,nil) end function c28573958.atop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(800) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) end end function c28573958.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.IsEnvironment(56433456) end function c28573958.cfilter2(c) return c:IsRace(RACE_FAIRY) and c:IsDiscardable() end function c28573958.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c28573958.cfilter2,tp,LOCATION_HAND,0,1,nil) end Duel.DiscardHand(tp,c28573958.cfilter2,1,1,REASON_COST+REASON_DISCARD) end function c28573958.filter2(c,e,tp) return c:IsFaceup() and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsRace(RACE_FAIRY) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c28573958.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(tp) and c28573958.filter2(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c28573958.filter2,tp,LOCATION_REMOVED,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c28573958.filter2,tp,LOCATION_REMOVED,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c28573958.spop(e,tp,eg,ep,ev,re,r,rp) if not Duel.IsEnvironment(56433456) then return end local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
MalRD/darkstar
scripts/zones/Giddeus/IDs.lua
11
2645
----------------------------------- -- Area: Giddeus ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.GIDDEUS] = { text = { ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6388, -- Obtained: <item>. GIL_OBTAINED = 6389, -- Obtained <number> gil. KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>. NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here. SENSE_OF_FOREBODING = 6403, -- You are suddenly overcome with a sense of foreboding... CONQUEST_BASE = 7049, -- Tallying conquest results... FISHING_MESSAGE_OFFSET = 7208, -- You can't fish here. SPRING_FILL_UP = 7354, -- You fill your flask with water. SPRING_DEFAULT = 7355, -- Sparkling clear water bubbles up from the ground. If you have a container, you can fill it here. CHEST_UNLOCKED = 7388, -- You unlock the chest! HARVESTING_IS_POSSIBLE_HERE = 7396, -- Harvesting is possible here if you have <item>. HOMEPOINT_SET = 7424, -- Home point set! }, mob = { HOO_MJUU_THE_TORRENT_PH = { [17371490] = 17371515, -- -63.000 -0.860 -91.000 [17371498] = 17371515, -- -32.000 0.740 -105.000 [17371486] = 17371515, -- -37.100 0.582 -127.259 [17371504] = 17371515, -- -42.389 0.315 -130.930 [17371508] = 17371515, -- -57.000 -2.000 -119.000 [17371513] = 17371515, -- -39.073 0.597 -115.279 }, JUU_DUZU_THE_WHIRLWIND_PH = { [17371298] = 17371300, -- 116.667 -3.442 -261.079 [17371533] = 17371300, -- 85.728 -0.071 -248.141 [17371291] = 17371300, -- 99.902 -2.725 -213.337 [17371525] = 17371300, -- 81.263 0.498 -208.812 [17371529] = 17371300, -- 72.302 0.642 -202.985 [17371519] = 17371300, -- 20.353 -3.647 -169.309 }, VUU_PUQU_THE_BEGUILER_PH = { [17371577] = 17371578, -- -23.973 0.459 -399.155 }, VAA_HUJA_THE_ERUDITE = 17371579, }, npc = { TREASURE_CHEST = 17371608, HARVESTING = { 17371609, 17371610, 17371611, 17371612, 17371613, 17371614, }, }, } return zones[dsp.zone.GIDDEUS]
gpl-3.0
MalRD/darkstar
scripts/globals/abilities/box_step.lua
12
7949
----------------------------------- -- Ability: Box Step -- Lowers target's defense. If successful, you will earn two Finishing Moves. -- Obtained: Dancer Level 30 -- TP Required: 10% -- Recast Time: 00:05 -- Duration: First Step lasts 1 minute, each following Step extends its current duration by 30 seconds. ----------------------------------- require("scripts/globals/weaponskills") require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getAnimation() ~= 1) then return dsp.msg.basic.REQUIRES_COMBAT,0 else if (player:hasStatusEffect(dsp.effect.TRANCE)) then return 0,0 elseif (player:getTP() < 100) then return dsp.msg.basic.NOT_ENOUGH_TP,0 else return 0,0 end end end function onUseAbility(player,target,ability,action) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(dsp.effect.TRANCE) then player:delTP(100) end local hit = 2 local effect = 1 if math.random() <= getHitRate(player,target,true,player:getMod(dsp.mod.STEP_ACCURACY)) then hit = 6 local mjob = player:getMainJob() local daze = 1 if (mjob == 19) then if (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_1)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_1):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_1) if (player:hasStatusEffect(dsp.effect.PRESTO)) then target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_3,1,0,duration+30) daze = 3 effect = 3 else target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_2,1,0,duration+30) daze = 2 effect = 2 end elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_2)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_2):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_2) if (player:hasStatusEffect(dsp.effect.PRESTO)) then target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_4,1,0,duration+30) daze = 3 effect = 4 else target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_3,1,0,duration+30) daze = 2 effect = 3 end elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_3)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_3):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_3) if (player:hasStatusEffect(dsp.effect.PRESTO)) then target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_5,1,0,duration+30) daze = 3 effect = 5 else target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_4,1,0,duration+30) daze = 2 effect = 4 end elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_4)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_4):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_4) if (player:hasStatusEffect(dsp.effect.PRESTO)) then daze = 3 else daze = 2 end target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_5,1,0,duration+30) effect = 5 elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_5)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_5):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_5) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_5,1,0,duration+30) daze = 1 effect = 5 else if (player:hasStatusEffect(dsp.effect.PRESTO)) then target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_2,1,0,60) daze = 3 effect = 2 else target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_1,1,0,60) daze = 2 effect = 1 end end else if (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_1)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_1):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_1) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_2,1,0,duration+30) effect = 2 elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_2)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_2):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_2) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_3,1,0,duration+30) effect = 3 elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_3)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_3):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_3) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_4,1,0,duration+30) effect = 4 elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_4)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_4):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_4) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_5,1,0,duration+30) effect = 5 elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_5)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_5):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_5) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_5,1,0,duration+30) effect = 5 else target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_1,1,0,60) effect = 1 end end if (player:hasStatusEffect(dsp.effect.FINISHING_MOVE_1)) then player:delStatusEffectSilent(dsp.effect.FINISHING_MOVE_1) player:addStatusEffect(dsp.effect.FINISHING_MOVE_1+daze,1,0,7200) elseif (player:hasStatusEffect(dsp.effect.FINISHING_MOVE_2)) then player:delStatusEffectSilent(dsp.effect.FINISHING_MOVE_2) player:addStatusEffect(dsp.effect.FINISHING_MOVE_2+daze,1,0,7200) elseif (player:hasStatusEffect(dsp.effect.FINISHING_MOVE_3)) then player:delStatusEffectSilent(dsp.effect.FINISHING_MOVE_3) if (daze > 2) then daze = 2 end player:addStatusEffect(dsp.effect.FINISHING_MOVE_3+daze,1,0,7200) elseif (player:hasStatusEffect(dsp.effect.FINISHING_MOVE_4)) then player:delStatusEffectSilent(dsp.effect.FINISHING_MOVE_4) player:addStatusEffect(dsp.effect.FINISHING_MOVE_5,1,0,7200) elseif (player:hasStatusEffect(dsp.effect.FINISHING_MOVE_5)) then else player:addStatusEffect(dsp.effect.FINISHING_MOVE_1 - 1 + daze,1,0,7200) end else ability:setMsg(dsp.msg.basic.JA_MISS) end action:animation(target:getID(), getStepAnimation(player:getWeaponSkillType(dsp.slot.MAIN))) action:speceffect(target:getID(), hit) return effect end
gpl-3.0
MalRD/darkstar
scripts/zones/Windurst_Woods/npcs/Bin_Stejihna.lua
12
1365
----------------------------------- -- Area: Windurst_Woods -- NPC: Bin Stejihna -- Only sells when Windurst controlls Zulkheim Region -- Confirmed shop stock, August 2013 ----------------------------------- local ID = require("scripts/zones/Windurst_Woods/IDs") require("scripts/globals/shop") require("scripts/globals/zone") ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) local RegionOwner = GetRegionOwner(dsp.region.ZULKHEIM) if RegionOwner ~= dsp.nation.WINDURST then player:showText(npc,ID.text.BIN_STEJIHNA_CLOSED_DIALOG) else player:showText(npc,ID.text.BIN_STEJIHNA_OPEN_DIALOG) local rank = getNationRank(dsp.nation.WINDURST) if rank ~= 3 then table.insert(stock, 1840) --Semolina table.insert(stock, 1840) end local stock = { 1840, 1840, -- Semolina 4372, 44, -- Giant Sheep Meat 622, 44, -- Dried Marjoram 610, 55, -- San d'Orian Flour 611, 36, -- Rye Flour 4366, 22, -- La Theine Cabbage 4378, 55 -- Selbina Milk } dsp.shop.general(player, stock, WINDURST) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
gpl-3.0
MalRD/darkstar
scripts/zones/Jugner_Forest_[S]/IDs.lua
9
1685
----------------------------------- -- Area: Jugner_Forest_[S] ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.JUGNER_FOREST_S] = { text = { NOTHING_HAPPENS = 119, -- Nothing happens... ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6388, -- Obtained: <item>. GIL_OBTAINED = 6389, -- Obtained <number> gil. KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>. NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here. LOGGING_IS_POSSIBLE_HERE = 7069, -- Logging is possible here if you have <item>. FISHING_MESSAGE_OFFSET = 7362, -- You can't fish here. ALREADY_OBTAINED_TELE = 7698, -- You already possess the gate crystal for this telepoint. COMMON_SENSE_SURVIVAL = 9500, -- It appears that you have arrived at a new survival guide provided by the Servicemen's Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world. }, mob = { DRUMSKULL_ZOGDREGG_PH = { [17113380] = 17113381, -- 195.578 -0.556 -347.699 }, FINGERFILCHER_DRADZAD = 17113462, COBRACLAW_BUCHZVOTCH = 17113464, }, npc = { LOGGING = { 17113901, 17113902, 17113903, 17113904, 17113905, 17113906, }, }, } return zones[dsp.zone.JUGNER_FOREST_S]
gpl-3.0
Wuzzy2/mobs_mc
pig.lua
1
4724
--License for code WTFPL and otherwise stated in readmes -- intllib local MP = minetest.get_modpath(minetest.get_current_modname()) local S, NS = dofile(MP.."/intllib.lua") mobs:register_mob("mobs_mc:pig", { type = "animal", runaway = true, hp_min = 10, hp_max = 10, collisionbox = {-0.45, -0.01, -0.45, 0.45, 0.865, 0.45}, visual = "mesh", mesh = "mobs_mc_pig.b3d", textures = {{ "blank.png", -- baby "mobs_mc_pig.png", -- base "blank.png", -- saddle }}, visual_size = {x=2.5, y=2.5}, makes_footstep_sound = true, walk_velocity = 1, run_velocity = 3, drops = { {name = mobs_mc.items.porkchop_raw, chance = 1, min = 1, max = 3,}, }, water_damage = 1, lava_damage = 4, light_damage = 0, fear_height = 4, sounds = { random = "mobs_pig", death = "mobs_pig_angry", damage = "mobs_pig", distance = 16, }, animation = { stand_speed = 40, walk_speed = 40, run_speed = 50, stand_start = 0, stand_end = 0, walk_start = 0, walk_end = 40, run_start = 0, run_end = 40, }, follow = mobs_mc.follow.pig, view_range = 5, do_custom = function(self, dtime) -- set needed values if not already present if not self.v2 then self.v2 = 0 self.max_speed_forward = 4 self.max_speed_reverse = 2 self.accel = 4 self.terrain_type = 3 self.driver_attach_at = {x = 0.0, y = 6.75, z = -1.5} self.driver_eye_offset = {x = 0, y = 3, z = 0} self.driver_scale = {x = 1/self.visual_size.x, y = 1/self.visual_size.y} end -- if driver present allow control of horse if self.driver then mobs.drive(self, "walk", "stand", false, dtime) return false -- skip rest of mob functions end return true end, on_die = function(self, pos) -- drop saddle when horse is killed while riding -- also detach from horse properly if self.driver then mobs.detach(self.driver, {x = 1, y = 0, z = 1}) end end, on_rightclick = function(self, clicker) if not clicker or not clicker:is_player() then return end local wielditem = clicker:get_wielded_item() -- Feed pig if wielditem:get_name() ~= mobs_mc.items.carrot_on_a_stick then if mobs:feed_tame(self, clicker, 1, true, true) then return end end if mobs:protect(self, clicker) then return end if self.child then return end -- Put saddle on pig local item = clicker:get_wielded_item() if item:get_name() == mobs_mc.items.saddle and self.saddle ~= "yes" then self.base_texture = { "blank.png", -- baby "mobs_mc_pig.png", -- base "mobs_mc_pig_saddle.png", -- saddle } self.object:set_properties({ textures = self.base_texture }) self.saddle = "yes" self.tamed = true self.drops = { {name = mobs_mc.items.porkchop_raw, chance = 1, min = 1, max = 3,}, {name = mobs_mc.items.saddle, chance = 1, min = 1, max = 1,}, } if not minetest.settings:get_bool("creative_mode") then local inv = clicker:get_inventory() local stack = inv:get_stack("main", clicker:get_wield_index()) stack:take_item() inv:set_stack("main", clicker:get_wield_index(), stack) end return end -- Mount or detach player local name = clicker:get_player_name() if self.driver and clicker == self.driver then -- Detach if already attached mobs.detach(clicker, {x=1, y=0, z=0}) return elseif not self.driver and self.saddle == "yes" and wielditem:get_name() == mobs_mc.items.carrot_on_a_stick then -- Ride pig if it has a saddle and player uses a carrot on a stick mobs.attach(self, clicker) if not minetest.settings:get_bool("creative_mode") then local inv = self.driver:get_inventory() -- 26 uses if wielditem:get_wear() > 63000 then -- Break carrot on a stick local def = wielditem:get_definition() if def.sounds and def.sounds.breaks then minetest.sound_play(def.sounds.breaks, {pos = clicker:getpos(), max_hear_distance = 8, gain = 0.5}) end wielditem = {name = mobs_mc.items.fishing_rod, count = 1} else wielditem:add_wear(2521) end inv:set_stack("main",self.driver:get_wield_index(), wielditem) end return -- Capture pig elseif not self.driver and clicker:get_wielded_item():get_name() ~= "" then mobs:capture_mob(self, clicker, 0, 5, 60, false, nil) end end, }) mobs:spawn_specific("mobs_mc:pig", mobs_mc.spawn.grassland, {"air"}, 9, minetest.LIGHT_MAX+1, 30, 15000, 30, mobs_mc.spawn_height.overworld_min, mobs_mc.spawn_height.overworld_max) -- compatibility mobs:alias_mob("mobs:pig", "mobs_mc:pig") -- spawn eggs mobs:register_egg("mobs_mc:pig", S("Pig"), "mobs_mc_spawn_icon_pig.png", 0) if minetest.settings:get_bool("log_mods") then minetest.log("action", "MC Pig loaded") end
gpl-3.0
Lsty/ygopro-scripts
c66518841.lua
5
1372
--プライドの咆哮 function c66518841.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE) e1:SetCondition(c66518841.condition) e1:SetCost(c66518841.cost) e1:SetOperation(c66518841.activate) c:RegisterEffect(e1) end function c66518841.condition(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetAttacker() if tc:IsControler(1-tp) then tc=Duel.GetAttackTarget() end if not tc then return false end local bc=tc:GetBattleTarget() if tc and bc then local dif=bc:GetAttack()-tc:GetAttack() e:SetLabel(dif) return dif>0 else return false end end function c66518841.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckLPCost(tp,e:GetLabel()) end Duel.PayLPCost(tp,e:GetLabel()) end function c66518841.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetAttacker() if tc:IsControler(1-tp) then tc=Duel.GetAttackTarget() end local bc=tc:GetBattleTarget() local dif=bc:GetAttack()-tc:GetAttack() if dif>0 and tc:IsRelateToBattle() and bc:IsRelateToBattle() and tc:IsFaceup() and bc:IsFaceup() then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_DAMAGE_CAL) e1:SetValue(dif+300) tc:RegisterEffect(e1) end end
gpl-2.0
MalRD/darkstar
scripts/zones/Temenos/bcnms/central_temenos_1st_floor.lua
9
1338
----------------------------------- -- Area: Temenos -- Name: Central Temenos 1st Floor ----------------------------------- require("scripts/globals/limbus"); require("scripts/globals/battlefield") require("scripts/globals/keyitems"); -- After registering the BCNM via bcnmRegister(bcnmid) function onBattlefieldTick(battlefield, tick) dsp.battlefield.onBattlefieldTick(battlefield, tick) end function onBattlefieldRegister(player,battlefield) SetServerVariable("[C_Temenos_1st]UniqueID",os.time()); HideArmouryCrates(Central_Temenos_1st_Floor,TEMENOS); HideTemenosDoor(Central_Temenos_1st_Floor); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBattlefieldEnter(player,battlefield) player:setCharVar("characterLimbusKey",GetServerVariable("[C_Temenos_1st]UniqueID")); player:delKeyItem(dsp.ki.COSMOCLEANSE); player:delKeyItem(dsp.ki.WHITE_CARD); end; -- Leaving by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBattlefieldLeave(player,battlefield,leavecode) --print("leave code "..leavecode); if leavecode == dsp.battlefield.leaveCode.LOST then SetServerVariable("[C_Temenos_1st]UniqueID",0); player:setPos(580,-1.5,4.452,192); end end;
gpl-3.0
Lsty/ygopro-scripts
c25716180.lua
9
1042
--ゼンマイニャンコ function c25716180.initial_effect(c) --to hand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(25716180,0)) e1:SetCategory(CATEGORY_TOHAND) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_NO_TURN_RESET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetTarget(c25716180.target) e1:SetOperation(c25716180.operation) c:RegisterEffect(e1) end function c25716180.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and chkc:IsAbleToHand() end if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToHand,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND) local g=Duel.SelectTarget(tp,Card.IsAbleToHand,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0) end function c25716180.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc and tc:IsRelateToEffect(e) then Duel.SendtoHand(tc,nil,REASON_EFFECT) end end
gpl-2.0
Lsty/ygopro-scripts
c68661341.lua
7
1759
--一点買い function c68661341.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(c68661341.cost) e1:SetTarget(c68661341.target) e1:SetOperation(c68661341.activate) c:RegisterEffect(e1) end function c68661341.cfilter(c) return c:IsType(TYPE_MONSTER) or not c:IsAbleToRemoveAsCost() end function c68661341.cost(e,tp,eg,ep,ev,re,r,rp,chk) local g=Duel.GetFieldGroup(tp,LOCATION_HAND,0) g:RemoveCard(e:GetHandler()) if chk==0 then return g:GetCount()>=3 and not g:IsExists(c68661341.cfilter,1,nil) end Duel.Remove(g,POS_FACEUP,REASON_COST) end function c68661341.filter(c) return c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c68661341.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c68661341.filter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c68661341.activate(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c68661341.filter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetCode(EFFECT_CANNOT_SUMMON) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetTargetRange(1,0) e1:SetTarget(c68661341.sumlimit) e1:SetLabel(g:GetFirst():GetCode()) Duel.RegisterEffect(e1,tp) local e2=e1:Clone() e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) Duel.RegisterEffect(e2,tp) end end function c68661341.sumlimit(e,c) return c:GetCode()~=e:GetLabel() end
gpl-2.0
MalRD/darkstar
scripts/globals/abilities/pets/attachments/strobe.lua
11
1471
----------------------------------- -- Attachment: Strobe -- http://forum.square-enix.com/ffxi/threads/49065?p=565264#post565264 -- Values are currently PRIOR TO NOVEMBER 2015 UPDATE! ----------------------------------- require("scripts/globals/automaton") require("scripts/globals/status") ----------------------------------- function onEquip(pet) updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 5) pet:addListener("AUTOMATON_ATTACHMENT_CHECK", "ATTACHMENT_STROBE", function(automaton, target) if automaton:getLocalVar("provoke") < VanadielTime() and (automaton:checkDistance(target) - target:getModelSize()) < 7 then automaton:useMobAbility(1945) else return 0 end end) end function onUnequip(pet) updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 0) pet:removeListener("ATTACHMENT_STROBE") end function onManeuverGain(pet, maneuvers) onUpdate(pet, maneuvers) end function onManeuverLose(pet, maneuvers) onUpdate(pet, maneuvers - 1) end function onUpdate(pet, maneuvers) if maneuvers == 0 then updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 5) elseif maneuvers == 1 then updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 10) elseif maneuvers == 2 then updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 15) elseif maneuvers == 3 then updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 20) end end
gpl-3.0
MalRD/darkstar
scripts/globals/items/frostreaper.lua
12
1065
----------------------------------------- -- ID: 16784 -- Item: Frostreaper -- Additional Effect: Ice Damage ----------------------------------------- require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5 if (math.random(0,99) >= chance) then return 0,0,0 else local dmg = math.random(3,10) local params = {} params.bonusmab = 0 params.includemab = false dmg = addBonusesAbility(player, dsp.magic.ele.ICE, target, dmg, params) dmg = dmg * applyResistanceAddEffect(player,target,dsp.magic.ele.ICE,0) dmg = adjustForTarget(target,dmg,dsp.magic.ele.ICE) dmg = finalMagicNonSpellAdjustments(player,target,dsp.magic.ele.ICE,dmg) local message = dsp.msg.basic.ADD_EFFECT_DMG if (dmg < 0) then message = dsp.msg.basic.ADD_EFFECT_HEAL end return dsp.subEffect.ICE_DAMAGE,message,dmg end end
gpl-3.0
Lsty/ygopro-scripts
c27062594.lua
3
3096
--運命の扉 function c27062594.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_ATTACK_ANNOUNCE) e1:SetCondition(c27062594.condition) e1:SetTarget(c27062594.target) e1:SetOperation(c27062594.activate) c:RegisterEffect(e1) end function c27062594.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetAttacker():IsControler(1-tp) and Duel.GetAttackTarget()==nil end function c27062594.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,27062594,0,0x21,0,0,1,RACE_FIEND,ATTRIBUTE_LIGHT) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c27062594.activate(e,tp,eg,ep,ev,re,r,rp) if not Duel.NegateAttack() then return end Duel.BreakEffect() if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end local c=e:GetHandler() if not c:IsRelateToEffect(e) or not Duel.IsPlayerCanSpecialSummonMonster(tp,27062594,0,0x21,0,0,1,RACE_FIEND,ATTRIBUTE_LIGHT) then return end c:AddTrapMonsterAttribute(TYPE_EFFECT,ATTRIBUTE_LIGHT,RACE_FIEND,1,0,0) Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP) c:TrapMonsterBlock() local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(27062594,0)) e1:SetCategory(CATEGORY_DAMAGE) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCode(EVENT_PHASE+PHASE_STANDBY) e1:SetCondition(c27062594.damcon) e1:SetCost(c27062594.damcost) e1:SetTarget(c27062594.damtg) e1:SetOperation(c27062594.damop) e1:SetReset(RESET_EVENT+0x1fe0000) c:RegisterEffect(e1) end function c27062594.damcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c27062594.cfilter(c) return c:IsSetCard(0x7f) and c:IsAbleToRemoveAsCost() end function c27062594.damcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c27062594.cfilter,tp,LOCATION_GRAVE,0,1,nil) end local g=Duel.GetMatchingGroup(c27062594.cfilter,tp,LOCATION_GRAVE,0,nil) local rg=Group.CreateGroup() repeat Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local sg=g:Select(tp,1,1,nil) g:Remove(Card.IsCode,nil,sg:GetFirst():GetCode()) rg:Merge(sg) until g:GetCount()==0 or not Duel.SelectYesNo(tp,aux.Stringid(27062594,1)) local ct=Duel.Remove(rg,POS_FACEUP,REASON_COST) e:SetLabel(ct) end function c27062594.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(e:GetLabel()*500) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,e:GetLabel()*500) end function c27062594.damop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) local val=Duel.Damage(p,d,REASON_EFFECT) local c=e:GetHandler() if c:IsFaceup() and c:IsRelateToEffect(e) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(val) e1:SetReset(RESET_EVENT+0x1ff0000) c:RegisterEffect(e1) end end
gpl-2.0
Lsty/ygopro-scripts
c84877802.lua
3
1872
--最強の盾 function c84877802.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_EQUIP) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetTarget(c84877802.target) e1:SetOperation(c84877802.operation) c:RegisterEffect(e1) --atk/def local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_EQUIP) e2:SetCode(EFFECT_UPDATE_ATTACK) e2:SetValue(c84877802.atkval) c:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_EQUIP) e3:SetCode(EFFECT_UPDATE_DEFENCE) e3:SetValue(c84877802.defval) c:RegisterEffect(e3) --Equip limit local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_EQUIP_LIMIT) e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e4:SetValue(c84877802.equiplimit) c:RegisterEffect(e4) end function c84877802.equiplimit(e,c) return c:IsRace(RACE_WARRIOR) end function c84877802.filter(c) return c:IsFaceup() and c:IsRace(RACE_WARRIOR) end function c84877802.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and c84877802.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c84877802.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) Duel.SelectTarget(tp,c84877802.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0) end function c84877802.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if e:GetHandler():IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then Duel.Equip(tp,e:GetHandler(),tc) end end function c84877802.atkval(e,c) if c:IsDefencePos() then return 0 else return c:GetBaseDefence() end end function c84877802.defval(e,c) if c:IsAttackPos() then return 0 else return c:GetBaseAttack() end end
gpl-2.0
MalRD/darkstar
scripts/globals/items/plate_of_sole_sushi_+1.lua
11
1437
----------------------------------------- -- ID: 5163 -- Item: plate_of_sole_sushi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 20 -- Strength 5 -- Dexterity 6 -- Accuracy % 16 -- Ranged ACC % 16 -- Sleep Resist 2 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,3600,5163) end function onEffectGain(target, effect) target:addMod(dsp.mod.HP, 20) target:addMod(dsp.mod.STR, 5) target:addMod(dsp.mod.DEX, 6) target:addMod(dsp.mod.FOOD_ACCP, 16) target:addMod(dsp.mod.FOOD_ACC_CAP, 76) target:addMod(dsp.mod.FOOD_RACCP, 16) target:addMod(dsp.mod.FOOD_RACC_CAP, 76) target:addMod(dsp.mod.SLEEPRES, 2) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 20) target:delMod(dsp.mod.STR, 5) target:delMod(dsp.mod.DEX, 6) target:delMod(dsp.mod.FOOD_ACCP, 16) target:delMod(dsp.mod.FOOD_ACC_CAP, 76) target:delMod(dsp.mod.FOOD_RACCP, 16) target:delMod(dsp.mod.FOOD_RACC_CAP, 76) target:delMod(dsp.mod.SLEEPRES, 2) end
gpl-3.0
Lsty/ygopro-scripts
c97232518.lua
3
1309
--深淵のスタングレイ function c97232518.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c97232518.target) e1:SetOperation(c97232518.activate) c:RegisterEffect(e1) end function c97232518.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,97232518,0,0x21,1900,0,5,RACE_THUNDER,ATTRIBUTE_LIGHT) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c97232518.activate(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 or not Duel.IsPlayerCanSpecialSummonMonster(tp,97232518,0,0x21,1900,0,5,RACE_THUNDER,ATTRIBUTE_LIGHT) then return end c:AddTrapMonsterAttribute(TYPE_EFFECT,ATTRIBUTE_LIGHT,RACE_THUNDER,5,1900,0) Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP) c:TrapMonsterBlock() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e1:SetRange(LOCATION_MZONE) e1:SetValue(1) e1:SetReset(RESET_EVENT+0x1fe0000) c:RegisterEffect(e1) end
gpl-2.0
peterkohaut/scummvm
devtools/create_ultima/files/ultima6/scripts/se/lang/en/game.lua
19
3136
return { PASS="Pass!\n", YOU_SEE="you see %s", NOTHING="nothing!\n", SEARCHING_HERE_YOU_FIND="Searching here, you find %s", SEARCHING_HERE_YOU_FIND_NOTHING="Searching here, you find nothing.\n", SEARCH_NEXT_OBJ=", %s", SEARCH_LAST_OBJ=" and %s", OUT_OF_RANGE="Out of Range!\n", BLAH="Blah", CARRY_TOO_MUCH="You are carrying too much already.\n", GOT_CORN="You got some corn from the plant.\n", USE_CLAY="You shaped a small, soft pot from the clay.\n", USE_FISHING_POLE_NO_WATER="You need to stand next to deep water.\n", USE_FISHING_POLE_FAIL="You didn't get a fish.\n", USE_FISHING_POLE_SUCCESS="You caught a fish!\n", USE_DIGGING_STICK_NO_WATER="There is nothing to dig!\n", USE_DIGGING_STICK="You get some clay.\n", USE_YUCCA_PLANT="You got some flax from the yucca plant.\n", USE_TREE="You pulled a branch from the tree.\n", IMG1_TXT1_END="Members of all the tribes come for the feast... the largest and most important feast ever held in the Valley of Eodon.", IMG1_TXT2_END="Kurak sits beside Yolaru, Pindiro beside Barako, Haakur beside Sakkhra, and peace is sworn between the tribes.", IMG1_TXT3_END="You know this peace isn't for you. Soon enough, you will hear the call to action again. But tonight, there is time for music and dance, friendship and love.", IMG2_TXT1_END="At dawn, your past catches up with you... and your future beckons. A vision of Lord British appears before you.", IMG2_TXT2_END="\"You have done well,\" he says. \"But now I must take you where you are needed. For the sake of the friends you leave behind, I am sorry. Prepare yourself.\"", IMG3_TXT1_END="You say farewell to Aiela. \"Aiela does not know your world. Take her there,\" she pleads. \"Teach her of your world.", IMG3_TXT2_END="You shake your head. \"My world would strangle you. You must stay. My heart remains with you. But my duty is elsewhere... with him.\"", IMG3_TXT3_END="Tears roll down her cheeks. \"Abandon duty, and you will not be warrior Aiela loves. Choose duty, and you must leave. Either way, Aiela loses all... Farewell.\"", IMG4_TXT1_END="You say farewell to Tristia. \"I must go with Lord British,\" you say. \"My duty lies with him, though it breaks my heart.\"", IMG4_TXT2_END="Tristia laughs sweetly. \"Tristia does not mind,\" she says. \"Tristia has found another loves: handsome Botorok. Botorok is so much better than you. Go with your chief. Go.\"", IMG5_TXT1_END="You are joined by Spector's former assistant, Fritz, who came out of hiding to fight the Myrmidex, and bears their scars.", IMG5_TXT2_END="The moongate appears, summoned by the shade of Lord British. Jimmy, Spector and Fritz gather their belongs...", IMG5_TXT3_END="But Rafkin does not. \"I'm staying, my friend,\" he says, \"Someone must. I will stay here... and hope other scientists come. Farewell.\"", IMG5_TXT4_END="Saddened, you follow your friends and allies into the moongate, leaving the Valley of Eodon. Perhaps someday you will return to those you have left behind.", IMG2_TXT3_END="CONGRATULATIONS. You have completed THE SAVAGE EMPIRE in XXTIMESTRXX. Communicate your success to Lord British at Origin!", }
gpl-3.0
Mijyuoon/starfall
lua/moonscript/errors.lua
1
2937
local util = loadmodule("moonscript.util") local concat, insert do local _obj_0 = table concat, insert = _obj_0.concat, _obj_0.insert end local split, pos_to_line split, pos_to_line = util.split, util.pos_to_line local user_error user_error = function(...) return error({ "user-error", ... }) end local lookup_line lookup_line = function(fname, pos, cache) if not cache[fname] then do local _with_0 = assert(io.open(fname)) cache[fname] = _with_0:read("*a") _with_0:close() end end return pos_to_line(cache[fname], pos) end local reverse_line_number reverse_line_number = function(fname, line_table, line_num, cache) for i = line_num, 0, -1 do if line_table[i] then return lookup_line(fname, line_table[i], cache) end end return "unknown" end local truncate_traceback truncate_traceback = function(traceback, chunk_func) if chunk_func == nil then chunk_func = "moonscript_chunk" end traceback = split(traceback, "\n") local stop = #traceback while stop > 1 do if traceback[stop]:match(chunk_func) then break end stop = stop - 1 end do local _accum_0 = { } local _len_0 = 1 local _max_0 = stop for _index_0 = 1, _max_0 < 0 and #traceback + _max_0 or _max_0 do local t = traceback[_index_0] _accum_0[_len_0] = t _len_0 = _len_0 + 1 end traceback = _accum_0 end local rep = "function '" .. chunk_func .. "'" traceback[#traceback] = traceback[#traceback]:gsub(rep, "main chunk") return concat(traceback, "\n") end local rewrite_traceback rewrite_traceback = function(text, err) local data = loadmodule("moonscript.data") local V, S, Ct, C do local _obj_0 = lpeg V, S, Ct, C = _obj_0.V, _obj_0.S, _obj_0.Ct, _obj_0.C end local header_text = "stack traceback:" local Header, Line = V("Header"), V("Line") local Break = lpeg.S("\n") local g = lpeg.P({ Header, Header = header_text * Break * Ct(Line ^ 1), Line = "\t" * C((1 - Break) ^ 0) * (Break + -1) }) local cache = { } local rewrite_single rewrite_single = function(trace) local fname, line, msg = trace:match('^(.-):(%d+): (.*)$') local tbl = data.line_tables["@" .. tostring(fname)] if fname and tbl then return concat({ fname, ":", reverse_line_number(fname, tbl, line, cache), ": ", "(", line, ") ", msg }) else return trace end end err = rewrite_single(err) local match = g:match(text) if not (match) then return nil end for i, trace in ipairs(match) do match[i] = rewrite_single(trace) end return concat({ "moon: " .. err, header_text, "\t" .. concat(match, "\n\t") }, "\n") end return { rewrite_traceback = rewrite_traceback, truncate_traceback = truncate_traceback, user_error = user_error, reverse_line_number = reverse_line_number }
bsd-3-clause
Lsty/ygopro-scripts
c85520851.lua
3
1318
--超伝導恐獣 function c85520851.initial_effect(c) --damage local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(85520851,0)) e1:SetCategory(CATEGORY_DAMAGE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetCountLimit(1) e1:SetRange(LOCATION_MZONE) e1:SetCost(c85520851.cost) e1:SetTarget(c85520851.target) e1:SetOperation(c85520851.operation) c:RegisterEffect(e1) end function c85520851.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetAttackAnnouncedCount()==0 and Duel.CheckReleaseGroup(tp,nil,1,nil) end local sg=Duel.SelectReleaseGroup(tp,nil,1,1,nil) Duel.Release(sg,REASON_COST) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_OATH) e1:SetCode(EFFECT_CANNOT_ATTACK_ANNOUNCE) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END) e:GetHandler():RegisterEffect(e1) end function c85520851.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(1000) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,1000) end function c85520851.operation(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end
gpl-2.0
Lsty/ygopro-scripts
c10117149.lua
3
3648
--ブンボーグ005 function c10117149.initial_effect(c) --pendulum summon aux.AddPendulumProcedure(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --splimit local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetRange(LOCATION_PZONE) e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE) e2:SetTargetRange(1,0) e2:SetCondition(aux.nfbdncon) e2:SetTarget(c10117149.splimit) c:RegisterEffect(e2) --destroy local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_DESTROY) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_SUMMON_SUCCESS) e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e3:SetTarget(c10117149.destg) e3:SetOperation(c10117149.desop) c:RegisterEffect(e3) local e4=e3:Clone() e4:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e4) --atk up local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_SINGLE) e5:SetCode(EFFECT_UPDATE_ATTACK) e5:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e5:SetRange(LOCATION_MZONE) e5:SetValue(c10117149.atkval) c:RegisterEffect(e5) --spsummon local e6=Effect.CreateEffect(c) e6:SetCategory(CATEGORY_SPECIAL_SUMMON) e6:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e6:SetCode(EVENT_DESTROYED) e6:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e6:SetCountLimit(1,10117149) e6:SetCondition(c10117149.spcon) e6:SetTarget(c10117149.sptg) e6:SetOperation(c10117149.spop) c:RegisterEffect(e6) end function c10117149.splimit(e,c,tp,sumtp,sumpos) return not c:IsSetCard(0xab) and bit.band(sumtp,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM end function c10117149.desfilter(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDestructable() end function c10117149.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and c10117149.desfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c10117149.desfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,c10117149.desfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function c10117149.desop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end function c10117149.cfilter(c) return c:IsFaceup() and c:IsSetCard(0xab) end function c10117149.atkval(e,c) return Duel.GetMatchingGroupCount(c10117149.cfilter,c:GetControler(),LOCATION_EXTRA,0,nil)*500 end function c10117149.spcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsPreviousLocation(LOCATION_SZONE) and (c:GetPreviousSequence()==6 or c:GetPreviousSequence()==7) end function c10117149.spfilter(c,e,tp) return c:IsSetCard(0xab) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c10117149.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c10117149.spfilter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c10117149.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c10117149.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c10117149.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
kianooshnoori/teleexitbot
bot/seedbot.lua
1
10265
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '2' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban", "admin" }, sudo_users = {211140992},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[Teleseed v2 - Open Source An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Our team! Alphonse (@Iwals) I M /-\ N (@Imandaneshi) Siyanew (@Siyanew) Rondoozle (@Potus) Seyedan (@Seyedan25) Special thanks to: Juan Potato Siyanew Topkecleon Vamptacus Our channels: English: @TeleSeedCH Persian: @IranSeed ]], help_text_realm = [[ Realm Commands: !creategroup [name] Create a group !createrealm [name] Create a realm !setname [name] Set realm name !setabout [group_id] [text] Set a group's about text !setrules [grupo_id] [text] Set a group's rules !lock [grupo_id] [setting] Lock a group's setting !unlock [grupo_id] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [grupo_id] Kick all memebers and delete group !kill realm [realm_id] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Get a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups » Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id Return group id or user id !help Get commands list !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules [text] Set [text] as rules !set about [text] Set [text] as about !settings Returns group settings !newlink Create/revoke your group link !link Returns group link !owner Returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] [text] Save [text] as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] Returns user id !log Will return group logs !banlist Will return group ban list » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
pevzi/Simple-Tiled-Implementation
init.lua
9
1323
--- Simple and fast Tiled map loader and renderer. -- @module sti -- @author Landon Manning -- @copyright 2015 -- @license MIT/X11 local STI = { _LICENSE = "MIT/X11", _URL = "https://github.com/karai17/Simple-Tiled-Implementation", _VERSION = "0.14.1.12", _DESCRIPTION = "Simple Tiled Implementation is a Tiled Map Editor library designed for the *awesome* LÖVE framework.", cache = {} } local path = (...):gsub('%.init$', '') .. "." local Map = require(path .. "map") --- Instance a new map. -- @param path Path to the map file. -- @param plugins A list of plugins to load. -- @param ox Offset of map on the X axis (in pixels) -- @param oy Offset of map on the Y axis (in pixels) -- @return table The loaded Map. function STI.new(map, plugins, ox, oy) -- Check for valid map type local ext = map:sub(-4, -1) assert(ext == ".lua", string.format( "Invalid file type: %s. File must be of type: lua.", ext )) -- Get path to map local path = map:reverse():find("[/\\]") or "" if path ~= "" then path = map:sub(1, 1 + (#map - path)) end -- Load map map = love.filesystem.load(map) setfenv(map, {}) map = setmetatable(map(), {__index = Map}) map:init(STI, path, plugins, ox, oy) return map end --- Flush image cache. function STI:flush() self.cache = {} end return STI
mit
rotmanmi/nn
Jacobian.lua
33
13475
nn.Jacobian = {} function nn.Jacobian.backward(module, input, param, dparam) local doparam = 0 if param then doparam = 1 end param = param or input -- output deriv module:forward(input) local dout = module.output.new():resizeAs(module.output) -- 1D view local sdout = module.output.new(dout:storage(),1,dout:nElement()) -- jacobian matrix to calculate local jacobian = torch.Tensor(param:nElement(),dout:nElement()):zero() for i=1,sdout:nElement() do dout:zero() sdout[i] = 1 module:zeroGradParameters() local din = module:updateGradInput(input, dout) module:accGradParameters(input, dout) if doparam == 1 then jacobian:select(2,i):copy(dparam) else jacobian:select(2,i):copy(din) end end return jacobian end function nn.Jacobian.backwardUpdate(module, input, param) -- output deriv module:forward(input) local dout = module.output.new():resizeAs(module.output) -- 1D view local sdout = module.output.new(dout:storage(),1,dout:nElement()) -- jacobian matrix to calculate local jacobian = torch.Tensor(param:nElement(),dout:nElement()):zero() -- original param local params = module:parameters() local origparams = {} for j=1,#params do table.insert(origparams, params[j]:clone()) end for i=1,sdout:nElement() do for j=1,#params do params[j]:copy(origparams[j]) end dout:zero() sdout[i] = 1 module:updateGradInput(input, dout) module:accUpdateGradParameters(input, dout, 1) jacobian:select(2,i):copy(param) end for j=1,#params do params[j]:copy(origparams[j]) end return jacobian end function nn.Jacobian.forward(module, input, param, perturbation) param = param or input -- perturbation amount perturbation = perturbation or 1e-6 -- 1D view of input --local tst = param:storage() local sin = param.new(param):resize(param:nElement())--param.new(tst,1,tst:size()) -- jacobian matrix to calculate local jacobian = torch.Tensor():resize(param:nElement(),module:forward(input):nElement()) local outa = torch.Tensor(jacobian:size(2)) local outb = torch.Tensor(jacobian:size(2)) for i=1,sin:nElement() do local orig = sin[i] sin[i] = orig - perturbation outa:copy(module:forward(input)) sin[i] = orig + perturbation outb:copy(module:forward(input)) sin[i] = orig outb:add(-1,outa):div(2*perturbation) jacobian:select(1,i):copy(outb) end return jacobian end function nn.Jacobian.backwardDiagHessian(module, input, diagHessianParamName) -- Compute the second derivatives (diagonal Hessian elements) -- by backpropagation (using the code from hessian.lua). -- -- This function computes the diagonal Hessian elements of the following function: -- -- F(x_1, x_2, ..., x_n) = y_1^2/2 + y_2^2/2 + ... + y_m^2/2, -- -- where -- x_1, ..., x_n are the input values and parameters of the given module, -- y_1, ..., y_m are the output values of the given module. -- -- All x_i and y_i values are scalars here. In other words, -- x_1, ..., x_n denote the scalar elements of the module input tensor, -- the scalar elements of module.weight, -- and the scalar elements of module.bias; -- y_1, ..., y_m are the scalar elements of the module output tensor. -- -- The diagonal Hessian elements of F are computed with respect to -- the module input values and parameters (x_1, .., x_n). -- -- The function F is chosen for its convenient properties: -- -- dF / dy_i = y_i, -- d^2F / dy_i^2 = 1. -- -- In other words, the diagonal Hessian elements of F with respect -- to the module OUTPUT values (y_1, ... y_m) are equal to 1. -- -- Because of that, computing the diagonal Hessian elements of F -- with respect to the module INPUT values and PARAMETERS (x_1, ..., x_n) -- can be done by calling updateDiagHessianInput() and accDiagHessianParameters() -- using a tensor of ones as diagHessianOutput. module:forward(input) local diagHessianOutput = module.output.new():resizeAs(module.output):fill(1) module.diagHessianWeight:zero() module.diagHessianBias:zero() module:updateDiagHessianInput(input, diagHessianOutput) module:accDiagHessianParameters(input, diagHessianOutput) return module[diagHessianParamName] end function nn.Jacobian.linearModuleDiagHessian(module, input, gradParamName) -- Compute the second derivatives (diagonal Hessian elements) -- from the first derivatives for the given module -- (without using the code from hessian.lua). -- -- The given module is assumed to be linear with respect to its inputs and weights -- (like nn.Linear, nn.SpatialConvolution, etc.) -- -- This function computes the diagonal Hessian elements of the following function: -- -- F(x_1, x_2, ..., x_n) = y_1^2/2 + y_2^2/2 + ... + y_m^2/2. -- -- (See the the comment for nn.Jacobian.backwardDiagHessian() for explanation.) -- -- The first derivatives of F with respect to -- the module inputs and parameters (x_1, ..., x_n) are: -- -- dF / dx_i = \sum_k (dF / dy_k) (dy_k / dx_i). -- -- The second derivatives are: -- -- d^2F / dx_i = \sum_k [(d^2F / dy_k^2) (dy_k / dx_i)^2 + (dF / dy_k) (d^2y_k / dx_i^2)]. -- -- The second derivatives of F with respect to the module outputs (y_1, ..., y_m) -- are equal to 1, so: -- -- d^2F / dx_i = \sum_k [(dy_k / dx_i)^2 + (dF / dy_k) (d^2y_k / dx_i^2)]. -- -- Assuming the linearity of module outputs (y_1, ..., y_m) -- with respect to module inputs and parameters (x_1, ..., x_n), -- we have (d^2y_k / dx_i^2) = 0, -- and the expression finally becomes: -- -- d^2F / dx_i = \sum_k (dy_k / dx_i)^2. -- -- The first derivatives (dy_k / dx_i) are computed by normal backpropagation, -- using updateGradInput() and accGradParameters(). local gradParam = module[gradParamName] local diagHessian = gradParam.new():resize(gradParam:nElement()):zero() module:forward(input) local gradOutput = module.output.new():resizeAs(module.output) local gradOutput1D = gradOutput:view(gradOutput:nElement()) for i=1,gradOutput:nElement() do gradOutput1D:zero() gradOutput1D[i] = 1 module.gradWeight:zero() module.gradBias:zero() module:updateGradInput(input, gradOutput) module:accGradParameters(input, gradOutput) diagHessian:addcmul(gradParam, gradParam) end return diagHessian end function nn.Jacobian.forwardUpdate(module, input, param, perturbation) -- perturbation amount perturbation = perturbation or 1e-6 -- 1D view of input --local tst = param:storage() local sin = param.new(param):resize(param:nElement())--param.new(tst,1,tst:size()) -- jacobian matrix to calculate local jacobian = torch.Tensor():resize(param:nElement(),module:forward(input):nElement()) local outa = torch.Tensor(jacobian:size(2)) local outb = torch.Tensor(jacobian:size(2)) for i=1,sin:nElement() do local orig = sin[i] sin[i] = orig - perturbation outa:copy(module:forward(input)) sin[i] = orig + perturbation outb:copy(module:forward(input)) sin[i] = orig outb:add(-1,outa):div(2*perturbation) jacobian:select(1,i):copy(outb) jacobian:select(1,i):mul(-1) jacobian:select(1,i):add(sin[i]) end return jacobian end function nn.Jacobian.testJacobian(module, input, minval, maxval, perturbation) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:copy(torch.rand(input:nElement()):mul(inrange):add(minval)) local jac_fprop = nn.Jacobian.forward(module, input, input, perturbation) local jac_bprop = nn.Jacobian.backward(module, input) local error = jac_fprop-jac_bprop return error:abs():max() end function nn.Jacobian.testJacobianParameters(module, input, param, dparam, minval, maxval, perturbation) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:copy(torch.rand(input:nElement()):mul(inrange):add(minval)) param:copy(torch.rand(param:nElement()):mul(inrange):add(minval)) local jac_bprop = nn.Jacobian.backward(module, input, param, dparam) local jac_fprop = nn.Jacobian.forward(module, input, param, perturbation) local error = jac_fprop - jac_bprop return error:abs():max() end function nn.Jacobian.testJacobianUpdateParameters(module, input, param, minval, maxval, perturbation) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:copy(torch.rand(input:nElement()):mul(inrange):add(minval)) param:copy(torch.rand(param:nElement()):mul(inrange):add(minval)) local params_bprop = nn.Jacobian.backwardUpdate(module, input, param) local params_fprop = nn.Jacobian.forwardUpdate(module, input, param, perturbation) local error = params_fprop - params_bprop return error:abs():max() end function nn.Jacobian.testDiagHessian(module, input, gradParamName, diagHessianParamName, minval, maxval) -- Compute the diagonal Hessian elements for the same function in two different ways, -- then compare the results and return the difference. minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:copy(torch.rand(input:nElement()):mul(inrange):add(minval)) module:initDiagHessianParameters() local h_bprop = nn.Jacobian.backwardDiagHessian(module, input, diagHessianParamName) local h_linearmodule = nn.Jacobian.linearModuleDiagHessian(module, input, gradParamName) local error = h_bprop - h_linearmodule return error:abs():max() end function nn.Jacobian.testDiagHessianInput(module, input, minval, maxval) return nn.Jacobian.testDiagHessian(module, input, 'gradInput', 'diagHessianInput', minval, maxval) end function nn.Jacobian.testDiagHessianWeight(module, input, minval, maxval) return nn.Jacobian.testDiagHessian(module, input, 'gradWeight', 'diagHessianWeight', minval, maxval) end function nn.Jacobian.testDiagHessianBias(module, input, minval, maxval) return nn.Jacobian.testDiagHessian(module, input, 'gradBias', 'diagHessianBias', minval, maxval) end function nn.Jacobian.testIO(module,input, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval -- run module module:forward(input) local go = module.output:clone():copy(torch.rand(module.output:nElement()):mul(inrange):add(minval)) module:zeroGradParameters() module:updateGradInput(input,go) module:accGradParameters(input,go) local fo = module.output:clone() local bo = module.gradInput:clone() -- write module local filename = os.tmpname() local f = torch.DiskFile(filename, 'w'):binary() f:writeObject(module) f:close() -- read module local m = torch.DiskFile(filename):binary():readObject() m:forward(input) m:zeroGradParameters() m:updateGradInput(input,go) m:accGradParameters(input,go) -- cleanup os.remove(filename) local fo2 = m.output:clone() local bo2 = m.gradInput:clone() local errf = fo - fo2 local errb = bo - bo2 return errf:abs():max(), errb:abs():max() end function nn.Jacobian.testAllUpdate(module, input, weight, gradWeight) local gradOutput local lr = torch.uniform(0.1, 1) local errors = {} -- accGradParameters local maccgp = module:clone() local weightc = maccgp[weight]:clone() maccgp:forward(input) gradOutput = torch.rand(maccgp.output:size()) maccgp:zeroGradParameters() maccgp:updateGradInput(input, gradOutput) maccgp:accGradParameters(input, gradOutput) maccgp:updateParameters(lr) errors["accGradParameters"] = (weightc-maccgp[gradWeight]*lr-maccgp[weight]):norm() -- accUpdateGradParameters local maccugp = module:clone() maccugp:forward(input) maccugp:updateGradInput(input, gradOutput) maccugp:accUpdateGradParameters(input, gradOutput, lr) errors["accUpdateGradParameters"] = (maccugp[weight]-maccgp[weight]):norm() -- shared, accGradParameters local macsh1 = module:clone() local macsh2 = module:clone() macsh2:share(macsh1, weight) macsh1:forward(input) macsh2:forward(input) macsh1:zeroGradParameters() macsh2:zeroGradParameters() macsh1:updateGradInput(input, gradOutput) macsh2:updateGradInput(input, gradOutput) macsh1:accGradParameters(input, gradOutput) macsh2:accGradParameters(input, gradOutput) macsh1:updateParameters(lr) macsh2:updateParameters(lr) local err = (weightc-maccgp[gradWeight]*(lr*2)-macsh1[weight]):norm() err = err + (weightc-maccgp[gradWeight]*(lr*2)-macsh2[weight]):norm() errors["accGradParameters [shared]"] = err -- shared, accUpdateGradParameters local macshu1 = module:clone() local macshu2 = module:clone() macshu2:share(macshu1, weight) macshu1:forward(input) macshu2:forward(input) macshu1:updateGradInput(input, gradOutput) macshu2:updateGradInput(input, gradOutput) macshu1:accUpdateGradParameters(input, gradOutput, lr) macshu2:accUpdateGradParameters(input, gradOutput, lr) err = (weightc-maccgp[gradWeight]*(lr*2)-macshu1[weight]):norm() err = err + (weightc-maccgp[gradWeight]*(lr*2)-macshu2[weight]):norm() errors["accUpdateGradParameters [shared]"] = err return errors end
bsd-3-clause
tryroach/vlc
share/lua/playlist/koreus.lua
57
4037
--[[ Copyright © 2009 the VideoLAN team 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() if vlc.access ~= "http" and vlc.access ~= "https" then return false end koreus_site = string.match( vlc.path, "koreus" ) if not koreus_site then return false end return ( string.match( vlc.path, "video" ) ) -- http://www.koreus.com/video/pouet.html end -- Parse function. function parse() while true do line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then _,_,name = string.find( line, "content=\"(.-)\"" ) name = vlc.strings.resolve_xml_special_chars( name ) end if string.match( line, "<meta property=\"og:description\"" ) then _,_,description = string.find( line, "content=\"(.-)\"" ) if (description ~= nil) then description = vlc.strings.resolve_xml_special_chars( description ) end end if string.match( line, "<span id=\"spoil\" style=\"display:none\">" ) then _,_,desc_spoil = string.find( line, "<span id=\"spoil\" style=\"display:none\">(.-)</span>" ) desc_spoil = vlc.strings.resolve_xml_special_chars( desc_spoil ) description = description .. "\n\r" .. desc_spoil end if string.match( line, "<meta name=\"author\"" ) then _,_,artist = string.find( line, "content=\"(.-)\"" ) artist = vlc.strings.resolve_xml_special_chars( artist ) end if string.match( line, "link rel=\"image_src\"" ) then _,_,arturl = string.find( line, "href=\"(.-)\"" ) end vid_url = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.mp4)' ) if vid_url then path_url = vid_url end vid_url_hd = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%-hd%.mp4)' ) if vid_url_hd then path_url_hd = vid_url_hd end vid_url_webm = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.webm)' ) if vid_url_webm then path_url_webm = vid_url_webm end vid_url_flv = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.flv)' ) if vid_ulr_flv then path_url_flv = vid_url_flv end end if path_url_hd then if vlc.access == 'https' then path_url_hd = path_url_hd:gsub('http','https') end return { { path = path_url_hd; name = name; description = description; artist = artist; arturl = arturl } } elseif path_url then if vlc.access == 'https' then path_url = path_url:gsub('http','https') end return { { path = path_url; name = name; description = description; artist = artist; arturl = arturl } } elseif path_url_webm then if vlc.access == 'https' then path_url_webm = path_url_webm:gsub('http','https') end return { { path = path_url_webm; name = name; description = description; artist = artist; arturl = arturl } } elseif path_url_flv then if vlc.access == 'https' then path_url_flv = path_url_flv:gsub('http','https') end return { { path = path_url_flv; name = name; description = description; artist = artist; arturl = arturl } } else return {} end end
gpl-2.0
rotmanmi/nn
SpatialAveragePooling.lua
37
1063
local SpatialAveragePooling, parent = torch.class('nn.SpatialAveragePooling', 'nn.Module') function SpatialAveragePooling:__init(kW, kH, dW, dH) parent.__init(self) self.kW = kW self.kH = kH self.dW = dW or 1 self.dH = dH or 1 self.divide = true end function SpatialAveragePooling:updateOutput(input) input.nn.SpatialAveragePooling_updateOutput(self, input) -- for backward compatibility with saved models -- which are not supposed to have "divide" field if not self.divide then self.output:mul(self.kW*self.kH) end return self.output end function SpatialAveragePooling:updateGradInput(input, gradOutput) if self.gradInput then input.nn.SpatialAveragePooling_updateGradInput(self, input, gradOutput) -- for backward compatibility if not self.divide then self.gradInput:mul(self.kW*self.kH) end return self.gradInput end end function SpatialAveragePooling:__tostring__() return string.format('%s(%d,%d,%d,%d)', torch.type(self), self.kW, self.kH, self.dW, self.dH) end
bsd-3-clause
Mike325/.vim
lua/tests/tables.lua
1
7912
local random_string = require('tests.utils').random_string local random_generator = require('tests.utils').random_generator local random_list = require('tests.utils').random_list local random_map = require('tests.utils').random_map local check_clear_lst = require('tests.utils').check_clear_lst describe('has_attrs', function() local has_attrs = require('utils.tables').has_attrs it('Check attribute in list', function() for _ = 1, 10 do local lst = random_list(math.random(5, 20)) local node = math.random(1, #lst) assert.is_true(has_attrs(lst, lst[node])) node = random_string(math.random(2, 10)) assert.is_false(has_attrs(lst, node)) -- note: this may hit one node and generate a false negative node = random_generator() assert.is_false(has_attrs(lst, node)) end end) it('Check attribute in table', function() for _ = 1, 10 do local tbl = random_map(math.random(5, 20)) local keys = vim.tbl_keys(tbl) local idx = math.random(1, #keys) assert.is_true(has_attrs(tbl, tbl[keys[idx]])) local node = random_string(math.random(2, 10)) assert.is_false(has_attrs(tbl, node)) -- note: this may hit one node and generate a false negative node = random_generator() assert.is_false(has_attrs(tbl, node)) end end) it('Check list in list', function() for _ = 1, 10 do local lst = random_list(math.random(5, 20)) local beg_idx = math.random(1, math.floor(#lst / 2)) local end_idx = math.random(math.floor(#lst / 2), #lst) local tmp_lst = vim.list_slice(lst, beg_idx, end_idx) assert.is_true(has_attrs(lst, tmp_lst)) table.insert(tmp_lst, random_generator()) assert.is_false(has_attrs(lst, tmp_lst)) beg_idx = math.random(1, math.floor(#lst / 2)) end_idx = math.random(math.floor(#lst / 2), #lst) tmp_lst = vim.list_slice(lst, beg_idx, end_idx) table.insert(tmp_lst, random_generator()) assert.is_false(has_attrs(lst, tmp_lst)) end end) it('Check list in table', function() for _ = 1, 10 do local tbl = random_map(math.random(5, 20)) local keys = vim.tbl_keys(tbl) local beg_idx = math.random(1, math.floor(#keys / 2)) local end_idx = math.random(math.floor(#keys / 2), #keys) local keys_vals = vim.list_slice(keys, beg_idx, end_idx) local tbl_in_tbl = {} for _, key in ipairs(keys_vals) do table.insert(tbl_in_tbl, tbl[key]) end assert.is_true(has_attrs(tbl, tbl_in_tbl)) table.insert(tbl_in_tbl, random_generator()) assert.is_false(has_attrs(tbl, tbl_in_tbl)) end end) end) describe('merge_uniq_list', function() local merge_uniq_list = require('utils.tables').merge_uniq_list local function check_lists(src, dest, merge) for _, src_node in ipairs(src) do local has_node = false for _, merge_node in ipairs(merge) do if src_node == merge_node then has_node = true break end end assert.is_true(has_node) end for _, dest_node in ipairs(dest) do local has_node = false for _, merge_node in ipairs(merge) do if dest_node == merge_node then has_node = true break end end assert.is_true(has_node) end end it('random lists', function() for _ = 1, 10 do local lst_src = random_list(math.random(1, 10)) local lst_dest = random_list(math.random(5, 20)) local merged_lst = merge_uniq_list(vim.deepcopy(lst_dest), lst_src) check_lists(lst_src, lst_dest, merged_lst) assert.equals(#merged_lst, (#lst_src + #lst_dest)) end end) it('overlap lists', function() for _ = 1, 10 do local lst_src = random_list(math.random(1, 10)) local lst_dest = random_list(math.random(5, 20)) local end_idx = math.random(2, #lst_src) vim.list_extend(lst_dest, lst_src, 1, end_idx) local merged_lst = merge_uniq_list(vim.deepcopy(lst_dest), lst_src) check_lists(lst_src, lst_dest, merged_lst) assert.equals(#merged_lst, (#lst_src + #lst_dest - end_idx)) end end) end) describe('clear_lst', function() local clear_lst = require('utils.tables').clear_lst it('Trim values', function() for _ = 1, 10 do local lst = random_list(math.random(1, 20), function(n) if type(n) == type '' then return n .. string.rep(' ', math.random(1, 5)) end return n end) check_clear_lst(clear_lst(lst)) end end) it('Remove empty strings', function() for _ = 1, 10 do local lst = random_list(math.random(1, 20), function(n) if type(n) == type '' then if math.random(1, 10) % 2 == 0 then return string.rep(' ', math.random(1, 5)) end end return n end) check_clear_lst(clear_lst(lst)) end end) end) describe('str_to_clean_tbl', function() local str_to_clean_tbl = require('utils.tables').str_to_clean_tbl local strings = { { 't,1,2,r5,6', ',' }, { 't,,,,,,,,,,5', ',' }, { 't q 4 1' }, { 't\t w\t\tyas\t \t\taas fa' }, { ' ' }, } it('Sample strings', function() for _, v in ipairs(strings) do local lst = str_to_clean_tbl(v[1], v[2]) assert.is_true(vim.tbl_islist(lst)) check_clear_lst(lst) end end) it('Random Strings', function() for _ = 1, 10 do local str = random_string(150) local sep = math.random(0, 10) % 2 == 0 and random_string(1) or ' ' local lst = str_to_clean_tbl(str, sep) assert.is_true(vim.tbl_islist(lst)) check_clear_lst(lst) end end) end) describe('shallowcopy', function() local shallowcopy = require('utils.tables').shallowcopy it('simple array', function() for _ = 1, 10 do local lst = random_list(math.random(1, 20)) local copied = shallowcopy(lst) assert.are.same(lst, copied) end end) it('simple table', function() for _ = 1, 10 do local tbl = random_map(math.random(1, 20)) local copied = shallowcopy(tbl) assert.are.same(tbl, copied) end end) it('nested array', function() for _ = 1, 10 do local nested = random_list(math.random(1, 20)) for _ = 1, 10 do table.insert(nested, random_list(math.random(1, 20))) end local copied = shallowcopy(nested) for idx, _ in ipairs(nested) do assert.equals(nested[idx], copied[idx]) end end end) end) describe('isempty', function() local isempty = require('utils.tables').isempty it('table', function() assert.is_true(isempty {}) assert.is_false(isempty { 1 }) assert.is_false(isempty { test = 1 }) assert.is_false(isempty { 1, 2, 3, test = 1 }) assert.is_false(isempty(random_list(3))) assert.is_false(isempty(random_map(3))) end) end)
mit
MalRD/darkstar
scripts/zones/West_Sarutabaruta/IDs.lua
8
5375
----------------------------------- -- Area: West_Sarutabaruta ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.WEST_SARUTABARUTA] = { text = { NOTHING_HAPPENS = 119, -- Nothing happens... ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6388, -- Obtained: <item>. GIL_OBTAINED = 6389, -- Obtained <number> gil. KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>. KEYITEM_LOST = 6392, -- Lost key item: <keyitem>. NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here. FISHING_MESSAGE_OFFSET = 7049, -- You can't fish here. DIG_THROW_AWAY = 7062, -- You dig up <item>, but your inventory is full. You regretfully throw the <item> away. FIND_NOTHING = 7064, -- You dig and you dig, but find nothing. CONQUEST_BASE = 7149, -- Tallying conquest results... SIGN_1 = 7378, -- Northeast: Central Tower, Horutoto Ruins Northwest: Giddeus South: Port Windurst SIGN_3 = 7379, -- East: East Sarutabaruta West: Giddeus SIGN_5 = 7380, -- Northeast: Central Tower, Horutoto Ruins East: East Sarutabaruta West: Giddeus SIGN_7 = 7381, -- South: Windurst East: East Sarutabaruta SIGN_9 = 7382, -- West: Giddeus North: East Sarutabaruta South: Windurst SIGN_11 = 7383, -- North: East Sarutabaruta Southeast: Windurst SIGN_13 = 7384, -- East: Port Windurst West: West Tower, Horutoto Ruins SIGN_15 = 7385, -- East: East Sarutabaruta West: Giddeus Southeast: Windurst SIGN_17 = 7386, -- Northwest: Northwest Tower, Horutoto Ruins East: Outpost Southwest: Giddeus PAORE_KUORE_DIALOG = 7388, -- Welcome to Windurst! Proceed through this gateway to entaru Port Windurst. KOLAPO_OILAPO_DIALOG = 7389, -- Hi-diddly-diddly! This is the gateway to Windurst! The grasslands you're on now are known as West Sarutabaruta. MAATA_ULAATA = 7390, -- Hello-wello! This is the central tower of the Horutoto Ruins. It's one of the several ancient-wancient magic towers which dot these grasslands. IPUPU_DIALOG = 7393, -- I decided to take a little strolly-wolly, but before I realized it, I found myself way out here! Now I am sorta stuck... Woe is me! FROST_DEPOSIT_TWINKLES = 7400, -- A frost deposit at the base of the tree twinkles in the starlight. MELT_BARE_HANDS = 7402, -- It looks like it would melt if you touched it with your bare hands... HARVESTING_IS_POSSIBLE_HERE = 7438, -- Harvesting is possible here if you have <item>. CONQUEST = 7454, -- You've earned conquest points! PLAYER_OBTAINS_ITEM = 7855, -- <name> obtains <item>! UNABLE_TO_OBTAIN_ITEM = 7856, -- You were unable to obtain the item. PLAYER_OBTAINS_TEMP_ITEM = 7857, -- <name> obtains the temporary item: <item>! ALREADY_POSSESS_TEMP = 7858, -- You already possess that temporary item. NO_COMBINATION = 7863, -- You were unable to enter a combination. REGIME_REGISTERED = 10183, -- New training regime registered! DONT_SWAP_JOBS = 10184, -- hanging your job will result in the cancellation of your current training regime. REGIME_CANCELED = 10185, -- Training regime canceled. COMMON_SENSE_SURVIVAL = 12334, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world. }, mob = { NUNYENUNC_PH = { [17248323] = 17248517, -- -95.00 -17.000 383.000 [17248515] = 17248517, -- -7.194 -17.288 431.604 [17248516] = 17248517, -- 53.159 -24.540 554.652 [17248514] = 17248517, -- 159.501 -20.117 485.528 }, TOM_TIT_TAT_PH = { [17248467] = 17248468, -- 31.149 -20.045 358.265 [17248466] = 17248468, -- 77.509 -20.719 434.757 [17248507] = 17248468, -- 139.154 -21.418 505.416 [17248506] = 17248468, -- 151.484 -21.133 494.038 [17248543] = 17248468, -- 211.910 -19.944 546.316 [17248546] = 17248468, -- 211.099 -20.673 568.574 [17248544] = 17248468, -- 239.421 -19.659 583.122 [17248545] = 17248468, -- 274.296 -20.357 587.339 }, }, npc = { CASKET_BASE = 17248798, SIGNPOST_OFFSET = 17248825, OVERSEER_BASE = 17248858, HARVESTING = { 17248874, 17248875, 17248876, 17248877, 17248878, 17248879, }, }, } return zones[dsp.zone.WEST_SARUTABARUTA]
gpl-3.0
gallenmu/MoonGen
libmoon/examples/webserver.lua
4
2623
local lm = require "libmoon" local device = require "device" local stats = require "stats" local log = require "log" local memory = require "memory" local server = require "webserver" function configure(parser) parser:description[[ REST API demo, check out these endpoints: * curl localhost/devices/<id> * curl localhost/counters/2 * curl localhost/hello * curl localhost/hello/libmoon * curl -X POST localhost/hello --data-ascii '{"foo": 42, "hello": "world"}' ]] parser:argument("dev", "Device to use, generates some dummy traffic to showcase the statistics API."):convert(tonumber) parser:option("-p --port", "Start the REST API on the given port."):args(1):default(8080):convert(tonumber) parser:option("-b --bind", "Bind to a specific IP.") parser:option("-o --output", "File to output statistics to") return parser:parse() end -- this function is executed in the context of the webserver thread -- you have to define the handlers that you are using *in this thread*, otherwise they won't work function initWebserver(turbo, defaultResponse) log:info("Running webserver initializer, received argument: %s", defaultResponse) -- See turbo documentation for more: https://github.com/kernelsauce/turbo local helloWorld = class("helloWorld", turbo.web.RequestHandler) function helloWorld:get(pathArg) if pathArg == "" then pathArg = defaultResponse end self:write({hello = pathArg}) end function helloWorld:post(...) local json = self:get_json(true) if not json then error(turbo.web.HTTPError(400, {message = "Expected JSON data in POST body."})) end self:write(json) end -- return an turbo handler list return { {"^/hello/?([^/]*)$", helloWorld}, } end function master(args,...) server.startWebserverTask({ port = args.port, bind = args.bind, -- a function that defines additional handlers, it's run as it would with lm.startTask() -- this means it needs to be passed by name -- any extra arguments passed to startWebserverTasks will be passed on to this function with the usual serialization init = "initWebserver" }, "Hello, world") if args.dev then local dev = device.config{port = args.dev} device.waitForLinks() stats.startStatsTask{devices = {dev}, file = args.output} lm.startTask("txTask", dev:getTxQueue(0)) end lm.waitForTasks() end function txTask(queue) local mempool = memory.createMemPool(function(buf) -- just some random packets buf:getUdpPacket():fill{ pktLength = 60 } end) local bufs = mempool:bufArray() while lm.running() do bufs:alloc(60) bufs:offloadUdpChecksums() queue:send(bufs) end end
mit
MalRD/darkstar
scripts/globals/mobskills/happobarai.lua
11
1037
--------------------------------------------- -- Happobarai -- -- Description: Damages enemies in an area of effect. Additional effect: Stun -- Type: Physical -- Utsusemi/Blink absorb: 2-3 shadows -- Range: 10' radial -- Notes: --------------------------------------------- require("scripts/globals/monstertpmoves") require("scripts/globals/settings") require("scripts/globals/status") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local numhits = 1 local accmod = 1 local dmgmod = 2.2 local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,MOBPARAM_3_SHADOW) local typeEffect = dsp.effect.STUN MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4) target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING) return dmg end
gpl-3.0
ashkanpj/yagoopfire
plugins/media.lua
297
1590
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
Distrotech/vlc
share/lua/modules/dkjson.lua
95
25741
--[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.1* This module writes no global values, not even the module table. Import it using json = require ("dkjson") Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This is mainly useful for tables that can be empty. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.1"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the functions `quotestring` and `decode`. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable this option: --]==] local always_try_using_lpeg = true --[==[ In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. You can contact the author by sending an e-mail to 'kolf' at the e-mail provider 'gmx.de'. --------------------------------------------------------------------- *Copyright (C) 2010, 2011 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall = error, require, pcall local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local concat = table.concat local common = require ("common") local us_tostring = common.us_tostring if _VERSION == 'Lua 5.1' then local function noglobals (s,k,v) error ("global access: " .. k, 2) end setfenv (1, setmetatable ({}, { __index = noglobals, __newindex = noglobals })) end local _ENV = nil -- blocking globals in Lua 5.2 local json = { version = "dkjson 2.1" } pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = us_tostring (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local metatype = valmeta and valmeta.__jsontype local isa, n if metatype == 'array' then isa = true n = value.n or #value elseif metatype == 'object' then isa = false else isa, n = isarray (value) end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 1 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = tonumber (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end function json.decode (str, pos, nullval, objectmeta, arraymeta) objectmeta = objectmeta or {__jsontype = 'object'} arraymeta = arraymeta or {__jsontype = 'array'} return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") local pegmatch = g.match local P, S, R, V = g.P, g.S, g.R, g.V local SpecialChars = (R"\0\31" + S"\"\\\127" + P"\194" * (R"\128\159" + P"\173") + P"\216" * R"\128\132" + P"\220\132" + P"\225\158" * S"\180\181" + P"\226\128" * (R"\140\143" + S"\168\175") + P"\226\129" * R"\160\175" + P"\239\187\191" + P"\229\191" + R"\176\191") / escapeutf8 local QuoteStr = g.Cs (g.Cc "\"" * (SpecialChars + 1)^0 * g.Cc "\"") quotestring = function (str) return pegmatch (QuoteStr, str) end json.quotestring = quotestring local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/tonumber local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, objectmeta, arraymeta) local state = { objectmeta = objectmeta or {__jsontype = 'object'}, arraymeta = arraymeta or {__jsontype = 'array'} } local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
Lsty/ygopro-scripts
c58268433.lua
3
1173
--ブレードラビット function c58268433.initial_effect(c) --flip local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(58268433,0)) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e1:SetCode(EVENT_CHANGE_POS) e1:SetCondition(c58268433.condition) e1:SetTarget(c58268433.target) e1:SetOperation(c58268433.operation) c:RegisterEffect(e1) end function c58268433.condition(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return bit.band(c:GetPreviousPosition(),POS_ATTACK)~=0 and c:IsFaceup() and c:IsDefencePos() end function c58268433.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and chkc:IsDestructable() end if chk==0 then return true end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,Card.IsDestructable,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) end function c58268433.operation(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
gpl-2.0