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 |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
- Downloads last month
- 14