repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
UnfortunateFruit/darkstar
scripts/zones/Upper_Jeuno/npcs/Guslam.lua
19
6497
----------------------------------- -- Area: Upper Jeuno -- NPC: Guslam -- Starts Quest: Borghertz's Hands (AF Hands, Many job) -- @zone 244 -- @pos -5 1 48 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- If it's the first Hands quest ----------------------------------- function nbHandsQuestsCompleted(player) questNotAvailable = 0; for nb = 1, 15, 1 do if(player:getQuestStatus(JEUNO,43 + nb) ~= QUEST_AVAILABLE) then questNotAvailable = questNotAvailable + 1; end end return questNotAvailable; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getMainLvl() >= 50 and player:getVar("BorghertzAlreadyActiveWithJob") == 0) then if(player:getMainJob() == 1 and player:getQuestStatus(BASTOK,THE_TALEKEEPER_S_TRUTH) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_WARRING_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for WAR elseif(player:getMainJob() == 2 and player:getQuestStatus(BASTOK,THE_FIRST_MEETING) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_STRIKING_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for MNK elseif(player:getMainJob() == 3 and player:getQuestStatus(SANDORIA,PRELUDE_OF_BLACK_AND_WHITE) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_HEALING_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for WHM elseif(player:getMainJob() == 4 and player:getQuestStatus(WINDURST,RECOLLECTIONS) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_SORCEROUS_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for BLM elseif(player:getMainJob() == 5 and player:getQuestStatus(SANDORIA,ENVELOPED_IN_DARKNESS) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_VERMILLION_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for RDM elseif(player:getMainJob() == 6 and player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_SNEAKY_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for THF elseif(player:getMainJob() == 7 and player:getQuestStatus(SANDORIA,A_BOY_S_DREAM) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_STALWART_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for PLD elseif(player:getMainJob() == 8 and player:getQuestStatus(BASTOK,DARK_PUPPET) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_SHADOWY_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for DRK elseif(player:getMainJob() == 9 and player:getQuestStatus(JEUNO,SCATTERED_INTO_SHADOW) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_WILD_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for BST elseif(player:getMainJob() == 10 and player:getQuestStatus(JEUNO,THE_REQUIEM) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_HARMONIOUS_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for BRD elseif(player:getMainJob() == 11 and player:getQuestStatus(WINDURST,FIRE_AND_BRIMSTONE) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_CHASING_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for RNG elseif(player:getMainJob() == 12 and player:getQuestStatus(OUTLANDS,YOMI_OKURI) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_LOYAL_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for SAM elseif(player:getMainJob() == 13 and player:getQuestStatus(OUTLANDS,I_LL_TAKE_THE_BIG_BOX) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_LURKING_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for NIN elseif(player:getMainJob() == 14 and player:getQuestStatus(SANDORIA,CHASING_QUOTAS) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_DRAGON_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for DRG elseif(player:getMainJob() == 15 and player:getQuestStatus(WINDURST,CLASS_REUNION) ~= QUEST_AVAILABLE and player:getQuestStatus(JEUNO,BORGHERTZ_S_CALLING_HANDS) == QUEST_AVAILABLE) then player:startEvent(0x009b); -- Start Quest for SMN else player:startEvent(0x009a); -- Standard dialog end elseif(player:getVar("BorghertzAlreadyActiveWithJob") >= 1 and player:hasKeyItem(OLD_GAUNTLETS) == false) then player:startEvent(0x002b); -- During Quest before KI obtained elseif(player:hasKeyItem(OLD_GAUNTLETS) == true) then player:startEvent(0x001a); -- Dialog with Old Gauntlets KI if(nbHandsQuestsCompleted(player) == 1) then player:setVar("BorghertzHandsFirstTime",1); else player:setVar("BorghertzCS",1); end else player:startEvent(0x009a); -- Standard dialog end end; -- 0x009a Standard dialog -- 0x009b Start Quest -- 0x002b During Quest before KI obtained -- 0x001a Dialog avec Old Gauntlets KI -- 0x009c During Quest after Old Gauntlets KI ? ----------------------------------- -- 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 == 0x009b) then NumQuest = 43 + player:getMainJob(); player:addQuest(JEUNO,NumQuest); player:setVar("BorghertzAlreadyActiveWithJob",player:getMainJob()); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/weaponskills/sidewinder.lua
30
1400
----------------------------------- -- Sidewinder -- Archery weapon skill -- Skill level: 175 -- Delivers an inparams.accurate attack that deals quintuple damage. params.accuracy varies with TP. -- Aligned with the Aqua Gorget, Light Gorget & Breeze Gorget. -- Aligned with the Aqua Belt, Light Belt & Breeze Belt. -- Element: None -- Modifiers: STR:20% ; AGI:50% -- 100%TP 200%TP 300%TP -- 5.00 5.00 5.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 5; params.ftp200 = 5; params.ftp300 = 5; params.str_wsc = 0.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.2; params.agi_wsc = 0.5; end local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
johnmccabe/dockercraft
world/Plugins/APIDump/Hooks/OnDisconnect.lua
36
1597
return { HOOK_DISCONNECT = { CalledWhen = [[ A client has disconnected, either by explicitly sending the disconnect packet (in older protocols) or their connection was terminated ]], DefaultFnName = "OnDisconnect", -- also used as pagename Desc = [[ This hook is called when a client has disconnected from the server, for whatever reason. It is also called when the client sends the Disconnect packet (only in pre-1.7 protocols). This hook is not called for server ping connections.</p> <p> Note that the hook is called even for connections to players who failed to auth. In such a case there's no {{cPlayer}} object associated with the client.</p> <p> See also the {{OnHandshake|HOOK_HANDSHAKE}} hook which is called when the client connects (and presents a handshake message, so that they are not just status-pinging). If you need to store a per-player object, use the {{OnPlayerJoined|HOOK_PLAYER_JOINED}} and {{OnPlayerDestroyed|HOOK_PLAYER_DESTROYED}} hooks instead, those are guaranteed to have the {{cPlayer}} object associated. ]], Params = { { Name = "Client", Type = "{{cClientHandle}}", Notes = "The client who has disconnected" }, { Name = "Reason", Type = "string", Notes = "The reason that the client has sent in the disconnect packet" }, }, Returns = [[ If the function returns false or no value, Cuberite calls other plugins' callbacks for this event. If the function returns true, no other plugins are called for this event. In either case, the client is disconnected. ]], }, -- HOOK_DISCONNECT }
apache-2.0
nesstea/darkstar
scripts/zones/Cloister_of_Tides/Zone.lua
30
1736
----------------------------------- -- -- 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
nesstea/darkstar
scripts/globals/items/slice_of_tavnazian_ram_meat.lua
18
1332
----------------------------------------- -- ID: 5208 -- Item: slice_of_tavnazian_ram_meat -- Food Effect: 5Min, Galka only ----------------------------------------- -- Strength 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 8) then result = 247; end if (target:getMod(MOD_EAT_RAW_MEAT) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5208); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Palborough_Mines/npcs/_3z7.lua
26
1103
----------------------------------- -- Elevator in Palborough -- Notes: Used to operate Elevator @3z0 ----------------------------------- package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Palborough_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RunElevator(ELEVATOR_PALBOROUGH_MINES_LIFT); 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/MagicCarpet/plugin.lua
6
1795
local Carpets = {} local PLUGIN function Initialize( Plugin ) Plugin:SetName("MagicCarpet") Plugin:SetVersion(3) cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_MOVING, OnPlayerMoving) cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_DESTROYED, OnPlayerDestroyed) local PluginManager = cPluginManager:Get() PluginManager:BindCommand("/mc", "magiccarpet", HandleCarpetCommand, " - Spawns a magical carpet"); PLUGIN = Plugin LOG( "Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion() ) return true end function OnDisable() LOG( PLUGIN:GetName() .. " v." .. PLUGIN:GetVersion() .. " is shutting down..." ) for i, Carpet in pairs( Carpets ) do Carpet:remove() end end function HandleCarpetCommand(Split, Player) Carpet = Carpets[ Player:GetUUID() ] if( Carpet == nil ) then Carpets[ Player:GetUUID() ] = cCarpet:new() Player:SendMessageSuccess("You're on a magic carpet!") Player:SendMessageInfo("Look straight down to descend. Jump to ascend.") else Carpet:remove() Carpets[ Player:GetUUID() ] = nil Player:SendMessageSuccess("The carpet vanished!") end return true end function OnPlayerDestroyed(a_Player) local Carpet = Carpets[a_Player:GetUUID()] if (Carpet) then Carpet:remove() end Carpets[a_Player:GetUUID()] = nil end function OnPlayerMoving(Player) local Carpet = Carpets[ Player:GetUUID() ] if( Carpet == nil ) then return end if( Player:GetPitch() == 90 ) then Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY() - 1, Player:GetPosZ() ) ) else if( Player:GetPosY() < Carpet:getY() ) then Player:TeleportToCoords(Player:GetPosX(), Carpet:getY() + 0.2, Player:GetPosZ()) end Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY(), Player:GetPosZ() ) ) end end
apache-2.0
nesstea/darkstar
scripts/globals/spells/bluemagic/blood_saber.lua
21
1690
----------------------------------------- -- Spell: Blood Saber -- Steals HP from enemies within range. Ineffective against undead -- Spell cost: 25 MP -- Monster Type: Undead -- Spell Type: Magical (Dark) -- Blue Magic Points: 2 -- Stat Bonus: HP-5, MP+5 -- Level: 48 -- Casting Time: 4 seconds -- Recast Time: 90 seconds -- Magic Bursts on: Compression, Gravitation, Darkness -- Combos: None ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local dmg = 1 + (0.709 * (caster:getSkillLevel(BLUE_SKILL)) + caster:getMod(1 + BLUE_SKILL)); local resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),BLUE_SKILL,1.0); dmg = dmg*resist; dmg = addBonuses(caster,spell,target,dmg); dmg = adjustForTarget(target,dmg,spell:getElement()); if (dmg > (caster:getSkillLevel(BLUE_SKILL) + 20)) then dmg = (caster:getSkillLevel(BLUE_SKILL) + 20); end if (dmg < 0) then dmg = 0 end if (target:isUndead()) then spell:setMsg(75); return dmg; end if (target:getHP() < dmg) then dmg = target:getHP(); end dmg = BlueFinalAdjustments(caster,target,spell,dmg); caster:addHP(dmg); return dmg; end;
gpl-3.0
FailcoderAddons/supervillain-ui
SVUI_ActionBars/components/totem.lua
2
5886
--[[ ########################################################## 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 ipairs = _G.ipairs; local type = _G.type; local math = _G.math; local cos, deg, rad, sin = math.cos, math.deg, math.rad, math.sin; local hooksecurefunc = _G.hooksecurefunc; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = _G['SVUI'] local L = SV.L; local MOD = SV.ActionBars; --[[ ########################################################## LOCALS ########################################################## ]]-- local PlayerClass = select(2, UnitClass('player')) local TOTEM_PRIORITIES = STANDARD_TOTEM_PRIORITIES; local MOVER_NAME = L["Totem Bar"]; if(PlayerClass == "SHAMAN") then TOTEM_PRIORITIES = SHAMAN_TOTEM_PRIORITIES elseif(PlayerClass == "DEATHKNIGHT") then MOVER_NAME = L["Ghoul Bar"] elseif(PlayerClass == "DRUID") then MOVER_NAME = L["Mushroom Bar"] end --[[ ########################################################## TOTEMS ########################################################## ]]-- local Totems = CreateFrame("Frame", "SVUI_TotemBar", UIParent); function Totems:Refresh() for i = 1, MAX_TOTEMS do local slot = TOTEM_PRIORITIES[i] local haveTotem, name, start, duration, icon = GetTotemInfo(slot) local svuitotem = _G["SVUI_TotemBarTotem"..slot] if(haveTotem) then svuitotem:Show() svuitotem.Icon:SetTexture(icon) CooldownFrame_Set(svuitotem.CD, start, duration, 1) local blizztotem = _G["TotemFrameTotem"..slot] local tslot = blizztotem.slot if(tslot and tslot > 0) then local anchor = _G["SVUI_TotemBarTotem"..tslot] blizztotem:ClearAllPoints() blizztotem:SetAllPoints(anchor) blizztotem:SetFrameStrata(anchor:GetFrameStrata()) blizztotem:SetFrameLevel(anchor:GetFrameLevel() + 99) end else svuitotem:Hide() end end end function Totems:Update() local settings = SV.db.ActionBars.Totem; local totemSize = settings.buttonsize; local totemSpace = settings.buttonspacing; local totemGrowth = settings.showBy; local totemSort = settings.sortDirection; for i = 1, MAX_TOTEMS do local button = self[i] if(button) then local lastButton = self[i - 1] button:SetSize(totemSize, totemSize) button:ClearAllPoints() if(totemGrowth == "HORIZONTAL" and totemSort == "ASCENDING") then if(i == 1) then button:SetPoint("LEFT", self, "LEFT", totemSpace, 0) elseif lastButton then button:SetPoint("LEFT", lastButton, "RIGHT", totemSpace, 0) end elseif(totemGrowth == "VERTICAL" and totemSort == "ASCENDING") then if(i == 1) then button:SetPoint("TOP", self, "TOP", 0, -totemSpace) elseif lastButton then button:SetPoint("TOP", lastButton, "BOTTOM", 0, -totemSpace) end elseif(totemGrowth == "HORIZONTAL" and totemSort == "DESCENDING") then if(i == 1) then button:SetPoint("RIGHT", self, "RIGHT", -totemSpace, 0) elseif lastButton then button:SetPoint("RIGHT", lastButton, "LEFT", -totemSpace, 0) end else if(i == 1) then button:SetPoint("BOTTOM", self, "BOTTOM", 0, totemSpace) elseif lastButton then button:SetPoint("BOTTOM", lastButton, "TOP", 0, totemSpace) end end end end local calcWidth, calcHeight; if(totemGrowth == "HORIZONTAL") then calcWidth = ((totemSize * MAX_TOTEMS) + (totemSpace * MAX_TOTEMS) + totemSpace); calcHeight = (totemSize + (totemSpace * 2)); else calcWidth = (totemSize + (totemSpace * 2)); calcHeight = ((totemSize * MAX_TOTEMS) + (totemSpace * MAX_TOTEMS) + totemSpace); end self:SetSize(calcWidth, calcHeight); self:Refresh() end local Totems_OnEnter = function(self) if(not self:IsVisible()) then return end GameTooltip:SetOwner(self, 'ANCHOR_BOTTOMRIGHT') GameTooltip:SetTotem(self:GetID()) end local Totems_OnLeave = function() GameTooltip:Hide() end local Totems_OnEvent = function(self, event, ...) self:Refresh() end local _hook_TotemFrame_OnUpdate = function() for i=1, MAX_TOTEMS do local slot = TOTEM_PRIORITIES[i] local blizztotem = _G["TotemFrameTotem"..slot] local tslot = blizztotem.slot if(tslot and tslot > 0) then local anchor = _G["SVUI_TotemBarTotem"..tslot] blizztotem:ClearAllPoints() blizztotem:SetAllPoints(anchor) blizztotem:SetFrameStrata(anchor:GetFrameStrata()) blizztotem:SetFrameLevel(anchor:GetFrameLevel() + 99) end end end function MOD:InitializeTotemBar() if(not SV.db.ActionBars.Totem.enable) then return; end local xOffset = SV.db.Dock.dockLeftWidth + 12 Totems:SetPoint("BOTTOMLEFT", SV.Screen, "BOTTOMLEFT", xOffset, 40) for i = 1, MAX_TOTEMS do local slot = TOTEM_PRIORITIES[i] local totem = CreateFrame("Button", "SVUI_TotemBarTotem"..slot, Totems) totem:SetFrameStrata("BACKGROUND") totem:SetID(slot) totem:SetStyle("Frame", "Icon") totem:Hide() totem.Icon = totem:CreateTexture(nil, "ARTWORK") totem.Icon:InsetPoints() totem.Icon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS)) totem.CD = CreateFrame("Cooldown", "SVUI_TotemBarTotem"..slot.."Cooldown", totem, "CooldownFrameTemplate") totem.CD:SetReverse(true) totem.Anchor = CreateFrame("Frame", nil, totem) totem.Anchor:SetAllPoints() Totems[i] = totem end Totems:Show() TotemFrame:Show() TotemFrame.Hide = TotemFrame.Show _G.TotemFrame_AdjustPetFrame = SV.fubar hooksecurefunc("TotemFrame_Update", _hook_TotemFrame_OnUpdate) Totems:RegisterEvent("PLAYER_TOTEM_UPDATE") Totems:RegisterEvent("PLAYER_ENTERING_WORLD") Totems:SetScript("OnEvent", Totems_OnEvent) Totems:Update() SV:NewAnchor(Totems, MOVER_NAME) end
mit
nesstea/darkstar
scripts/zones/Bastok_Markets/npcs/Fatimah.lua
53
2085
----------------------------------- -- Area: Bastok Markets -- NPC: Fatimah -- Type: Goldsmithing Adv. Synthesis Image Support -- @pos -193.849 -7.824 -56.372 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,6); local SkillLevel = player:getSkillLevel(SKILL_GOLDSMITHING); local Cost = getAdvImageSupportCost(player, SKILL_GOLDSMITHING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_GOLDSMITHING_IMAGERY) == false) then player:startEvent(0x012E,Cost,SkillLevel,0,0xB0001AF,player:getGil(),0,0,0); -- Event doesn't work else player:startEvent(0x012E,Cost,SkillLevel,0,0xB0001AF,player:getGil(),28674,0,0); end else player:startEvent(0x012E); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local Cost = getAdvImageSupportCost(player, SKILL_GOLDSMITHING); if (csid == 0x012E and option == 1) then if (player:getGil() >= Cost) then player:messageSpecial(GOLDSMITHING_SUPPORT,0,3,0); player:addStatusEffect(EFFECT_GOLDSMITHING_IMAGERY,3,0,480); player:delGil(Cost); else player:messageSpecial(NOT_HAVE_ENOUGH_GIL); end end end;
gpl-3.0
albfan/clink
clink/test/test_merge.lua
4
2852
-- -- Copyright (c) 2013 Martin Ridgers -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. -- -------------------------------------------------------------------------------- local p local q local r local s -------------------------------------------------------------------------------- q = clink.arg.new_parser():set_arguments({ "sub_p" }) p = clink.arg.new_parser() p:set_flags("-flg_p", "-flg_ps") p:set_arguments( { "sub_p______" .. q, "sub_p_sub_s" .. q, "sub_p_str_s" .. q, "str_p______", "str_p_sub_s", "str_p_str_s", }, { "str_p" } ) r = clink.arg.new_parser():set_arguments({ "sub_s" }) s = clink.arg.new_parser() s:set_flags("-flg_s", "-flg_ps") s:set_arguments( { "______sub_s" .. r, "sub_p_sub_s" .. r, "sub_p_str_s", "______str_s", "str_p_sub_s" .. r, "str_p_str_s", }, { "str_s" } ) clink.arg.register_parser("argcmd_merge", p) clink.arg.register_parser("argcmd_merge", s) local merge_tests = { { "flg_p_flg_s -flg_", { "-flg_p", "-flg_s", "-flg_ps" } }, { "______str_s", "str_s" }, { "______sub_s", "sub_s" }, { "str_p______", "str_p" }, { "sub_p______", "sub_p" }, -- Disabled as merge_parsers is currently too naive to cater for this case. --{ "str_p_str_s", { "str_p", "str_s" } }, --{ "str_p_sub_s", { "str_p", "sub_s" } }, --{ "sub_p_str_s", { "sub_p", "str_s" } }, --{ "sub_p_sub_s", { "sub_p", "sub_s" } }, } for _, i in ipairs(merge_tests) do local test, result = i[1], i[2] local test_name = "Merge: "..test local cmd = "argcmd_merge "..test if type(result) == "string" then clink.test.test_output(test, cmd, cmd.." "..result.." ") else clink.test.test_matches(test, cmd.."\t", result) end end
gpl-3.0
nesstea/darkstar
scripts/globals/spells/bluemagic/ice_break.lua
25
1919
----------------------------------------- -- Spell: Ice Break -- Deals ice damage to enemies within range. Additional Effect: "Bind" -- Spell cost: 142 MP -- Monster Type: Arcana -- Spell Type: Magical (Ice) -- Blue Magic Points: 3 -- Stat Bonus: INT+1 -- Level: 50 -- Casting Time: 5.25 seconds -- Recast Time: 33.75 seconds -- Magic Bursts on: Induration, Distortion, and Darkness -- Combos: Magic Defense Bonus ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0); local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.multiplier = 2.25; params.tMultiplier = 1.0; params.duppercap = 69; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.3; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BlueMagicalSpell(caster, target, spell, params, INT_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if (damage > 0 and resist > 0.0625) then local typeEffect = EFFECT_BIND; target:delStatusEffect(typeEffect); -- Wiki says it can overwrite itself or other binds target:addStatusEffect(typeEffect,1,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
nesstea/darkstar
scripts/zones/Labyrinth_of_Onzozo/mobs/Goblin_Bandit.lua
6
1073
----------------------------------- -- Area: Labyrinth of Onzozo -- MOB: Goblin Bandit -- Note: Place holder Soulstealer Skullnix ----------------------------------- require("scripts/globals/groundsofvalor"); require("scripts/zones/Labyrinth_of_Onzozo/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) checkGoVregime(ally,mob,771,2); checkGoVregime(ally,mob,772,2); checkGoVregime(ally,mob,774,2); local mobID = mob:getID(); if (Soulstealer_Skullnix_PH[mobID] ~= nil) then local ToD = GetServerVariable("[POP]Soulstealer_Skullnix"); if (ToD <= os.time(t) and GetMobAction(Soulstealer_Skullnix) == 0) then if (math.random(1,20) == 5) then UpdateNMSpawnPoint(Soulstealer_Skullnix); GetMobByID(Soulstealer_Skullnix):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Soulstealer_Skullnix", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Lower_Jeuno/npcs/Sutarara.lua
17
1649
----------------------------------- -- Area: Lower Jeuno -- NPC: Sutarara -- Involved in Quests: Tenshodo Menbership (before accepting) -- @pos 30 0.1 -2 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TenshodoMembership = player:getQuestStatus(JEUNO,TENSHODO_MEMBERSHIP); local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,10) == false) then player:startEvent(10055); elseif(TenshodoMembership ~= QUEST_COMPLETED) then player:startEvent(0x00d0); elseif(TenshodoMembership == QUEST_COMPLETED) then player:startEvent(0x00d3); 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 == 10055) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",10,true); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Davoi/npcs/qm1.lua
17
1419
----------------------------------- -- Area: Davoi -- NPC: ??? (qm1) -- Involved in Quest: To Cure a Cough -- @pos -115.830 -0.427 -184.289 149 ----------------------------------- package.loaded["scripts/zones/Davoi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Davoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local toCureaCough = player:getQuestStatus(SANDORIA,TO_CURE_A_COUGH); if(toCureaCough == QUEST_ACCEPTED and player:hasKeyItem(THYME_MOSS) == false) then player:addKeyItem(THYME_MOSS); player:messageSpecial(KEYITEM_OBTAINED,THYME_MOSS); 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
vonflynee/opencomputersserver
world/opencomputers/689b9f29-1d36-4106-bf0e-c06a2ebfb1ef/bin/flash.lua
15
2414
local component = require("component") local shell = require("shell") local fs = require("filesystem") local args, options = shell.parse(...) if #args < 1 and not options.l then io.write("Usage: flash [-qlr] [<bios.lua>] [label]\n") io.write(" q: quiet mode, don't ask questions.\n") io.write(" l: print current contents of installed EEPROM.\n") io.write(" r: save the current contents of installed EEPROM to file.") return end local function printRom() local eeprom = component.eeprom io.write(eeprom.get()) end local function readRom() local eeprom = component.eeprom fileName = shell.resolve(args[1]) if not options.q then if fs.exists(fileName) then io.write("Are you sure you want to overwrite " .. fileName .. "?\n") io.write("Type `y` to confirm.\n") repeat local response = io.read() until response and response:lower():sub(1, 1) == "y" end io.write("Reading EEPROM " .. eeprom.address .. ".\n" ) end local bios = eeprom.get() local file = assert(io.open(fileName, "wb")) file:write(bios) file:close() if not options.q then io.write("All done!\nThe label is '" .. eeprom.getLabel() .. "'.\n") end end local function writeRom() local file = assert(io.open(args[1], "rb")) local bios = file:read("*a") file:close() if not options.q then io.write("Insert the EEPROM you would like to flash.\n") io.write("When ready to write, type `y` to confirm.\n") repeat local response = io.read() until response and response:lower():sub(1, 1) == "y" io.write("Beginning to flash EEPROM.\n") end local eeprom = component.eeprom if not options.q then io.write("Flashing EEPROM " .. eeprom.address .. ".\n") io.write("Please do NOT power down or restart your computer during this operation!\n") end eeprom.set(bios) local label = args[2] if not options.q and not label then io.write("Enter new label for this EEPROM. Leave input blank to leave the label unchanged.\n") label = io.read() end if label and #label > 0 then eeprom.setLabel(label) if not options.q then io.write("Set label to '" .. eeprom.getLabel() .. "'.\n") end end if not options.q then io.write("All done! You can remove the EEPROM and re-insert the previous one now.\n") end end if options.l then printRom() elseif options.r then readRom() else writeRom() end
mit
vonflynee/opencomputersserver
world/opencomputers/4f2775bd-9dcb-42e6-8318-1837ede27e76/bin/flash.lua
15
2414
local component = require("component") local shell = require("shell") local fs = require("filesystem") local args, options = shell.parse(...) if #args < 1 and not options.l then io.write("Usage: flash [-qlr] [<bios.lua>] [label]\n") io.write(" q: quiet mode, don't ask questions.\n") io.write(" l: print current contents of installed EEPROM.\n") io.write(" r: save the current contents of installed EEPROM to file.") return end local function printRom() local eeprom = component.eeprom io.write(eeprom.get()) end local function readRom() local eeprom = component.eeprom fileName = shell.resolve(args[1]) if not options.q then if fs.exists(fileName) then io.write("Are you sure you want to overwrite " .. fileName .. "?\n") io.write("Type `y` to confirm.\n") repeat local response = io.read() until response and response:lower():sub(1, 1) == "y" end io.write("Reading EEPROM " .. eeprom.address .. ".\n" ) end local bios = eeprom.get() local file = assert(io.open(fileName, "wb")) file:write(bios) file:close() if not options.q then io.write("All done!\nThe label is '" .. eeprom.getLabel() .. "'.\n") end end local function writeRom() local file = assert(io.open(args[1], "rb")) local bios = file:read("*a") file:close() if not options.q then io.write("Insert the EEPROM you would like to flash.\n") io.write("When ready to write, type `y` to confirm.\n") repeat local response = io.read() until response and response:lower():sub(1, 1) == "y" io.write("Beginning to flash EEPROM.\n") end local eeprom = component.eeprom if not options.q then io.write("Flashing EEPROM " .. eeprom.address .. ".\n") io.write("Please do NOT power down or restart your computer during this operation!\n") end eeprom.set(bios) local label = args[2] if not options.q and not label then io.write("Enter new label for this EEPROM. Leave input blank to leave the label unchanged.\n") label = io.read() end if label and #label > 0 then eeprom.setLabel(label) if not options.q then io.write("Set label to '" .. eeprom.getLabel() .. "'.\n") end end if not options.q then io.write("All done! You can remove the EEPROM and re-insert the previous one now.\n") end end if options.l then printRom() elseif options.r then readRom() else writeRom() end
mit
nesstea/darkstar
scripts/globals/items/kinkobo.lua
30
1043
----------------------------------------- -- ID: 17592 -- Item: Kinkobo -- Enchantment: Subtle Blow -- Duration: 60 Mins ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) return 0; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) if (target:addStatusEffect(EFFECT_ENCHANTMENT) == false) then target:addStatusEffect(EFFECT_ENCHANTMENT,0,0,3600,17592); end; end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_SUBTLE_BLOW, 20); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_SUBTLE_BLOW, 20); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Bastok_Mines/npcs/Azima.lua
24
1949
----------------------------------- -- Area: Bastok Mines -- NPC: Azima -- Alchemy Adv. Synthesis Image Support -- @pos 123.5 2 1 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,1); local SkillLevel = player:getSkillLevel(SKILL_ALCHEMY); local Cost = getAdvImageSupportCost(player,SKILL_ALCHEMY); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_ALCHEMY_IMAGERY) == false) then player:startEvent(0x007A,Cost,SkillLevel,0,0xB0001AF,player:getGil(),0,0,0); -- Event doesn't work else player:startEvent(0x007A,Cost,SkillLevel,0,0xB0001AF,player:getGil(),0x6FE2,0,0); end else player:startEvent(0x007A); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local Cost = getAdvImageSupportCost(player,SKILL_ALCHEMY); if (csid == 0x007A and option == 1) then player:delGil(Cost); player:messageSpecial(ALCHEMY_SUPPORT,0,7,0); player:addStatusEffect(EFFECT_ALCHEMY_IMAGERY,3,0,480); end end;
gpl-3.0
PUMpITapp/instantpizza
src/IOHandler.lua
1
7995
local ioHandler = {} --- Set if the program is running on the box or not local onBox = true progress = "IOhandler" --- Change the path system if the app runs on the box comparing to the emulator if onBox == true then dir = sys.root_path() else sys = {} sys.root_path = function () return '' end dir = "" end dofile(dir .. "table.save.lua") ---Function that is used to create a new user. --@param name is the users name --@param address is the users address --@param zipCode is the users zipCode --@param city is the users city --@param phone is the users phonenumber --@param email is the users email address --@param pizzeria is the pizzeria the user selects User = {} function User:new(name,address,zipCode,city,phone,email,pizzeria) newObj ={ name = name, address = address, zipCode = zipCode, city = city, phone = phone, email = email, pizzeria = pizzeria, } self.__index = self return setmetatable(newObj, self) end ---Function that is used to create a new pizzeria. --@param name is the pizzerias name --@param city is the pizzerias city --@param zipCode is the pizzerias zipCode --@param phoneNr is the pizzerias phonenumber --@param imgPath is the pizzerias path to the logotype --@param rating is the rating of the pizzeria --@param pizzas is the pizzerias pizzas in a table --@param drinks is the pizzerias drinks in a table Pizzeria = {} function Pizzeria:new(name,city,zipCode,phoneNr,imgPath,rating,pizzas,drinks) newObj = { name = name, city = city, zipCode = zipCode, phoneNr = phoneNr, imgPath = imgPath, rating = rating, pizzas = pizzas, drinks = drinks } self.__index = self return setmetatable(newObj, self) end ---Function that is used to create new pizzas. --@param name is the name of the pizza --@param price is the price of the pizza --@param ingredients is the ingredients of the pizza Pizza = {} function Pizza:new(name,price,ingredients) newObj = { name = name, price = price, ingredients = ingredients } self.__index = self return setmetatable(newObj, self) end ---Function that is used to create new drinks --@param name is the name och the drink --@param price is the price of the drink Drink = {} function Drink:new(name,price) newObj = { name = name, price = price } self.__index = self return setmetatable(newObj, self) end ---Function to read users from file --@return usersTable Contains the users that is read from file function ioHandler.readUserData() local usersTable = {} usersTable = table.load(dir .. "UserData.lua") return usersTable end ---Function to read pizzerias from file --@return pizzeriaTable Contains the pizzerias from file function ioHandler.readPizzerias() local pizzeriaTable = {} pizzeriaTable = table.load(dir .. "PizzeriaData.lua") return pizzeriaTable end ---Test function that reads pizzerias from file --@return pizzeriaTable Contains pizzerias that is read from file function ioHandler.readPizzerias_test() local pizzeriaTable = {} pizzeriaTable = table.load(dir .. "PizzeriaData_testing.lua") return pizzeriaTable end ---Function that adds lots dummy pizzerias and pizzas function ioHandler.addTestPizzerias() drinks ={} pizzas = {} pizzeriasTable = {} --Create drinks Drink1 = Drink:new("Coca cola","10") Drink2 = Drink:new("Fanta","10") Drink3 = Drink:new("Ramlösa","10") Drink4 = Drink:new("Julmust","10") --Creates pizzas. {name,price,{ingredients}} Pizza1 = Pizza:new("Vesuvio","70",{"Skinka","Ost"}) Pizza2 = Pizza:new("Kebab","75",{"Skinka","Ost","Kebab"}) Pizza3 = Pizza:new("Mexicana","70",{"Skinka","Ost","Taco"}) Pizza4 = Pizza:new("Azteka","65",{"Skinka","Ost","Jalapenos"}) Pizza5 = Pizza:new("Kebab Special","70",{"Kebab","Ost","Pommes"}) Pizza6 = Pizza:new("Kebabtallrik","65",{"Kebab","Pommes","Sallad"}) Pizza7 = Pizza:new("Kebabrulle","70",{"Kebab","Bröd","Sås"}) Pizza8 = Pizza:new("Hawaii","60",{"Skinka","Ost","Ananas"}) Pizza9 = Pizza:new("Poker","85",{"Oxfile","Ost","Champinjoner"}) Pizza10 = Pizza:new("Salami","75",{"Salami","Ost"}) Pizza11 = Pizza:new("Vegetaria","60",{"Champinjoner","Ost","Oliver"}) Pizza12 = Pizza:new("Capricciosa","60",{"Skinka","Ost","Champinjoner"}) Pizza13 = Pizza:new("Tono","80",{"Tonfisk","Ost"}) Pizza14 = Pizza:new("Margaritha","60",{"Ost"}) Pizza15 = Pizza:new("Tutti frutti","60",{"Ost","Ananas","Banan"}) Pizza16 = Pizza:new("Calzone","65",{"Inbakad","Skinka","Ost"}) Pizza17 = Pizza:new("Honolulu","60",{"Banan","Ost","Ananas"}) Pizza18 = Pizza:new("Kycklingpizza","60",{"Kyckling","Ost","Curry"}) Pizza19 = Pizza:new("Opera","70",{"Salami","Ost","Oliver"}) Pizza20 = Pizza:new("Disco","80",{"Korv","Fisk","BBQ"}) --Put drink1 and 2 into table drinks drinks[1] = Drink1 drinks[2] = Drink2 drinks[3] = Drink3 drinks[4] = Drink4 --Put pizzas into pizzas table pizzas[1] = Pizza1 pizzas[2] = Pizza2 pizzas[3] = Pizza3 pizzas[4] = Pizza4 pizzas[5] = Pizza5 pizzas[6] = Pizza6 pizzas[7] = Pizza7 pizzas[8] = Pizza8 pizzas[9] = Pizza9 pizzas[10] = Pizza10 pizzas[11] = Pizza11 pizzas[12] = Pizza12 pizzas[13] = Pizza13 pizzas[14] = Pizza14 pizzas[15] = Pizza15 pizzas[16] = Pizza16 pizzas[17] = Pizza17 pizzas[18] = Pizza18 pizzas[19] = Pizza19 pizzas[20] = Pizza20 --Create pizzerias Pizzeria1 = Pizzeria:new("Pizzeria Mona Lisa","Linköping","58434","010-1111111","pizza1.png","5.0",pizzas,drinks) Pizzeria2 = Pizzeria:new("Pizzeria Baguetten","Linköping","58436","010-1111112","pizza2.png","5.0",pizzas,drinks) Pizzeria3 = Pizzeria:new("Pizzeria Florens","Linköping","58220","010-1111113","pizza3.png","5.0",pizzas,drinks) Pizzeria4 = Pizzeria:new("Pizzeria Bari","Linköping","58217","010-1111114","pizza4.png","5.0",pizzas,drinks) Pizzeria5 = Pizzeria:new("Pizzeria Victoria","Linköping","58234","010-1111115","pizza5.png","5.0",pizzas,drinks) Pizzeria6 = Pizzeria:new("Pizzeria La Luna","Linköping","58214","010-1111116","pizza6.png","5.0",pizzas,drinks) Pizzeria7 = Pizzeria:new("Pizzafiket","Linköping","58233","010-1111117","pizza7.png","5.0",pizzas,drinks) Pizzeria8 = Pizzeria:new("Mamma Mia","Linköping","58232","010-1111118","pizza8.png","5.0",pizzas,drinks) Pizzeria9 = Pizzeria:new("Pizzeria Montecarlo","Linköping","58248","010-1111119","pizza9.png","5.0",pizzas,drinks) Pizzeria10 = Pizzeria:new("Pizzeria Tropicana","Linköping","58726","010-1111110","pizza10.png","5.0",pizzas,drinks) --Put pizzerias in table pizzeriasTable[1] = Pizzeria1 pizzeriasTable[2] = Pizzeria2 pizzeriasTable[3] = Pizzeria3 pizzeriasTable[4] = Pizzeria4 pizzeriasTable[5] = Pizzeria5 pizzeriasTable[6] = Pizzeria6 pizzeriasTable[7] = Pizzeria7 pizzeriasTable[8] = Pizzeria8 pizzeriasTable[9] = Pizzeria9 pizzeriasTable[10] = Pizzeria10 table.save(pizzeriasTable,dir .. "PizzeriaData.lua") end ---Function that saves userdata. --@param userForm is the user that is being saved. function ioHandler.saveUserData(userForm) tempUserTable = {} usersTable = {} j=1 user = User:new(userForm.name,userForm.address,userForm.zipCode,userForm.city,userForm.phone,userForm.email,userForm.pizzeria) ---Read users from file so previous users are not overwritten tempUserTable = ioHandler.readUserData() if not (tempUserTable == nil)then for i=1,#tempUserTable do usersTable[j]=tempUserTable[i] j=j+1 end end usersTable[j]=user table.save(usersTable,dir .. "UserData.lua") end ---Function that saves a table of users to file --@param userTable is the table of users that are going to be saved function ioHandler.saveUserTable(userTable) table.save(userTable,dir .. "UserData.lua") end ---Function that updates userdata --@param userForm is the user being edited function ioHandler.updateUser(userForm) users = table.load(dir .. "UserData.lua") table.remove(users,userForm.editIndex) ioHandler.saveUserTable(users) ioHandler.saveUserData(userForm) end return ioHandler
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/bowl_of_homemade_stew.lua
35
1131
----------------------------------------- -- ID: 5222 -- Item: Bowl of Homemade Stew -- Food Effect: 30Min, All Races ----------------------------------------- -- Vitality 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5222); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VIT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VIT, 1); end;
gpl-3.0
dpino/snabbswitch
lib/luajit/src/jit/dis_x86.lua
49
32818
---------------------------------------------------------------------------- -- LuaJIT x86/x64 disassembler module. -- -- Copyright (C) 2005-2017 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- Sending small code snippets to an external disassembler and mixing the -- output with our own stuff was too fragile. So I had to bite the bullet -- and write yet another x86 disassembler. Oh well ... -- -- The output format is very similar to what ndisasm generates. But it has -- been developed independently by looking at the opcode tables from the -- Intel and AMD manuals. The supported instruction set is quite extensive -- and reflects what a current generation Intel or AMD CPU implements in -- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3, -- SSE4.1, SSE4.2, SSE4a, AVX, AVX2 and even privileged and hypervisor -- (VMX/SVM) instructions. -- -- Notes: -- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported. -- * No attempt at optimization has been made -- it's fast enough for my needs. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local lower, rep = string.lower, string.rep local bit = require("bit") local tohex = bit.tohex -- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on. local map_opc1_32 = { --0x [0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es", "orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*", --1x "adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss", "sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds", --2x "andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa", "subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das", --3x "xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa", "cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas", --4x "incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR", "decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR", --5x "pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR", "popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR", --6x "sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr", "fs:seg","gs:seg","o16:","a16", "pushUi","imulVrmi","pushBs","imulVrms", "insb","insVS","outsb","outsVS", --7x "joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj", "jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj", --8x "arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms", "testBmr","testVmr","xchgBrm","xchgVrm", "movBmr","movVmr","movBrm","movVrm", "movVmg","leaVrm","movWgm","popUm", --9x "nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR", "xchgVaR","xchgVaR","xchgVaR","xchgVaR", "sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait", "sz*pushfw,pushf","sz*popfw,popf","sahf","lahf", --Ax "movBao","movVao","movBoa","movVoa", "movsb","movsVS","cmpsb","cmpsVS", "testBai","testVai","stosb","stosVS", "lodsb","lodsVS","scasb","scasVS", --Bx "movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi", "movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI", --Cx "shift!Bmu","shift!Vmu","retBw","ret","vex*3$lesVrm","vex*2$ldsVrm","movBmi","movVmi", "enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS", --Dx "shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb", "fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7", --Ex "loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj", "inBau","inVau","outBua","outVua", "callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda", --Fx "lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm", "clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm", } assert(#map_opc1_32 == 255) -- Map for 1st opcode byte in 64 bit mode (overrides only). local map_opc1_64 = setmetatable({ [0x06]=false, [0x07]=false, [0x0e]=false, [0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false, [0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false, [0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:", [0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb", [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb", [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb", [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb", [0x82]=false, [0x9a]=false, [0xc4]="vex*3", [0xc5]="vex*2", [0xce]=false, [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false, }, { __index = map_opc1_32 }) -- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you. -- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2 local map_opc2 = { --0x [0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret", "invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu", --1x "movupsXrm|movssXrvm|movupdXrm|movsdXrvm", "movupsXmr|movssXmvr|movupdXmr|movsdXmvr", "movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm", "movlpsXmr||movlpdXmr", "unpcklpsXrvm||unpcklpdXrvm", "unpckhpsXrvm||unpckhpdXrvm", "movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm", "movhpsXmr||movhpdXmr", "$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm", "hintnopVm","hintnopVm","hintnopVm","hintnopVm", --2x "movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil, "movapsXrm||movapdXrm", "movapsXmr||movapdXmr", "cvtpi2psXrMm|cvtsi2ssXrvVmt|cvtpi2pdXrMm|cvtsi2sdXrvVmt", "movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr", "cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm", "cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm", "ucomissXrm||ucomisdXrm", "comissXrm||comisdXrm", --3x "wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec", "opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil, --4x "cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm", "cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm", "cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm", "cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm", --5x "movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm", "rsqrtpsXrm|rsqrtssXrvm","rcppsXrm|rcpssXrvm", "andpsXrvm||andpdXrvm","andnpsXrvm||andnpdXrvm", "orpsXrvm||orpdXrvm","xorpsXrvm||xorpdXrvm", "addpsXrvm|addssXrvm|addpdXrvm|addsdXrvm","mulpsXrvm|mulssXrvm|mulpdXrvm|mulsdXrvm", "cvtps2pdXrm|cvtss2sdXrvm|cvtpd2psXrm|cvtsd2ssXrvm", "cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm", "subpsXrvm|subssXrvm|subpdXrvm|subsdXrvm","minpsXrvm|minssXrvm|minpdXrvm|minsdXrvm", "divpsXrvm|divssXrvm|divpdXrvm|divsdXrvm","maxpsXrvm|maxssXrvm|maxpdXrvm|maxsdXrvm", --6x "punpcklbwPrvm","punpcklwdPrvm","punpckldqPrvm","packsswbPrvm", "pcmpgtbPrvm","pcmpgtwPrvm","pcmpgtdPrvm","packuswbPrvm", "punpckhbwPrvm","punpckhwdPrvm","punpckhdqPrvm","packssdwPrvm", "||punpcklqdqXrvm","||punpckhqdqXrvm", "movPrVSm","movqMrm|movdquXrm|movdqaXrm", --7x "pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pvmu", "pshiftd!Pvmu","pshiftq!Mvmu||pshiftdq!Xvmu", "pcmpeqbPrvm","pcmpeqwPrvm","pcmpeqdPrvm","emms*|", "vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$", nil,nil, "||haddpdXrvm|haddpsXrvm","||hsubpdXrvm|hsubpsXrvm", "movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr", --8x "joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj", "jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj", --9x "setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm", "setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm", --Ax "push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil, "push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm", --Bx "cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr", "$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt", "|popcntVrm","ud2Dp","bt!Vmu","btcVmr", "bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt", --Cx "xaddBmr","xaddVmr", "cmppsXrvmu|cmpssXrvmu|cmppdXrvmu|cmpsdXrvmu","$movntiVmr|", "pinsrwPrvWmu","pextrwDrPmu", "shufpsXrvmu||shufpdXrvmu","$cmpxchg!Qmp", "bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR", --Dx "||addsubpdXrvm|addsubpsXrvm","psrlwPrvm","psrldPrvm","psrlqPrvm", "paddqPrvm","pmullwPrvm", "|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm", "psubusbPrvm","psubuswPrvm","pminubPrvm","pandPrvm", "paddusbPrvm","padduswPrvm","pmaxubPrvm","pandnPrvm", --Ex "pavgbPrvm","psrawPrvm","psradPrvm","pavgwPrvm", "pmulhuwPrvm","pmulhwPrvm", "|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr", "psubsbPrvm","psubswPrvm","pminswPrvm","porPrvm", "paddsbPrvm","paddswPrvm","pmaxswPrvm","pxorPrvm", --Fx "|||lddquXrm","psllwPrvm","pslldPrvm","psllqPrvm", "pmuludqPrvm","pmaddwdPrvm","psadbwPrvm","maskmovqMrm||maskmovdquXrm$", "psubbPrvm","psubwPrvm","psubdPrvm","psubqPrvm", "paddbPrvm","paddwPrvm","padddPrvm","ud", } assert(map_opc2[255] == "ud") -- Map for three-byte opcodes. Can't wait for their next invention. local map_opc3 = { ["38"] = { -- [66] 0f 38 xx --0x [0]="pshufbPrvm","phaddwPrvm","phadddPrvm","phaddswPrvm", "pmaddubswPrvm","phsubwPrvm","phsubdPrvm","phsubswPrvm", "psignbPrvm","psignwPrvm","psigndPrvm","pmulhrswPrvm", "||permilpsXrvm","||permilpdXrvm",nil,nil, --1x "||pblendvbXrma",nil,nil,nil, "||blendvpsXrma","||blendvpdXrma","||permpsXrvm","||ptestXrm", "||broadcastssXrm","||broadcastsdXrm","||broadcastf128XrlXm",nil, "pabsbPrm","pabswPrm","pabsdPrm",nil, --2x "||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm", "||pmovsxwqXrm","||pmovsxdqXrm",nil,nil, "||pmuldqXrvm","||pcmpeqqXrvm","||$movntdqaXrm","||packusdwXrvm", "||maskmovpsXrvm","||maskmovpdXrvm","||maskmovpsXmvr","||maskmovpdXmvr", --3x "||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm", "||pmovzxwqXrm","||pmovzxdqXrm","||permdXrvm","||pcmpgtqXrvm", "||pminsbXrvm","||pminsdXrvm","||pminuwXrvm","||pminudXrvm", "||pmaxsbXrvm","||pmaxsdXrvm","||pmaxuwXrvm","||pmaxudXrvm", --4x "||pmulddXrvm","||phminposuwXrm",nil,nil, nil,"||psrlvVSXrvm","||psravdXrvm","||psllvVSXrvm", --5x [0x58] = "||pbroadcastdXrlXm",[0x59] = "||pbroadcastqXrlXm", [0x5a] = "||broadcasti128XrlXm", --7x [0x78] = "||pbroadcastbXrlXm",[0x79] = "||pbroadcastwXrlXm", --8x [0x8c] = "||pmaskmovXrvVSm", [0x8e] = "||pmaskmovVSmXvr", --Dx [0xdc] = "||aesencXrvm", [0xdd] = "||aesenclastXrvm", [0xde] = "||aesdecXrvm", [0xdf] = "||aesdeclastXrvm", --Fx [0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt", [0xf7] = "| sarxVrmv| shlxVrmv| shrxVrmv", }, ["3a"] = { -- [66] 0f 3a xx --0x [0x00]="||permqXrmu","||permpdXrmu","||pblenddXrvmu",nil, "||permilpsXrmu","||permilpdXrmu","||perm2f128Xrvmu",nil, "||roundpsXrmu","||roundpdXrmu","||roundssXrvmu","||roundsdXrvmu", "||blendpsXrvmu","||blendpdXrvmu","||pblendwXrvmu","palignrPrvmu", --1x nil,nil,nil,nil, "||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru", "||insertf128XrvlXmu","||extractf128XlXmYru",nil,nil, nil,nil,nil,nil, --2x "||pinsrbXrvVmu","||insertpsXrvmu","||pinsrXrvVmuS",nil, --3x [0x38] = "||inserti128Xrvmu",[0x39] = "||extracti128XlXmYru", --4x [0x40] = "||dppsXrvmu", [0x41] = "||dppdXrvmu", [0x42] = "||mpsadbwXrvmu", [0x44] = "||pclmulqdqXrvmu", [0x46] = "||perm2i128Xrvmu", [0x4a] = "||blendvpsXrvmb",[0x4b] = "||blendvpdXrvmb", [0x4c] = "||pblendvbXrvmb", --6x [0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu", [0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu", [0xdf] = "||aeskeygenassistXrmu", --Fx [0xf0] = "||| rorxVrmu", }, } -- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands). local map_opcvm = { [0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff", [0xc8]="monitor",[0xc9]="mwait", [0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave", [0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga", [0xf8]="swapgs",[0xf9]="rdtscp", } -- Map for FP opcodes. And you thought stack machines are simple? local map_opcfp = { -- D8-DF 00-BF: opcodes with a memory operand. -- D8 [0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm", "fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm", -- DA "fiaddDm","fimulDm","ficomDm","ficompDm", "fisubDm","fisubrDm","fidivDm","fidivrDm", -- DB "fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp", -- DC "faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm", -- DD "fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm", -- DE "fiaddWm","fimulWm","ficomWm","ficompWm", "fisubWm","fisubrWm","fidivWm","fidivrWm", -- DF "fildWm","fisttpWm","fistWm","fistpWm", "fbld twordFmp","fildQm","fbstp twordFmp","fistpQm", -- xx C0-FF: opcodes with a pseudo-register operand. -- D8 "faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf", -- D9 "fldFf","fxchFf",{"fnop"},nil, {"fchs","fabs",nil,nil,"ftst","fxam"}, {"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"}, {"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"}, {"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"}, -- DA "fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil, -- DB "fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf", {nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil, -- DC "fadd toFf","fmul toFf",nil,nil, "fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf", -- DD "ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil, -- DE "faddpFf","fmulpFf",nil,{nil,"fcompp"}, "fsubrpFf","fsubpFf","fdivrpFf","fdivpFf", -- DF nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil, } assert(map_opcfp[126] == "fcomipFf") -- Map for opcode groups. The subkey is sp from the ModRM byte. local map_opcgroup = { arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" }, shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" }, testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" }, testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" }, incb = { "inc", "dec" }, incd = { "inc", "dec", "callUmp", "$call farDmp", "jmpUmp", "$jmp farDmp", "pushUm" }, sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" }, sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt", "smsw", nil, "lmsw", "vm*$invlpg" }, bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" }, cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil, nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" }, pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" }, pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" }, pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" }, pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" }, fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr", nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" }, prefetch = { "prefetch", "prefetchw" }, prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" }, } ------------------------------------------------------------------------------ -- Maps for register names. local map_regs = { B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" }, D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" }, Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }, M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext! X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }, Y = { "ymm0", "ymm1", "ymm2", "ymm3", "ymm4", "ymm5", "ymm6", "ymm7", "ymm8", "ymm9", "ymm10", "ymm11", "ymm12", "ymm13", "ymm14", "ymm15" }, } local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" } -- Maps for size names. local map_sz2n = { B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, Y = 32, } local map_sz2prefix = { B = "byte", W = "word", D = "dword", Q = "qword", M = "qword", X = "xword", Y = "yword", F = "dword", G = "qword", -- No need for sizes/register names for these two. } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local code, pos, hex = ctx.code, ctx.pos, "" local hmax = ctx.hexdump if hmax > 0 then for i=ctx.start,pos-1 do hex = hex..format("%02X", byte(code, i, i)) end if #hex > hmax then hex = sub(hex, 1, hmax)..". " else hex = hex..rep(" ", hmax-#hex+2) end end if operands then text = text.." "..operands end if ctx.o16 then text = "o16 "..text; ctx.o16 = false end if ctx.a32 then text = "a32 "..text; ctx.a32 = false end if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end if ctx.rex then local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "").. (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "").. (ctx.vexl and "l" or "") if ctx.vexv and ctx.vexv ~= 0 then t = t.."v"..ctx.vexv end if t ~= "" then text = ctx.rex.."."..t.." "..gsub(text, "^ ", "") elseif ctx.rex == "vex" then text = gsub("v"..text, "^v ", "") end ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.vexl = false; ctx.vexv = false end if ctx.seg then local text2, n = gsub(text, "%[", "["..ctx.seg..":") if n == 0 then text = ctx.seg.." "..text else text = text2 end ctx.seg = false end if ctx.lock then text = "lock "..text; ctx.lock = false end local imm = ctx.imm if imm then local sym = ctx.symtab[imm] if sym then text = text.."\t->"..sym end end ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text)) ctx.mrm = false ctx.vexv = false ctx.start = pos ctx.imm = nil end -- Clear all prefix flags. local function clearprefixes(ctx) ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.a32 = false; ctx.vexl = false end -- Fallback for incomplete opcodes at the end. local function incomplete(ctx) ctx.pos = ctx.stop+1 clearprefixes(ctx) return putop(ctx, "(incomplete)") end -- Fallback for unknown opcodes. local function unknown(ctx) clearprefixes(ctx) return putop(ctx, "(unknown)") end -- Return an immediate of the specified size. local function getimm(ctx, pos, n) if pos+n-1 > ctx.stop then return incomplete(ctx) end local code = ctx.code if n == 1 then local b1 = byte(code, pos, pos) return b1 elseif n == 2 then local b1, b2 = byte(code, pos, pos+1) return b1+b2*256 else local b1, b2, b3, b4 = byte(code, pos, pos+3) local imm = b1+b2*256+b3*65536+b4*16777216 ctx.imm = imm return imm end end -- Process pattern string and generate the operands. local function putpat(ctx, name, pat) local operands, regs, sz, mode, sp, rm, sc, rx, sdisp local code, pos, stop, vexl = ctx.code, ctx.pos, ctx.stop, ctx.vexl -- Chars used: 1DFGIMPQRSTUVWXYabcdfgijlmoprstuvwxyz for p in gmatch(pat, ".") do local x = nil if p == "V" or p == "U" then if ctx.rexw then sz = "Q"; ctx.rexw = false elseif ctx.o16 then sz = "W"; ctx.o16 = false elseif p == "U" and ctx.x64 then sz = "Q" else sz = "D" end regs = map_regs[sz] elseif p == "T" then if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end regs = map_regs[sz] elseif p == "B" then sz = "B" regs = ctx.rex and map_regs.B64 or map_regs.B elseif match(p, "[WDQMXYFG]") then sz = p if sz == "X" and vexl then sz = "Y"; ctx.vexl = false end regs = map_regs[sz] elseif p == "P" then sz = ctx.o16 and "X" or "M"; ctx.o16 = false if sz == "X" and vexl then sz = "Y"; ctx.vexl = false end regs = map_regs[sz] elseif p == "S" then name = name..lower(sz) elseif p == "s" then local imm = getimm(ctx, pos, 1); if not imm then return end x = imm <= 127 and format("+0x%02x", imm) or format("-0x%02x", 256-imm) pos = pos+1 elseif p == "u" then local imm = getimm(ctx, pos, 1); if not imm then return end x = format("0x%02x", imm) pos = pos+1 elseif p == "b" then local imm = getimm(ctx, pos, 1); if not imm then return end x = regs[imm/16+1] pos = pos+1 elseif p == "w" then local imm = getimm(ctx, pos, 2); if not imm then return end x = format("0x%x", imm) pos = pos+2 elseif p == "o" then -- [offset] if ctx.x64 then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("[0x%08x%08x]", imm2, imm1) pos = pos+8 else local imm = getimm(ctx, pos, 4); if not imm then return end x = format("[0x%08x]", imm) pos = pos+4 end elseif p == "i" or p == "I" then local n = map_sz2n[sz] if n == 8 and ctx.x64 and p == "I" then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("0x%08x%08x", imm2, imm1) else if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then imm = (0xffffffff+1)-imm x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm) else x = format(imm > 65535 and "0x%08x" or "0x%x", imm) end end pos = pos+n elseif p == "j" then local n = map_sz2n[sz] if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "B" and imm > 127 then imm = imm-256 elseif imm > 2147483647 then imm = imm-4294967296 end pos = pos+n imm = imm + pos + ctx.addr if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end ctx.imm = imm if sz == "W" then x = format("word 0x%04x", imm%65536) elseif ctx.x64 then local lo = imm % 0x1000000 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo) else x = "0x"..tohex(imm) end elseif p == "R" then local r = byte(code, pos-1, pos-1)%8 if ctx.rexb then r = r + 8; ctx.rexb = false end x = regs[r+1] elseif p == "a" then x = regs[1] elseif p == "c" then x = "cl" elseif p == "d" then x = "dx" elseif p == "1" then x = "1" else if not mode then mode = ctx.mrm if not mode then if pos > stop then return incomplete(ctx) end mode = byte(code, pos, pos) pos = pos+1 end rm = mode%8; mode = (mode-rm)/8 sp = mode%8; mode = (mode-sp)/8 sdisp = "" if mode < 3 then if rm == 4 then if pos > stop then return incomplete(ctx) end sc = byte(code, pos, pos) pos = pos+1 rm = sc%8; sc = (sc-rm)/8 rx = sc%8; sc = (sc-rx)/8 if ctx.rexx then rx = rx + 8; ctx.rexx = false end if rx == 4 then rx = nil end end if mode > 0 or rm == 5 then local dsz = mode if dsz ~= 1 then dsz = 4 end local disp = getimm(ctx, pos, dsz); if not disp then return end if mode == 0 then rm = nil end if rm or rx or (not sc and ctx.x64 and not ctx.a32) then if dsz == 1 and disp > 127 then sdisp = format("-0x%x", 256-disp) elseif disp >= 0 and disp <= 0x7fffffff then sdisp = format("+0x%x", disp) else sdisp = format("-0x%x", (0xffffffff+1)-disp) end else sdisp = format(ctx.x64 and not ctx.a32 and not (disp >= 0 and disp <= 0x7fffffff) and "0xffffffff%08x" or "0x%08x", disp) end pos = pos+dsz end end if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end if ctx.rexr then sp = sp + 8; ctx.rexr = false end end if p == "m" then if mode == 3 then x = regs[rm+1] else local aregs = ctx.a32 and map_regs.D or ctx.aregs local srm, srx = "", "" if rm then srm = aregs[rm+1] elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end ctx.a32 = false if rx then if rm then srm = srm.."+" end srx = aregs[rx+1] if sc > 0 then srx = srx.."*"..(2^sc) end end x = format("[%s%s%s]", srm, srx, sdisp) end if mode < 3 and (not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck. x = map_sz2prefix[sz].." "..x end elseif p == "r" then x = regs[sp+1] elseif p == "g" then x = map_segregs[sp+1] elseif p == "p" then -- Suppress prefix. elseif p == "f" then x = "st"..rm elseif p == "x" then if sp == 0 and ctx.lock and not ctx.x64 then x = "CR8"; ctx.lock = false else x = "CR"..sp end elseif p == "v" then if ctx.vexv then x = regs[ctx.vexv+1]; ctx.vexv = false end elseif p == "y" then x = "DR"..sp elseif p == "z" then x = "TR"..sp elseif p == "l" then vexl = false elseif p == "t" then else error("bad pattern `"..pat.."'") end end if x then operands = operands and operands..", "..x or x end end ctx.pos = pos return putop(ctx, name, operands) end -- Forward declaration. local map_act -- Fetch and cache MRM byte. local function getmrm(ctx) local mrm = ctx.mrm if not mrm then local pos = ctx.pos if pos > ctx.stop then return nil end mrm = byte(ctx.code, pos, pos) ctx.pos = pos+1 ctx.mrm = mrm end return mrm end -- Dispatch to handler depending on pattern. local function dispatch(ctx, opat, patgrp) if not opat then return unknown(ctx) end if match(opat, "%|") then -- MMX/SSE variants depending on prefix. local p if ctx.rep then p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)" ctx.rep = false elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false else p = "^[^%|]*" end opat = match(opat, p) if not opat then return unknown(ctx) end -- ctx.rep = false; ctx.o16 = false --XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi] --XXX remove in branches? end if match(opat, "%$") then -- reg$mem variants. local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)") if opat == "" then return unknown(ctx) end end if opat == "" then return unknown(ctx) end local name, pat = match(opat, "^([a-z0-9 ]*)(.*)") if pat == "" and patgrp then pat = patgrp end return map_act[sub(pat, 1, 1)](ctx, name, pat) end -- Get a pattern from an opcode map and dispatch to handler. local function dispatchmap(ctx, opcmap) local pos = ctx.pos local opat = opcmap[byte(ctx.code, pos, pos)] pos = pos + 1 ctx.pos = pos return dispatch(ctx, opat) end -- Map for action codes. The key is the first char after the name. map_act = { -- Simple opcodes without operands. [""] = function(ctx, name, pat) return putop(ctx, name) end, -- Operand size chars fall right through. B = putpat, W = putpat, D = putpat, Q = putpat, V = putpat, U = putpat, T = putpat, M = putpat, X = putpat, P = putpat, F = putpat, G = putpat, Y = putpat, -- Collect prefixes. [":"] = function(ctx, name, pat) ctx[pat == ":" and name or sub(pat, 2)] = name if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes. end, -- Chain to special handler specified by name. ["*"] = function(ctx, name, pat) return map_act[name](ctx, name, sub(pat, 2)) end, -- Use named subtable for opcode group. ["!"] = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2)) end, -- o16,o32[,o64] variants. sz = function(ctx, name, pat) if ctx.o16 then ctx.o16 = false else pat = match(pat, ",(.*)") if ctx.rexw then local p = match(pat, ",(.*)") if p then pat = p; ctx.rexw = false end end end pat = match(pat, "^[^,]*") return dispatch(ctx, pat) end, -- Two-byte opcode dispatch. opc2 = function(ctx, name, pat) return dispatchmap(ctx, map_opc2) end, -- Three-byte opcode dispatch. opc3 = function(ctx, name, pat) return dispatchmap(ctx, map_opc3[pat]) end, -- VMX/SVM dispatch. vm = function(ctx, name, pat) return dispatch(ctx, map_opcvm[ctx.mrm]) end, -- Floating point opcode dispatch. fp = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end local rm = mrm%8 local idx = pat*8 + ((mrm-rm)/8)%8 if mrm >= 192 then idx = idx + 64 end local opat = map_opcfp[idx] if type(opat) == "table" then opat = opat[rm+1] end return dispatch(ctx, opat) end, -- REX prefix. rex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX or VEX prefix allowed. for p in gmatch(pat, ".") do ctx["rex"..p] = true end ctx.rex = "rex" end, -- VEX prefix. vex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX or VEX prefix allowed. ctx.rex = "vex" local pos = ctx.pos if ctx.mrm then ctx.mrm = nil pos = pos-1 end local b = byte(ctx.code, pos, pos) if not b then return incomplete(ctx) end pos = pos+1 if b < 128 then ctx.rexr = true end local m = 1 if pat == "3" then m = b%32; b = (b-m)/32 local nb = b%2; b = (b-nb)/2 if nb == 0 then ctx.rexb = true end local nx = b%2 if nx == 0 then ctx.rexx = true end b = byte(ctx.code, pos, pos) if not b then return incomplete(ctx) end pos = pos+1 if b >= 128 then ctx.rexw = true end end ctx.pos = pos local map if m == 1 then map = map_opc2 elseif m == 2 then map = map_opc3["38"] elseif m == 3 then map = map_opc3["3a"] else return unknown(ctx) end local p = b%4; b = (b-p)/4 if p == 1 then ctx.o16 = "o16" elseif p == 2 then ctx.rep = "rep" elseif p == 3 then ctx.rep = "repne" end local l = b%2; b = (b-l)/2 if l ~= 0 then ctx.vexl = true end ctx.vexv = (-1-b)%16 return dispatchmap(ctx, map) end, -- Special case for nop with REX prefix. nop = function(ctx, name, pat) return dispatch(ctx, ctx.rex and pat or "nop") end, -- Special case for 0F 77. emms = function(ctx, name, pat) if ctx.rex ~= "vex" then return putop(ctx, "emms") elseif ctx.vexl then ctx.vexl = false return putop(ctx, "zeroall") else return putop(ctx, "zeroupper") end end, } ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code ofs = ofs + 1 ctx.start = ofs ctx.pos = ofs ctx.stop = stop ctx.imm = nil ctx.mrm = false clearprefixes(ctx) while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end if ctx.pos ~= ctx.start then incomplete(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create(code, addr, out) local ctx = {} ctx.code = code ctx.addr = (addr or 0) - 1 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 16 ctx.x64 = false ctx.map1 = map_opc1_32 ctx.aregs = map_regs.D return ctx end local function create64(code, addr, out) local ctx = create(code, addr, out) ctx.x64 = true ctx.map1 = map_opc1_64 ctx.aregs = map_regs.Q return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass(code, addr, out) create(code, addr, out):disass() end local function disass64(code, addr, out) create64(code, addr, out):disass() end -- Return register name for RID. local function regname(r) if r < 8 then return map_regs.D[r+1] end return map_regs.X[r-7] end local function regname64(r) if r < 16 then return map_regs.Q[r+1] end return map_regs.X[r-15] end -- Public module functions. return { create = create, create64 = create64, disass = disass, disass64 = disass64, regname = regname, regname64 = regname64 }
apache-2.0
NezzKryptic/Wire-Extras
lua/entities/gmod_wire_realmagnet/shared.lua
1
2162
ENT.Type = "anim" ENT.Base = "base_wire_entity" ENT.PrintName = "Wire Magnet" ENT.Author = "cpf" ENT.Contact = "" ENT.Purpose = "" ENT.Instructions = "" ENT.Spawnable = false ENT.AdminSpawnable = false function ENT:SetOn( boolon ) self:SetNetworkedBool( "On", boolon, true ) self:GetTable().On=boolon end function ENT:IsOn( name ) if SERVER then return self:GetTable().On end return self:GetNetworkedBool( "On" ) end function ENT:SetBackwards( boolon ) self:SetNetworkedBool( "Backwards", boolon, true ) self:GetTable().Backwards=boolon end function ENT:IsBackwards( name ) if SERVER then return self:GetTable().Backwards end return self:GetNetworkedBool( "Backwards" ) end function ENT:SetTargetOnlyMetal( boolon ) self:SetNetworkedBool( "TargetOnlyMetal", boolon, true ) self:GetTable().TargetOnlyMetal=boolon end function ENT:IsTargetOnlyMetal( name ) if SERVER then return self:GetTable().TargetOnlyMetal end return self:GetNetworkedBool( "TargetOnlyMetal" ) or true end function ENT:SetStrength(Strength) if Strength<0 then self:SetBackwards(true) Strength=math.abs(Strength) end Strength=math.min(Strength,GetConVarNumber("sbox_wire_magnets_maxstrength")) self:SetNetworkedFloat("Strength", Strength) self:GetTable().Strength=Strength end function ENT:GetStrength() if SERVER then return self:GetTable().Strength or 0 end return self:GetNetworkedFloat("Strength") or 0 end function ENT:SetLength(len) --print("set len:"..len) self:SetNetworkedFloat("Length", math.min(len,GetConVarNumber("sbox_wire_magnets_maxlen"))) self:GetTable().Len=math.min(len,GetConVarNumber("sbox_wire_magnets_maxlen")) end function ENT:GetLength() --PrintTable(self:GetTable()) if SERVER then return self:GetTable().Len or 0 end return self:GetNetworkedFloat("Length") or 0 end function ENT:SetPropFilter(pf) self:SetNetworkedString("PropFilter", pf) self:GetTable().PropFilter=pf end function ENT:GetPropFilter() if SERVER then return self:GetTable().PropFilter end return self:GetNetworkedString("PropFilter") or "" end
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/cup_of_chamomile_tea.lua
35
1384
----------------------------------------- -- ID: 4603 -- Item: cup_of_chamomile_tea -- Food Effect: 180Min, All Races ----------------------------------------- -- Magic 8 -- Vitality -2 -- Charisma 2 -- Magic Regen While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4603); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 8); target:addMod(MOD_VIT, -2); target:addMod(MOD_CHR, 2); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 8); target:delMod(MOD_VIT, -2); target:delMod(MOD_CHR, 2); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
hadi9090/celassicalteam
dkjson.lua
3282
26558
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.4* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.4"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat local json = { version = "dkjson 2.4" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") if g.version() == "0.11" then error "due to a bug in LPeg 0.11, it cannot be used for JSON matching" end local pegmatch = g.match local P, S, R = g.P, g.S, g.R local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
unlicense
nesstea/darkstar
scripts/zones/Garlaige_Citadel_[S]/Zone.lua
27
1281
----------------------------------- -- -- Zone: Garlaige_Citadel_[S] (164) -- ----------------------------------- package.loaded["scripts/zones/Garlaige_Citadel_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Garlaige_Citadel_[S]/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-300,-13.548,157,64); 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
UnfortunateFruit/darkstar
scripts/globals/mobskills/Seismostomp.lua
7
1152
--------------------------------------------- -- Seismostomp -- -- Description: Damage varies with TP. Additional effect: "Stun." -- Type: Physical (Blunt) -- -- --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.3; if(mob:isMobType(MOBTYPE_NOTORIOUS)) then dmgmod = dmgmod + math.random(); end local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local shadows = info.hitslanded; -- wipe shadows if(mob:isMobType(MOBTYPE_NOTORIOUS)) then shadows = MOBPARAM_WIPE_SHADOWS; end local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,shadows); local typeEffect = EFFECT_STUN; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4); target:delHP(dmg); return dmg; end;
gpl-3.0
plajjan/snabbswitch
lib/ljsyscall/syscall/freebsd/constants.lua
18
31643
-- tables of constants for NetBSD local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string, select = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string, select local abi = require "syscall.abi" local h = require "syscall.helpers" local bit = require "syscall.bit" local octal, multiflags, charflags, swapflags, strflag, atflag, modeflags = h.octal, h.multiflags, h.charflags, h.swapflags, h.strflag, h.atflag, h.modeflags local version = require "syscall.freebsd.version".version local ffi = require "ffi" local function charp(n) return ffi.cast("char *", n) end local c = {} c.errornames = require "syscall.freebsd.errors" c.STD = strflag { IN_FILENO = 0, OUT_FILENO = 1, ERR_FILENO = 2, IN = 0, OUT = 1, ERR = 2, } c.PATH_MAX = 1024 c.E = strflag { PERM = 1, NOENT = 2, SRCH = 3, INTR = 4, IO = 5, NXIO = 6, ["2BIG"] = 7, NOEXEC = 8, BADF = 9, CHILD = 10, DEADLK = 11, NOMEM = 12, ACCES = 13, FAULT = 14, NOTBLK = 15, BUSY = 16, EXIST = 17, XDEV = 18, NODEV = 19, NOTDIR = 20, ISDIR = 21, INVAL = 22, NFILE = 23, MFILE = 24, NOTTY = 25, TXTBSY = 26, FBIG = 27, NOSPC = 28, SPIPE = 29, ROFS = 30, MLINK = 31, PIPE = 32, DOM = 33, RANGE = 34, AGAIN = 35, INPROGRESS = 36, ALREADY = 37, NOTSOCK = 38, DESTADDRREQ = 39, MSGSIZE = 40, PROTOTYPE = 41, NOPROTOOPT = 42, PROTONOSUPPORT= 43, SOCKTNOSUPPORT= 44, OPNOTSUPP = 45, PFNOSUPPORT = 46, AFNOSUPPORT = 47, ADDRINUSE = 48, ADDRNOTAVAIL = 49, NETDOWN = 50, NETUNREACH = 51, NETRESET = 52, CONNABORTED = 53, CONNRESET = 54, NOBUFS = 55, ISCONN = 56, NOTCONN = 57, SHUTDOWN = 58, TOOMANYREFS = 59, TIMEDOUT = 60, CONNREFUSED = 61, LOOP = 62, NAMETOOLONG = 63, HOSTDOWN = 64, HOSTUNREACH = 65, NOTEMPTY = 66, PROCLIM = 67, USERS = 68, DQUOT = 69, STALE = 70, REMOTE = 71, BADRPC = 72, BADRPC = 72, RPCMISMATCH = 73, PROGUNAVAIL = 74, PROGMISMATCH = 75, PROCUNAVAIL = 76, NOLCK = 77, NOSYS = 78, FTYPE = 79, AUTH = 80, NEEDAUTH = 81, IDRM = 82, NOMSG = 83, OVERFLOW = 84, CANCELED = 85, ILSEQ = 86, NOATTR = 87, DOOFUS = 88, BADMSG = 89, MULTIHOP = 90, NOLINK = 91, PROTO = 92, NOTCAPABLE = 93, CAPMODE = 94, } if version >= 10 then c.E.NOTRECOVERABLE= 95 c.E.OWNERDEAD = 96 end -- alternate names c.EALIAS = { WOULDBLOCK = c.E.AGAIN, } c.AF = strflag { UNSPEC = 0, LOCAL = 1, INET = 2, IMPLINK = 3, PUP = 4, CHAOS = 5, NETBIOS = 6, ISO = 7, ECMA = 8, DATAKIT = 9, CCITT = 10, SNA = 11, DECNET = 12, DLI = 13, LAT = 14, HYLINK = 15, APPLETALK = 16, ROUTE = 17, LINK = 18, -- #define pseudo_AF_XTP 19 COIP = 20, CNT = 21, -- #define pseudo_AF_RTIP 22 IPX = 23, SIP = 24, -- pseudo_AF_PIP 25 ISDN = 26, -- pseudo_AF_KEY 27 INET6 = 28, NATM = 29, ATM = 30, -- pseudo_AF_HDRCMPLT 31 NETGRAPH = 32, SLOW = 33, SCLUSTER = 34, ARP = 35, BLUETOOTH = 36, IEEE80211 = 37, } c.AF.UNIX = c.AF.LOCAL c.AF.OSI = c.AF.ISO c.AF.E164 = c.AF.ISDN if version >= 10 then c.AF.INET_SDP = 40 c.AF.INET6_SDP = 42 end c.O = multiflags { RDONLY = 0x0000, WRONLY = 0x0001, RDWR = 0x0002, ACCMODE = 0x0003, NONBLOCK = 0x0004, APPEND = 0x0008, SHLOCK = 0x0010, EXLOCK = 0x0020, ASYNC = 0x0040, FSYNC = 0x0080, SYNC = 0x0080, NOFOLLOW = 0x0100, CREAT = 0x0200, TRUNC = 0x0400, EXCL = 0x0800, NOCTTY = 0x8000, DIRECT = 0x00010000, DIRECTORY = 0x00020000, EXEC = 0x00040000, TTY_INIT = 0x00080000, CLOEXEC = 0x00100000, } -- for pipe2, selected flags from c.O c.OPIPE = multiflags { NONBLOCK = 0x0004, CLOEXEC = 0x00100000, } -- sigaction, note renamed SIGACT from SIG_ c.SIGACT = strflag { ERR = -1, DFL = 0, IGN = 1, HOLD = 3, } c.SIGEV = strflag { NONE = 0, SIGNAL = 1, THREAD = 2, KEVENT = 3, THREAD_ID = 4, } c.SIG = strflag { HUP = 1, INT = 2, QUIT = 3, ILL = 4, TRAP = 5, ABRT = 6, EMT = 7, FPE = 8, KILL = 9, BUS = 10, SEGV = 11, SYS = 12, PIPE = 13, ALRM = 14, TERM = 15, URG = 16, STOP = 17, TSTP = 18, CONT = 19, CHLD = 20, TTIN = 21, TTOU = 22, IO = 23, XCPU = 24, XFSZ = 25, VTALRM = 26, PROF = 27, WINCH = 28, INFO = 29, USR1 = 30, USR2 = 31, THR = 32, } if version >=10 then c.SIG.LIBRT = 33 end c.SIG.LWP = c.SIG.THR c.EXIT = strflag { SUCCESS = 0, FAILURE = 1, } c.OK = charflags { F = 0, X = 0x01, W = 0x02, R = 0x04, } c.MODE = modeflags { SUID = octal('04000'), SGID = octal('02000'), STXT = octal('01000'), RWXU = octal('00700'), RUSR = octal('00400'), WUSR = octal('00200'), XUSR = octal('00100'), RWXG = octal('00070'), RGRP = octal('00040'), WGRP = octal('00020'), XGRP = octal('00010'), RWXO = octal('00007'), ROTH = octal('00004'), WOTH = octal('00002'), XOTH = octal('00001'), } c.SEEK = strflag { SET = 0, CUR = 1, END = 2, DATA = 3, HOLE = 4, } c.SOCK = multiflags { STREAM = 1, DGRAM = 2, RAW = 3, RDM = 4, SEQPACKET = 5, } if version >= 10 then c.SOCK.CLOEXEC = 0x10000000 c.SOCK.NONBLOCK = 0x20000000 end c.SOL = strflag { SOCKET = 0xffff, } c.POLL = multiflags { IN = 0x0001, PRI = 0x0002, OUT = 0x0004, RDNORM = 0x0040, RDBAND = 0x0080, WRBAND = 0x0100, INIGNEOF = 0x2000, ERR = 0x0008, HUP = 0x0010, NVAL = 0x0020, } c.POLL.WRNORM = c.POLL.OUT c.POLL.STANDARD = c.POLL["IN,PRI,OUT,RDNORM,RDBAND,WRBAND,ERR,HUP,NVAL"] c.AT_FDCWD = atflag { FDCWD = -100, } c.AT = multiflags { EACCESS = 0x100, SYMLINK_NOFOLLOW = 0x200, SYMLINK_FOLLOW = 0x400, REMOVEDIR = 0x800, } c.S_I = modeflags { FMT = octal('0170000'), FWHT = octal('0160000'), FSOCK = octal('0140000'), FLNK = octal('0120000'), FREG = octal('0100000'), FBLK = octal('0060000'), FDIR = octal('0040000'), FCHR = octal('0020000'), FIFO = octal('0010000'), SUID = octal('0004000'), SGID = octal('0002000'), SVTX = octal('0001000'), STXT = octal('0001000'), RWXU = octal('00700'), RUSR = octal('00400'), WUSR = octal('00200'), XUSR = octal('00100'), RWXG = octal('00070'), RGRP = octal('00040'), WGRP = octal('00020'), XGRP = octal('00010'), RWXO = octal('00007'), ROTH = octal('00004'), WOTH = octal('00002'), XOTH = octal('00001'), } c.S_I.READ = c.S_I.RUSR c.S_I.WRITE = c.S_I.WUSR c.S_I.EXEC = c.S_I.XUSR c.PROT = multiflags { NONE = 0x0, READ = 0x1, WRITE = 0x2, EXEC = 0x4, } c.MAP = multiflags { SHARED = 0x0001, PRIVATE = 0x0002, FILE = 0x0000, FIXED = 0x0010, RENAME = 0x0020, NORESERVE = 0x0040, RESERVED0080 = 0x0080, RESERVED0100 = 0x0100, HASSEMAPHORE = 0x0200, STACK = 0x0400, NOSYNC = 0x0800, ANON = 0x1000, NOCORE = 0x00020000, -- TODO add aligned maps in } if abi.abi64 and version >= 10 then c.MAP["32BIT"] = 0x00080000 end c.MCL = strflag { CURRENT = 0x01, FUTURE = 0x02, } -- flags to `msync'. - note was MS_ renamed to MSYNC_ c.MSYNC = multiflags { SYNC = 0x0000, ASYNC = 0x0001, INVALIDATE = 0x0002, } c.MADV = strflag { NORMAL = 0, RANDOM = 1, SEQUENTIAL = 2, WILLNEED = 3, DONTNEED = 4, FREE = 5, NOSYNC = 6, AUTOSYNC = 7, NOCORE = 8, CORE = 9, PROTECT = 10, } c.IPPROTO = strflag { IP = 0, HOPOPTS = 0, ICMP = 1, IGMP = 2, GGP = 3, IPV4 = 4, IPIP = 4, TCP = 6, ST = 7, EGP = 8, PIGP = 9, RCCMON = 10, NVPII = 11, PUP = 12, ARGUS = 13, EMCON = 14, XNET = 15, CHAOS = 16, UDP = 17, MUX = 18, MEAS = 19, HMP = 20, PRM = 21, IDP = 22, TRUNK1 = 23, TRUNK2 = 24, LEAF1 = 25, LEAF2 = 26, RDP = 27, IRTP = 28, TP = 29, BLT = 30, NSP = 31, INP = 32, SEP = 33, ["3PC"] = 34, IDPR = 35, XTP = 36, DDP = 37, CMTP = 38, TPXX = 39, IL = 40, IPV6 = 41, SDRP = 42, ROUTING = 43, FRAGMENT = 44, IDRP = 45, RSVP = 46, GRE = 47, MHRP = 48, BHA = 49, ESP = 50, AH = 51, INLSP = 52, SWIPE = 53, NHRP = 54, MOBILE = 55, TLSP = 56, SKIP = 57, ICMPV6 = 58, NONE = 59, DSTOPTS = 60, AHIP = 61, CFTP = 62, HELLO = 63, SATEXPAK = 64, KRYPTOLAN = 65, RVD = 66, IPPC = 67, ADFS = 68, SATMON = 69, VISA = 70, IPCV = 71, CPNX = 72, CPHB = 73, WSN = 74, PVP = 75, BRSATMON = 76, ND = 77, WBMON = 78, WBEXPAK = 79, EON = 80, VMTP = 81, SVMTP = 82, VINES = 83, TTP = 84, IGP = 85, DGP = 86, TCF = 87, IGRP = 88, OSPFIGP = 89, SRPC = 90, LARP = 91, MTP = 92, AX25 = 93, IPEIP = 94, MICP = 95, SCCSP = 96, ETHERIP = 97, ENCAP = 98, APES = 99, GMTP = 100, IPCOMP = 108, SCTP = 132, MH = 135, PIM = 103, CARP = 112, PGM = 113, MPLS = 137, PFSYNC = 240, RAW = 255, } c.SCM = multiflags { RIGHTS = 0x01, TIMESTAMP = 0x02, CREDS = 0x03, BINTIME = 0x04, } c.F = strflag { DUPFD = 0, GETFD = 1, SETFD = 2, GETFL = 3, SETFL = 4, GETOWN = 5, SETOWN = 6, OGETLK = 7, OSETLK = 8, OSETLKW = 9, DUP2FD = 10, GETLK = 11, SETLK = 12, SETLKW = 13, SETLK_REMOTE= 14, READAHEAD = 15, RDAHEAD = 16, DUPFD_CLOEXEC= 17, DUP2FD_CLOEXEC= 18, } c.FD = multiflags { CLOEXEC = 1, } -- note changed from F_ to FCNTL_LOCK c.FCNTL_LOCK = strflag { RDLCK = 1, UNLCK = 2, WRLCK = 3, UNLCKSYS = 4, CANCEL = 5, } -- lockf, changed from F_ to LOCKF_ c.LOCKF = strflag { ULOCK = 0, LOCK = 1, TLOCK = 2, TEST = 3, } -- for flock (2) c.LOCK = multiflags { SH = 0x01, EX = 0x02, NB = 0x04, UN = 0x08, } c.W = multiflags { NOHANG = 1, UNTRACED = 2, CONTINUED = 4, NOWAIT = 8, EXITED = 16, TRAPPED = 32, LINUXCLONE = 0x80000000, } c.W.STOPPED = c.W.UNTRACED -- waitpid and wait4 pid c.WAIT = strflag { ANY = -1, MYPGRP = 0, } c.MSG = multiflags { OOB = 0x1, PEEK = 0x2, DONTROUTE = 0x4, EOR = 0x8, TRUNC = 0x10, CTRUNC = 0x20, WAITALL = 0x40, DONTWAIT = 0x80, EOF = 0x100, NOTIFICATION = 0x2000, NBIO = 0x4000, COMPAT = 0x8000, NOSIGNAL = 0x20000, } if version >= 10 then c.MSG.CMSG_CLOEXEC = 0x40000 end c.PC = strflag { LINK_MAX = 1, MAX_CANON = 2, MAX_INPUT = 3, NAME_MAX = 4, PATH_MAX = 5, PIPE_BUF = 6, CHOWN_RESTRICTED = 7, NO_TRUNC = 8, VDISABLE = 9, ALLOC_SIZE_MIN = 10, FILESIZEBITS = 12, REC_INCR_XFER_SIZE= 14, REC_MAX_XFER_SIZE = 15, REC_MIN_XFER_SIZE = 16, REC_XFER_ALIGN = 17, SYMLINK_MAX = 18, MIN_HOLE_SIZE = 21, ASYNC_IO = 53, PRIO_IO = 54, SYNC_IO = 55, ACL_EXTENDED = 59, ACL_PATH_MAX = 60, CAP_PRESENT = 61, INF_PRESENT = 62, MAC_PRESENT = 63, ACL_NFS4 = 64, } -- getpriority, setpriority flags c.PRIO = strflag { PROCESS = 0, PGRP = 1, USER = 2, MIN = -20, -- TODO useful to have for other OSs MAX = 20, } c.RUSAGE = strflag { SELF = 0, CHILDREN = -1, THREAD = 1, } c.SOMAXCONN = 128 c.SO = strflag { DEBUG = 0x0001, ACCEPTCONN = 0x0002, REUSEADDR = 0x0004, KEEPALIVE = 0x0008, DONTROUTE = 0x0010, BROADCAST = 0x0020, USELOOPBACK = 0x0040, LINGER = 0x0080, OOBINLINE = 0x0100, REUSEPORT = 0x0200, TIMESTAMP = 0x0400, NOSIGPIPE = 0x0800, ACCEPTFILTER = 0x1000, BINTIME = 0x2000, NO_OFFLOAD = 0x4000, NO_DDP = 0x8000, SNDBUF = 0x1001, RCVBUF = 0x1002, SNDLOWAT = 0x1003, RCVLOWAT = 0x1004, SNDTIMEO = 0x1005, RCVTIMEO = 0x1006, ERROR = 0x1007, TYPE = 0x1008, LABEL = 0x1009, PEERLABEL = 0x1010, LISTENQLIMIT = 0x1011, LISTENQLEN = 0x1012, LISTENINCQLEN= 0x1013, SETFIB = 0x1014, USER_COOKIE = 0x1015, PROTOCOL = 0x1016, } c.SO.PROTOTYPE = c.SO.PROTOCOL c.DT = strflag { UNKNOWN = 0, FIFO = 1, CHR = 2, DIR = 4, BLK = 6, REG = 8, LNK = 10, SOCK = 12, WHT = 14, } c.IP = strflag { OPTIONS = 1, HDRINCL = 2, TOS = 3, TTL = 4, RECVOPTS = 5, RECVRETOPTS = 6, RECVDSTADDR = 7, RETOPTS = 8, MULTICAST_IF = 9, MULTICAST_TTL = 10, MULTICAST_LOOP = 11, ADD_MEMBERSHIP = 12, DROP_MEMBERSHIP = 13, MULTICAST_VIF = 14, RSVP_ON = 15, RSVP_OFF = 16, RSVP_VIF_ON = 17, RSVP_VIF_OFF = 18, PORTRANGE = 19, RECVIF = 20, IPSEC_POLICY = 21, FAITH = 22, ONESBCAST = 23, BINDANY = 24, FW_TABLE_ADD = 40, FW_TABLE_DEL = 41, FW_TABLE_FLUSH = 42, FW_TABLE_GETSIZE = 43, FW_TABLE_LIST = 44, FW3 = 48, DUMMYNET3 = 49, FW_ADD = 50, FW_DEL = 51, FW_FLUSH = 52, FW_ZERO = 53, FW_GET = 54, FW_RESETLOG = 55, FW_NAT_CFG = 56, FW_NAT_DEL = 57, FW_NAT_GET_CONFIG = 58, FW_NAT_GET_LOG = 59, DUMMYNET_CONFIGURE = 60, DUMMYNET_DEL = 61, DUMMYNET_FLUSH = 62, DUMMYNET_GET = 64, RECVTTL = 65, MINTTL = 66, DONTFRAG = 67, RECVTOS = 68, ADD_SOURCE_MEMBERSHIP = 70, DROP_SOURCE_MEMBERSHIP = 71, BLOCK_SOURCE = 72, UNBLOCK_SOURCE = 73, } c.IP.SENDSRCADDR = c.IP.RECVDSTADDR -- Baud rates just the identity function other than EXTA, EXTB c.B = strflag { EXTA = 19200, EXTB = 38400, } c.CC = strflag { VEOF = 0, VEOL = 1, VEOL2 = 2, VERASE = 3, VWERASE = 4, VKILL = 5, VREPRINT = 6, VINTR = 8, VQUIT = 9, VSUSP = 10, VDSUSP = 11, VSTART = 12, VSTOP = 13, VLNEXT = 14, VDISCARD = 15, VMIN = 16, VTIME = 17, VSTATUS = 18, } c.IFLAG = multiflags { IGNBRK = 0x00000001, BRKINT = 0x00000002, IGNPAR = 0x00000004, PARMRK = 0x00000008, INPCK = 0x00000010, ISTRIP = 0x00000020, INLCR = 0x00000040, IGNCR = 0x00000080, ICRNL = 0x00000100, IXON = 0x00000200, IXOFF = 0x00000400, IXANY = 0x00000800, IMAXBEL = 0x00002000, } c.OFLAG = multiflags { OPOST = 0x00000001, ONLCR = 0x00000002, OXTABS = 0x00000004, ONOEOT = 0x00000008, OCRNL = 0x00000010, ONOCR = 0x00000020, ONLRET = 0x00000040, } c.CFLAG = multiflags { CIGNORE = 0x00000001, CSIZE = 0x00000300, CS5 = 0x00000000, CS6 = 0x00000100, CS7 = 0x00000200, CS8 = 0x00000300, CSTOPB = 0x00000400, CREAD = 0x00000800, PARENB = 0x00001000, PARODD = 0x00002000, HUPCL = 0x00004000, CLOCAL = 0x00008000, CCTS_OFLOW = 0x00010000, CRTS_IFLOW = 0x00020000, CDTR_IFLOW = 0x00040000, CDSR_OFLOW = 0x00080000, CCAR_OFLOW = 0x00100000, } c.CFLAG.CRTSCTS = c.CFLAG.CCTS_OFLOW + c.CFLAG.CRTS_IFLOW c.LFLAG = multiflags { ECHOKE = 0x00000001, ECHOE = 0x00000002, ECHOK = 0x00000004, ECHO = 0x00000008, ECHONL = 0x00000010, ECHOPRT = 0x00000020, ECHOCTL = 0x00000040, ISIG = 0x00000080, ICANON = 0x00000100, ALTWERASE = 0x00000200, IEXTEN = 0x00000400, EXTPROC = 0x00000800, TOSTOP = 0x00400000, FLUSHO = 0x00800000, NOKERNINFO = 0x02000000, PENDIN = 0x20000000, NOFLSH = 0x80000000, } c.TCSA = multiflags { -- this is another odd one, where you can have one flag plus SOFT NOW = 0, DRAIN = 1, FLUSH = 2, SOFT = 0x10, } -- tcflush(), renamed from TC to TCFLUSH c.TCFLUSH = strflag { IFLUSH = 1, OFLUSH = 2, IOFLUSH = 3, } -- termios - tcflow() and TCXONC use these. renamed from TC to TCFLOW c.TCFLOW = strflag { OOFF = 1, OON = 2, IOFF = 3, ION = 4, } -- for chflags and stat. note these have no prefix c.CHFLAGS = multiflags { UF_NODUMP = 0x00000001, UF_IMMUTABLE = 0x00000002, UF_APPEND = 0x00000004, UF_OPAQUE = 0x00000008, UF_NOUNLINK = 0x00000010, SF_ARCHIVED = 0x00010000, SF_IMMUTABLE = 0x00020000, SF_APPEND = 0x00040000, SF_NOUNLINK = 0x00100000, SF_SNAPSHOT = 0x00200000, } c.CHFLAGS.IMMUTABLE = c.CHFLAGS.UF_IMMUTABLE + c.CHFLAGS.SF_IMMUTABLE c.CHFLAGS.APPEND = c.CHFLAGS.UF_APPEND + c.CHFLAGS.SF_APPEND c.CHFLAGS.OPAQUE = c.CHFLAGS.UF_OPAQUE c.CHFLAGS.NOUNLINK = c.CHFLAGS.UF_NOUNLINK + c.CHFLAGS.SF_NOUNLINK if version >=10 then c.CHFLAGS.UF_SYSTEM = 0x00000080 c.CHFLAGS.UF_SPARSE = 0x00000100 c.CHFLAGS.UF_OFFLINE = 0x00000200 c.CHFLAGS.UF_REPARSE = 0x00000400 c.CHFLAGS.UF_ARCHIVE = 0x00000800 c.CHFLAGS.UF_READONLY = 0x00001000 c.CHFLAGS.UF_HIDDEN = 0x00008000 end c.TCP = strflag { NODELAY = 1, MAXSEG = 2, NOPUSH = 4, NOOPT = 8, MD5SIG = 16, INFO = 32, CONGESTION = 64, KEEPINIT = 128, KEEPIDLE = 256, KEEPINTVL = 512, KEEPCNT = 1024, } c.RB = multiflags { AUTOBOOT = 0, ASKNAME = 0x001, SINGLE = 0x002, NOSYNC = 0x004, HALT = 0x008, INITNAME = 0x010, DFLTROOT = 0x020, KDB = 0x040, RDONLY = 0x080, DUMP = 0x100, MINIROOT = 0x200, VERBOSE = 0x800, SERIAL = 0x1000, CDROM = 0x2000, POWEROFF = 0x4000, GDB = 0x8000, MUTE = 0x10000, SELFTEST = 0x20000, RESERVED1 = 0x40000, RESERVED2 = 0x80000, PAUSE = 0x100000, MULTIPLE = 0x20000000, BOOTINFO = 0x80000000, } -- kqueue c.EV = multiflags { ADD = 0x0001, DELETE = 0x0002, ENABLE = 0x0004, DISABLE = 0x0008, ONESHOT = 0x0010, CLEAR = 0x0020, RECEIPT = 0x0040, DISPATCH = 0x0080, SYSFLAGS = 0xF000, FLAG1 = 0x2000, EOF = 0x8000, ERROR = 0x4000, } if version >= 10 then c.EV.DROP = 0x1000 end c.EVFILT = strflag { READ = -1, WRITE = -2, AIO = -3, VNODE = -4, PROC = -5, SIGNAL = -6, TIMER = -7, FS = -9, LIO = -10, USER = -11, SYSCOUNT = 11, } c.NOTE = multiflags { -- user FFNOP = 0x00000000, FFAND = 0x40000000, FFOR = 0x80000000, FFCOPY = 0xc0000000, FFCTRLMASK = 0xc0000000, FFLAGSMASK = 0x00ffffff, TRIGGER = 0x01000000, -- read and write LOWAT = 0x0001, -- vnode DELETE = 0x0001, WRITE = 0x0002, EXTEND = 0x0004, ATTRIB = 0x0008, LINK = 0x0010, RENAME = 0x0020, REVOKE = 0x0040, -- proc EXIT = 0x80000000, FORK = 0x40000000, EXEC = 0x20000000, PCTRLMASK = 0xf0000000, PDATAMASK = 0x000fffff, TRACK = 0x00000001, TRACKERR = 0x00000002, CHILD = 0x00000004, } c.SHM = strflag { ANON = charp(1), } c.PD = multiflags { DAEMON = 0x00000001, } c.ITIMER = strflag { REAL = 0, VIRTUAL = 1, PROF = 2, } c.SA = multiflags { ONSTACK = 0x0001, RESTART = 0x0002, RESETHAND = 0x0004, NOCLDSTOP = 0x0008, NODEFER = 0x0010, NOCLDWAIT = 0x0020, SIGINFO = 0x0040, } -- ipv6 sockopts c.IPV6 = strflag { SOCKOPT_RESERVED1 = 3, UNICAST_HOPS = 4, MULTICAST_IF = 9, MULTICAST_HOPS = 10, MULTICAST_LOOP = 11, JOIN_GROUP = 12, LEAVE_GROUP = 13, PORTRANGE = 14, --ICMP6_FILTER = 18, -- not namespaced as IPV6 CHECKSUM = 26, V6ONLY = 27, IPSEC_POLICY = 28, FAITH = 29, RTHDRDSTOPTS = 35, RECVPKTINFO = 36, RECVHOPLIMIT = 37, RECVRTHDR = 38, RECVHOPOPTS = 39, RECVDSTOPTS = 40, USE_MIN_MTU = 42, RECVPATHMTU = 43, PATHMTU = 44, PKTINFO = 46, HOPLIMIT = 47, NEXTHOP = 48, HOPOPTS = 49, DSTOPTS = 50, RTHDR = 51, RECVTCLASS = 57, TCLASS = 61, DONTFRAG = 62, } c.CLOCK = strflag { REALTIME = 0, VIRTUAL = 1, PROF = 2, MONOTONIC = 4, UPTIME = 5, UPTIME_PRECISE = 7, UPTIME_FAST = 8, REALTIME_PRECISE = 9, REALTIME_FAST = 10, MONOTONIC_PRECISE = 11, MONOTONIC_FAST = 12, SECOND = 13, THREAD_CPUTIME_ID = 14, PROCESS_CPUTIME_ID = 15, } c.EXTATTR_NAMESPACE = strflag { EMPTY = 0x00000000, USER = 0x00000001, SYSTEM = 0x00000002, } -- TODO mount flag is an int, so ULL is odd, but these are flags too... -- TODO many flags missing, plus FreeBSD has a lot more mount complexities c.MNT = strflag { RDONLY = 0x0000000000000001ULL, SYNCHRONOUS = 0x0000000000000002ULL, NOEXEC = 0x0000000000000004ULL, NOSUID = 0x0000000000000008ULL, NFS4ACLS = 0x0000000000000010ULL, UNION = 0x0000000000000020ULL, ASYNC = 0x0000000000000040ULL, SUIDDIR = 0x0000000000100000ULL, SOFTDEP = 0x0000000000200000ULL, NOSYMFOLLOW = 0x0000000000400000ULL, GJOURNAL = 0x0000000002000000ULL, MULTILABEL = 0x0000000004000000ULL, ACLS = 0x0000000008000000ULL, NOATIME = 0x0000000010000000ULL, NOCLUSTERR = 0x0000000040000000ULL, NOCLUSTERW = 0x0000000080000000ULL, SUJ = 0x0000000100000000ULL, FORCE = 0x0000000000080000ULL, } c.CTL = strflag { UNSPEC = 0, KERN = 1, VM = 2, VFS = 3, NET = 4, DEBUG = 5, HW = 6, MACHDEP = 7, USER = 8, P1003_1B = 9, MAXID = 10, } c.KERN = strflag { OSTYPE = 1, OSRELEASE = 2, OSREV = 3, VERSION = 4, MAXVNODES = 5, MAXPROC = 6, MAXFILES = 7, ARGMAX = 8, SECURELVL = 9, HOSTNAME = 10, HOSTID = 11, CLOCKRATE = 12, VNODE = 13, PROC = 14, FILE = 15, PROF = 16, POSIX1 = 17, NGROUPS = 18, JOB_CONTROL = 19, SAVED_IDS = 20, BOOTTIME = 21, NISDOMAINNAME = 22, UPDATEINTERVAL = 23, OSRELDATE = 24, NTP_PLL = 25, BOOTFILE = 26, MAXFILESPERPROC = 27, MAXPROCPERUID = 28, DUMPDEV = 29, IPC = 30, DUMMY = 31, PS_STRINGS = 32, USRSTACK = 33, LOGSIGEXIT = 34, IOV_MAX = 35, HOSTUUID = 36, ARND = 37, MAXID = 38, } if version >= 10 then -- not supporting on freebsd 9 as different ABI, recommend upgrade to use local function CAPRIGHT(idx, b) return bit.bor64(bit.lshift64(1, 57 + idx), b) end c.CAP = multiflags {} -- index 0 c.CAP.READ = CAPRIGHT(0, 0x0000000000000001ULL) c.CAP.WRITE = CAPRIGHT(0, 0x0000000000000002ULL) c.CAP.SEEK_TELL = CAPRIGHT(0, 0x0000000000000004ULL) c.CAP.SEEK = bit.bor64(c.CAP.SEEK_TELL, 0x0000000000000008ULL) c.CAP.PREAD = bit.bor64(c.CAP.SEEK, c.CAP.READ) c.CAP.PWRITE = bit.bor64(c.CAP.SEEK, c.CAP.WRITE) c.CAP.MMAP = CAPRIGHT(0, 0x0000000000000010ULL) c.CAP.MMAP_R = bit.bor64(c.CAP.MMAP, c.CAP.SEEK, c.CAP.READ) c.CAP.MMAP_W = bit.bor64(c.CAP.MMAP, c.CAP.SEEK, c.CAP.WRITE) c.CAP.MMAP_X = bit.bor64(c.CAP.MMAP, c.CAP.SEEK, 0x0000000000000020ULL) c.CAP.MMAP_RW = bit.bor64(c.CAP.MMAP_R, c.CAP.MMAP_W) c.CAP.MMAP_RX = bit.bor64(c.CAP.MMAP_R, c.CAP.MMAP_X) c.CAP.MMAP_WX = bit.bor64(c.CAP.MMAP_W, c.CAP.MMAP_X) c.CAP.MMAP_RWX = bit.bor64(c.CAP.MMAP_R, c.CAP.MMAP_W, c.CAP.MMAP_X) c.CAP.CREATE = CAPRIGHT(0, 0x0000000000000040ULL) c.CAP.FEXECVE = CAPRIGHT(0, 0x0000000000000080ULL) c.CAP.FSYNC = CAPRIGHT(0, 0x0000000000000100ULL) c.CAP.FTRUNCATE = CAPRIGHT(0, 0x0000000000000200ULL) c.CAP.LOOKUP = CAPRIGHT(0, 0x0000000000000400ULL) c.CAP.FCHDIR = CAPRIGHT(0, 0x0000000000000800ULL) c.CAP.FCHFLAGS = CAPRIGHT(0, 0x0000000000001000ULL) c.CAP.CHFLAGSAT = bit.bor64(c.CAP.FCHFLAGS, c.CAP.LOOKUP) c.CAP.FCHMOD = CAPRIGHT(0, 0x0000000000002000ULL) c.CAP.FCHMODAT = bit.bor64(c.CAP.FCHMOD, c.CAP.LOOKUP) c.CAP.FCHOWN = CAPRIGHT(0, 0x0000000000004000ULL) c.CAP.FCHOWNAT = bit.bor64(c.CAP.FCHOWN, c.CAP.LOOKUP) c.CAP.FCNTL = CAPRIGHT(0, 0x0000000000008000ULL) c.CAP.FLOCK = CAPRIGHT(0, 0x0000000000010000ULL) c.CAP.FPATHCONF = CAPRIGHT(0, 0x0000000000020000ULL) c.CAP.FSCK = CAPRIGHT(0, 0x0000000000040000ULL) c.CAP.FSTAT = CAPRIGHT(0, 0x0000000000080000ULL) c.CAP.FSTATAT = bit.bor64(c.CAP.FSTAT, c.CAP.LOOKUP) c.CAP.FSTATFS = CAPRIGHT(0, 0x0000000000100000ULL) c.CAP.FUTIMES = CAPRIGHT(0, 0x0000000000200000ULL) c.CAP.FUTIMESAT = bit.bor64(c.CAP.FUTIMES, c.CAP.LOOKUP) c.CAP.LINKAT = bit.bor64(c.CAP.LOOKUP, 0x0000000000400000ULL) c.CAP.MKDIRAT = bit.bor64(c.CAP.LOOKUP, 0x0000000000800000ULL) c.CAP.MKFIFOAT = bit.bor64(c.CAP.LOOKUP, 0x0000000001000000ULL) c.CAP.MKNODAT = bit.bor64(c.CAP.LOOKUP, 0x0000000002000000ULL) c.CAP.RENAMEAT = bit.bor64(c.CAP.LOOKUP, 0x0000000004000000ULL) c.CAP.SYMLINKAT = bit.bor64(c.CAP.LOOKUP, 0x0000000008000000ULL) c.CAP.UNLINKAT = bit.bor64(c.CAP.LOOKUP, 0x0000000010000000ULL) c.CAP.ACCEPT = CAPRIGHT(0, 0x0000000020000000ULL) c.CAP.BIND = CAPRIGHT(0, 0x0000000040000000ULL) c.CAP.CONNECT = CAPRIGHT(0, 0x0000000080000000ULL) c.CAP.GETPEERNAME = CAPRIGHT(0, 0x0000000100000000ULL) c.CAP.GETSOCKNAME = CAPRIGHT(0, 0x0000000200000000ULL) c.CAP.GETSOCKOPT = CAPRIGHT(0, 0x0000000400000000ULL) c.CAP.LISTEN = CAPRIGHT(0, 0x0000000800000000ULL) c.CAP.PEELOFF = CAPRIGHT(0, 0x0000001000000000ULL) c.CAP.RECV = c.CAP.READ c.CAP.SEND = c.CAP.WRITE c.CAP.SETSOCKOPT = CAPRIGHT(0, 0x0000002000000000ULL) c.CAP.SHUTDOWN = CAPRIGHT(0, 0x0000004000000000ULL) c.CAP.BINDAT = bit.bor64(c.CAP.LOOKUP, 0x0000008000000000ULL) c.CAP.CONNECTAT = bit.bor64(c.CAP.LOOKUP, 0x0000010000000000ULL) c.CAP.SOCK_CLIENT = bit.bor64(c.CAP.CONNECT, c.CAP.GETPEERNAME, c.CAP.GETSOCKNAME, c.CAP.GETSOCKOPT, c.CAP.PEELOFF, c.CAP.RECV, c.CAP.SEND, c.CAP.SETSOCKOPT, c.CAP.SHUTDOWN) c.CAP.SOCK_SERVER = bit.bor64(c.CAP.ACCEPT, c.CAP.BIND, c.CAP.GETPEERNAME, c.CAP.GETSOCKNAME, c.CAP.GETSOCKOPT, c.CAP.LISTEN, c.CAP.PEELOFF, c.CAP.RECV, c.CAP.SEND, c.CAP.SETSOCKOPT, c.CAP.SHUTDOWN) c.CAP.ALL0 = CAPRIGHT(0, 0x0000007FFFFFFFFFULL) c.CAP.UNUSED0_40 = CAPRIGHT(0, 0x0000008000000000ULL) c.CAP_UNUSED0_57 = CAPRIGHT(0, 0x0100000000000000ULL) -- index 1 c.CAP.MAC_GET = CAPRIGHT(1, 0x0000000000000001ULL) c.CAP.MAC_SET = CAPRIGHT(1, 0x0000000000000002ULL) c.CAP.SEM_GETVALUE = CAPRIGHT(1, 0x0000000000000004ULL) c.CAP.SEM_POST = CAPRIGHT(1, 0x0000000000000008ULL) c.CAP.SEM_WAIT = CAPRIGHT(1, 0x0000000000000010ULL) c.CAP.EVENT = CAPRIGHT(1, 0x0000000000000020ULL) c.CAP.KQUEUE_EVENT = CAPRIGHT(1, 0x0000000000000040ULL) c.CAP.IOCTL = CAPRIGHT(1, 0x0000000000000080ULL) c.CAP.TTYHOOK = CAPRIGHT(1, 0x0000000000000100ULL) c.CAP.PDGETPID = CAPRIGHT(1, 0x0000000000000200ULL) c.CAP.PDWAIT = CAPRIGHT(1, 0x0000000000000400ULL) c.CAP.PDKILL = CAPRIGHT(1, 0x0000000000000800ULL) c.CAP.EXTATTR_DELETE = CAPRIGHT(1, 0x0000000000001000ULL) c.CAP.EXTATTR_GET = CAPRIGHT(1, 0x0000000000002000ULL) c.CAP.EXTATTR_LIST = CAPRIGHT(1, 0x0000000000004000ULL) c.CAP.EXTATTR_SET = CAPRIGHT(1, 0x0000000000008000ULL) c.CAP_ACL_CHECK = CAPRIGHT(1, 0x0000000000010000ULL) c.CAP_ACL_DELETE = CAPRIGHT(1, 0x0000000000020000ULL) c.CAP_ACL_GET = CAPRIGHT(1, 0x0000000000040000ULL) c.CAP_ACL_SET = CAPRIGHT(1, 0x0000000000080000ULL) c.CAP_KQUEUE_CHANGE = CAPRIGHT(1, 0x0000000000100000ULL) c.CAP_KQUEUE = bit.bor64(c.CAP.KQUEUE_EVENT, c.CAP.KQUEUE_CHANGE) c.CAP_ALL1 = CAPRIGHT(1, 0x00000000001FFFFFULL) c.CAP_UNUSED1_22 = CAPRIGHT(1, 0x0000000000200000ULL) c.CAP_UNUSED1_57 = CAPRIGHT(1, 0x0100000000000000ULL) c.CAP_FCNTL = multiflags { GETFL = bit.lshift(1, c.F.GETFL), SETFL = bit.lshift(1, c.F.SETFL), GETOWN = bit.lshift(1, c.F.GETOWN), SETOWN = bit.lshift(1, c.F.SETOWN), } c.CAP_FCNTL.ALL = bit.bor(c.CAP_FCNTL.GETFL, c.CAP_FCNTL.SETFL, c.CAP_FCNTL.GETOWN, c.CAP_FCNTL.SETOWN) c.CAP_IOCTLS = multiflags { ALL = h.longmax, } c.CAP_RIGHTS_VERSION = 0 -- we do not understand others end -- freebsd >= 10 return c
apache-2.0
nesstea/darkstar
scripts/zones/Abyssea-Misareaux/Zone.lua
33
1482
----------------------------------- -- -- Zone: Abyssea - Misareaux -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Misareaux/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Abyssea-Misareaux/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then -- player:setPos(670,-15,318,119); end if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED and player:getVar("1stTimeAyssea") == 0) then player:setVar("1stTimeAyssea",1); 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
UnfortunateFruit/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Upital-Lupital.lua
38
1056
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Upital-Lupital -- Type: Standard NPC -- @zone: 94 -- @pos -57.809 -13.339 122.753 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01b7); 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
UnfortunateFruit/darkstar
scripts/zones/Leafallia/Zone.lua
34
1267
----------------------------------- -- -- Zone: Leafallia -- ----------------------------------- package.loaded["scripts/zones/Leafallia/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Leafallia/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-1,0,0,151); 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
Verdex/min
util.lua
1
2345
function d( v ) if type( v ) == "string" then return '"' .. v .. '"' elseif type( v ) == "boolean" then return tostring( v ) elseif type( v ) == "number" then return "" .. v elseif type( v ) == "table" then local t = {} for k, val in pairs( v ) do if type( k ) == "number" then t[#t+1] = d( val ) elseif type( k ) == "string" then t[#t+1] = k .. " = " .. d( val ) else t[#t+1] = d( k ) .. " = " .. d( val ) end end local listlet = table.concat( t, ", " ) return "{ " .. listlet .. " }" else return "some " .. type( v ) end end local tabs = 0 function f( v ) local dis = function ( h ) if type( h ) == "table" then tabs = tabs + 1 local o = f( h ) tabs = tabs - 1 return o elseif type( h ) == "string" then return '"' .. h .. '"' elseif type( h ) == "number" then return "" .. h elseif type( h ) == "boolean" then return tostring( h ) else error "unsupported type" end end if type( v ) ~= "table" then error "f needs a table" end local vs = {} for i, val in ipairs( v ) do if type( val ) == "table" then vs[#vs + 1] = "\n" .. string.rep(" ", tabs) .. i .. ": " .. dis( val ) else vs[#vs + 1] = i .. ": " .. dis( val ) end end local new_line = false for _, val in ipairs( vs ) do if #val > 15 then new_line = true break end end if #vs > 0 then if new_line then return table.concat( vs, ",\n" .. string.rep( " ", tabs ) ) else return table.concat( vs, ", " ) end end for k, val in pairs( v ) do vs[#vs + 1] = k .. ": " .. dis( val ) end for _, val in ipairs( vs ) do if #val > 15 then new_line = true break end end if #vs > 0 then if new_line then return table.concat( vs, ",\n" .. string.rep( " ", tabs ) ) else return table.concat( vs, ", " ) end end return "<EMPTY>" end
mit
UnfortunateFruit/darkstar
scripts/globals/items/bowl_of_dhalmel_stew.lua
35
1749
----------------------------------------- -- ID: 4433 -- Item: Bowl of Dhalmel Stew -- Food Effect: 180Min, All Races ----------------------------------------- -- Strength 4 -- Agility 1 -- Vitality 2 -- Intelligence -2 -- Attack % 25 -- Attack Cap 45 -- Ranged ATT % 25 -- Ranged ATT Cap 45 ----------------------------------------- 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,4433); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 4); target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, 2); target:addMod(MOD_INT, -2); target:addMod(MOD_FOOD_ATTP, 25); target:addMod(MOD_FOOD_ATT_CAP, 45); target:addMod(MOD_FOOD_RATTP, 25); target:addMod(MOD_FOOD_RATT_CAP, 45); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 4); target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, 2); target:delMod(MOD_INT, -2); target:delMod(MOD_FOOD_ATTP, 25); target:delMod(MOD_FOOD_ATT_CAP, 45); target:delMod(MOD_FOOD_RATTP, 25); target:delMod(MOD_FOOD_RATT_CAP, 45); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Northern_San_dOria/npcs/Pala_Korin.lua
36
1428
----------------------------------- -- Area: Northern San d'Oria -- NPC: Pala_Korin -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x22B); 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
nesstea/darkstar
scripts/globals/items/simit_+1.lua
19
1287
----------------------------------------- -- ID: 5597 -- Item: simit_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 18 -- Vitality 4 -- Defense 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5597); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 18); target:addMod(MOD_VIT, 4); target:addMod(MOD_DEF, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 18); target:delMod(MOD_VIT, 4); target:delMod(MOD_DEF, 2); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/aspir_knife.lua
15
1103
----------------------------------------- -- ID: 16509 -- Item: Aspir Knife -- Additional effect: MP Drain ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance or target:isUndead()) then return 0,0,0; else local drain = math.random(1,3); local params = {}; params.bonusmab = 0; params.includemab = false; -- drain = addBonusesAbility(player, ELE_DARK, target, drain, params); drain = drain * applyResistanceAddEffect(player,target,ELE_DARK,0); drain = adjustForTarget(target,drain,ELE_DARK); drain = finalMagicNonSpellAdjustments(player,target,ELE_DARK,drain); if (drain > target:getMP()) then drain = target:getMP(); end target:addMP(-drain); return SUBEFFECT_MP_DRAIN, 162, player:addMP(drain); end end;
gpl-3.0
JeffProgrammer/Torque6
build/scripts/ljpeg.lua
4
2015
function ljpeg() project "ljpeg" location (LIB_PROJECT_DIR) targetdir (LIB_BUILD_DIR) targetname "ljpeg" language "C++" kind "StaticLib" includedirs { SRC_DIR, } files { path.join(LIB_DIR, "ljpeg/**.h"), path.join(LIB_DIR, "ljpeg/**.c"), } removefiles { path.join(LIB_DIR, "ljpeg/extras/**"), path.join(LIB_DIR, "ljpeg/**.mac.h"), path.join(LIB_DIR, "ljpeg/**.linux.h"), path.join(LIB_DIR, "ljpeg/jmemansi.c"), path.join(LIB_DIR, "ljpeg/jmemdos.c"), path.join(LIB_DIR, "ljpeg/jmemmac.c"), path.join(LIB_DIR, "ljpeg/jmemname.c"), path.join(LIB_DIR, "ljpeg/jpegtran.c"), } configuration { "windows", "x32", "Release" } targetdir (LIB_BUILD_DIR .. "/windows.x32.release") configuration { "windows", "x32", "Debug" } targetdir (LIB_BUILD_DIR .. "/windows.x32.debug") configuration { "windows", "x64", "Release" } targetdir (LIB_BUILD_DIR .. "/windows.x64.release") configuration { "windows", "x64", "Debug" } targetdir (LIB_BUILD_DIR .. "/windows.x64.debug") configuration "Debug" defines { "TORQUE_DEBUG" } flags { "Symbols" } configuration "vs*" defines { "_CRT_SECURE_NO_WARNINGS" } configuration "vs2015" windowstargetplatformversion "10.0.10240.0" configuration "windows" links { "ole32" } configuration "linux" links { "dl" } configuration "linux or bsd" links { "m" } linkoptions { "-rdynamic" } buildoptions { "-fPIC" } configuration "macosx" configuration { "macosx", "gmake" } buildoptions { "-mmacosx-version-min=10.4" } linkoptions { "-mmacosx-version-min=10.4" } end
mit
UnfortunateFruit/darkstar
scripts/zones/Yhoator_Jungle/npcs/Ghantata_WW.lua
30
3054
----------------------------------- -- Area: Yhoator Jungle -- NPC: Ghantata, W.W. -- Border Conquest Guards -- @pos -84.113 -0.449 224.902 124 ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Yhoator_Jungle/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ELSHIMOUPLANDS; local csid = 0x7ff6; ----------------------------------- -- 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
ennis/autograph-pipelines
resources/scripts/pl/lapp.lua
2
14382
--- Simple command-line parsing using human-readable specification. -- Supports GNU-style parameters. -- -- lapp = require 'pl.lapp' -- local args = lapp [[ -- Does some calculations -- -o,--offset (default 0.0) Offset to add to scaled number -- -s,--scale (number) Scaling factor -- <number>; (number ) Number to be scaled -- ]] -- -- print(args.offset + args.scale * args.number) -- -- Lines begining with '-' are flags; there may be a short and a long name; -- lines begining wih '<var>' are arguments. Anything in parens after -- the flag/argument is either a default, a type name or a range constraint. -- -- See @{08-additional.md.Command_line_Programs_with_Lapp|the Guide} -- -- Dependencies: `pl.sip` -- @module pl.lapp local status,sip = pcall(require,'pl.sip') if not status then sip = require 'sip' end local match = sip.match_at_start local append,tinsert = table.insert,table.insert sip.custom_pattern('X','(%a[%w_%-]*)') local function lines(s) return s:gmatch('([^\n]*)\n') end local function lstrip(str) return str:gsub('^%s+','') end local function strip(str) return lstrip(str):gsub('%s+$','') end local function at(s,k) return s:sub(k,k) end local function isdigit(s) return s:find('^%d+$') == 1 end local lapp = {} local open_files,parms,aliases,parmlist,usage,windows,script lapp.callback = false -- keep Strict happy local filetypes = { stdin = {io.stdin,'file-in'}, stdout = {io.stdout,'file-out'}, stderr = {io.stderr,'file-out'} } --- controls whether to dump usage on error. -- Defaults to true lapp.show_usage_error = true --- quit this script immediately. -- @string msg optional message -- @bool no_usage suppress 'usage' display function lapp.quit(msg,no_usage) if no_usage == 'throw' then error(msg) end if msg then io.stderr:write(msg..'\n\n') end if not no_usage then io.stderr:write(usage) end os.exit(1) end --- print an error to stderr and quit. -- @string msg a message -- @bool no_usage suppress 'usage' display function lapp.error(msg,no_usage) if not lapp.show_usage_error then no_usage = true elseif lapp.show_usage_error == 'throw' then no_usage = 'throw' end lapp.quit(script..': '..msg,no_usage) end --- open a file. -- This will quit on error, and keep a list of file objects for later cleanup. -- @string file filename -- @string[opt] opt same as second parameter of `io.open` function lapp.open (file,opt) local val,err = io.open(file,opt) if not val then lapp.error(err,true) end append(open_files,val) return val end --- quit if the condition is false. -- @bool condn a condition -- @string msg message text function lapp.assert(condn,msg) if not condn then lapp.error(msg) end end local function range_check(x,min,max,parm) lapp.assert(min <= x and max >= x,parm..' out of range') end local function xtonumber(s) local val = tonumber(s) if not val then lapp.error("unable to convert to number: "..s) end return val end local types = {} local builtin_types = {string=true,number=true,['file-in']='file',['file-out']='file',boolean=true} local function convert_parameter(ps,val) if ps.converter then val = ps.converter(val) end if ps.type == 'number' then val = xtonumber(val) elseif builtin_types[ps.type] == 'file' then val = lapp.open(val,(ps.type == 'file-in' and 'r') or 'w' ) elseif ps.type == 'boolean' then return val end if ps.constraint then ps.constraint(val) end return val end --- add a new type to Lapp. These appear in parens after the value like -- a range constraint, e.g. '<ival> (integer) Process PID' -- @string name name of type -- @param converter either a function to convert values, or a Lua type name. -- @func[opt] constraint optional function to verify values, should use lapp.error -- if failed. function lapp.add_type (name,converter,constraint) types[name] = {converter=converter,constraint=constraint} end local function force_short(short) lapp.assert(#short==1,short..": short parameters should be one character") end -- deducing type of variable from default value; local function process_default (sval,vtype) local val if not vtype or vtype == 'number' then val = tonumber(sval) end if val then -- we have a number! return val,'number' elseif filetypes[sval] then local ft = filetypes[sval] return ft[1],ft[2] else if sval == 'true' and not vtype then return true, 'boolean' end if sval:match '^["\']' then sval = sval:sub(2,-2) end return sval,vtype or 'string' end end --- process a Lapp options string. -- Usually called as `lapp()`. -- @string str the options text -- @tparam {string} args a table of arguments (default is `_G.arg`) -- @return a table with parameter-value pairs function lapp.process_options_string(str,args) local results = {} local opts = {at_start=true} local varargs local arg = args or _G.arg open_files = {} parms = {} aliases = {} parmlist = {} local function check_varargs(s) local res,cnt = s:gsub('^%.%.%.%s*','') return res, (cnt > 0) end local function set_result(ps,parm,val) parm = type(parm) == "string" and parm:gsub("%W", "_") or parm -- so foo-bar becomes foo_bar in Lua if not ps.varargs then results[parm] = val else if not results[parm] then results[parm] = { val } else append(results[parm],val) end end end usage = str for line in lines(str) do local res = {} local optspec,optparm,i1,i2,defval,vtype,constraint,rest line = lstrip(line) local function check(str) return match(str,line,res) end -- flags: either '-<short>', '-<short>,--<long>' or '--<long>' if check '-$v{short}, --$o{long} $' or check '-$v{short} $' or check '--$o{long} $' then if res.long then optparm = res.long:gsub('[^%w%-]','_') -- I'm not sure the $o pattern will let anything else through? if res.short then aliases[res.short] = optparm end else optparm = res.short end if res.short and not lapp.slack then force_short(res.short) end res.rest, varargs = check_varargs(res.rest) elseif check '$<{name} $' then -- is it <parameter_name>? -- so <input file...> becomes input_file ... optparm,rest = res.name:match '([^%.]+)(.*)' optparm = optparm:gsub('%A','_') varargs = rest == '...' append(parmlist,optparm) end -- this is not a pure doc line and specifies the flag/parameter type if res.rest then line = res.rest res = {} local optional -- do we have ([optional] [<type>] [default <val>])? if match('$({def} $',line,res) or match('$({def}',line,res) then local typespec = strip(res.def) local ftype, rest = typespec:match('^(%S+)(.*)$') rest = strip(rest) if ftype == 'optional' then ftype, rest = rest:match('^(%S+)(.*)$') rest = strip(rest) optional = true end local default if ftype == 'default' then default = true if rest == '' then lapp.error("value must follow default") end else -- a type specification if match('$f{min}..$f{max}',ftype,res) then -- a numerical range like 1..10 local min,max = res.min,res.max vtype = 'number' constraint = function(x) range_check(x,min,max,optparm) end elseif not ftype:match '|' then -- plain type vtype = ftype else -- 'enum' type is a string which must belong to -- one of several distinct values local enums = ftype local enump = '|' .. enums .. '|' vtype = 'string' constraint = function(s) lapp.assert(enump:match('|'..s..'|'), "value '"..s.."' not in "..enums ) end end end res.rest = rest typespec = res.rest -- optional 'default value' clause. Type is inferred as -- 'string' or 'number' if there's no explicit type if default or match('default $r{rest}',typespec,res) then defval,vtype = process_default(res.rest,vtype) end else -- must be a plain flag, no extra parameter required defval = false vtype = 'boolean' end local ps = { type = vtype, defval = defval, required = defval == nil and not optional, comment = res.rest or optparm, constraint = constraint, varargs = varargs } varargs = nil if types[vtype] then local converter = types[vtype].converter if type(converter) == 'string' then ps.type = converter else ps.converter = converter end ps.constraint = types[vtype].constraint elseif not builtin_types[vtype] then lapp.error(vtype.." is unknown type") end parms[optparm] = ps end end -- cool, we have our parms, let's parse the command line args local iparm = 1 local iextra = 1 local i = 1 local parm,ps,val local end_of_flags = false local function check_parm (parm) local eqi = parm:find '=' if eqi then tinsert(arg,i+1,parm:sub(eqi+1)) parm = parm:sub(1,eqi-1) end return parm,eqi end local function is_flag (parm) return parms[aliases[parm] or parm] end while i <= #arg do local theArg = arg[i] local res = {} -- after '--' we don't parse args and they end up in -- the array part of the result (args[1] etc) if theArg == '--' then end_of_flags = true iparm = #parmlist + 1 i = i + 1 theArg = arg[i] if not theArg then break end end -- look for a flag, -<short flags> or --<long flag> if not end_of_flags and (match('--$S{long}',theArg,res) or match('-$S{short}',theArg,res)) then if res.long then -- long option parm = check_parm(res.long) elseif #res.short == 1 or is_flag(res.short) then parm = res.short else local parmstr,eq = check_parm(res.short) if not eq then parm = at(parmstr,1) local flag = is_flag(parm) if flag and flag.type ~= 'boolean' then --if isdigit(at(parmstr,2)) then -- a short option followed by a digit is an exception (for AW;)) -- push ahead into the arg array tinsert(arg,i+1,parmstr:sub(2)) else -- push multiple flags into the arg array! for k = 2,#parmstr do tinsert(arg,i+k-1,'-'..at(parmstr,k)) end end else parm = parmstr end end if aliases[parm] then parm = aliases[parm] end if not parms[parm] and (parm == 'h' or parm == 'help') then lapp.quit() end else -- a parameter parm = parmlist[iparm] if not parm then -- extra unnamed parameters are indexed starting at 1 parm = iextra ps = { type = 'string' } parms[parm] = ps iextra = iextra + 1 else ps = parms[parm] end if not ps.varargs then iparm = iparm + 1 end val = theArg end ps = parms[parm] if not ps then lapp.error("unrecognized parameter: "..parm) end if ps.type ~= 'boolean' then -- we need a value! This should follow if not val then i = i + 1 val = arg[i] theArg = val end lapp.assert(val,parm.." was expecting a value") else -- toggle boolean flags (usually false -> true) val = not ps.defval end ps.used = true val = convert_parameter(ps,val) set_result(ps,parm,val) if builtin_types[ps.type] == 'file' then set_result(ps,parm..'_name',theArg) end if lapp.callback then lapp.callback(parm,theArg,res) end i = i + 1 val = nil end -- check unused parms, set defaults and check if any required parameters were missed for parm,ps in pairs(parms) do if not ps.used then if ps.required then lapp.error("missing required parameter: "..parm) end set_result(ps,parm,ps.defval) end end return results end if arg then script = arg[0] script = script or rawget(_G,"LAPP_SCRIPT") or "unknown" -- strip dir and extension to get current script name script = script:gsub('.+[\\/]',''):gsub('%.%a+$','') else script = "inter" end setmetatable(lapp, { __call = function(tbl,str,args) return lapp.process_options_string(str,args) end, }) return lapp
mit
nesstea/darkstar
scripts/zones/La_Theine_Plateau/npcs/qm3.lua
29
2086
----------------------------------- -- Area: La Theine Plateau -- NPC:??? (qm3) -- Involved in Quest: I Can Hear A Rainbow ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/La_Theine_Plateau/TextIDs"); require("scripts/globals/icanheararainbow"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(WINDURST, I_CAN_HEAR_A_RAINBOW) == QUEST_ACCEPTED) then if (trade:hasItemQty(1125,1) and trade:getItemCount() == 1 and trade:getGil() == 0 and player:getVar("I_CAN_HEAR_A_RAINBOW") == 127) then player:startEvent(0x007c); end end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 0) then player:startEvent(0x00CB); 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 == 0x007c) then player:tradeComplete(); player:completeQuest(WINDURST, I_CAN_HEAR_A_RAINBOW); player:addTitle(RAINBOW_WEAVER); player:unlockJob(15); player:addSpell(296); player:messageSpecial(UNLOCK_SUMMONER); player:messageSpecial(UNLOCK_CARBUNCLE); player:setVar("ICanHearARainbow",0); SetServerVariable("I_Can_Hear_a_Rainbow", 1); elseif (csid == 0x00CB) then player:setVar("COP_Tenzen_s_Path",1); end end;
gpl-3.0
abhinavmoudgil95/funnybot
src/LanguageModel.lua
9
5434
require 'torch' require 'nn' require 'VanillaRNN' require 'LSTM' local utils = require 'util.utils' local LM, parent = torch.class('nn.LanguageModel', 'nn.Module') function LM:__init(kwargs) self.idx_to_token = utils.get_kwarg(kwargs, 'idx_to_token') self.token_to_idx = {} self.vocab_size = 0 for idx, token in pairs(self.idx_to_token) do self.token_to_idx[token] = idx self.vocab_size = self.vocab_size + 1 end self.model_type = utils.get_kwarg(kwargs, 'model_type') self.wordvec_dim = utils.get_kwarg(kwargs, 'wordvec_size') self.rnn_size = utils.get_kwarg(kwargs, 'rnn_size') self.num_layers = utils.get_kwarg(kwargs, 'num_layers') self.dropout = utils.get_kwarg(kwargs, 'dropout') self.batchnorm = utils.get_kwarg(kwargs, 'batchnorm') local V, D, H = self.vocab_size, self.wordvec_dim, self.rnn_size self.net = nn.Sequential() self.rnns = {} self.bn_view_in = {} self.bn_view_out = {} self.net:add(nn.LookupTable(V, D)) for i = 1, self.num_layers do local prev_dim = H if i == 1 then prev_dim = D end local rnn if self.model_type == 'rnn' then rnn = nn.VanillaRNN(prev_dim, H) elseif self.model_type == 'lstm' then rnn = nn.LSTM(prev_dim, H) end rnn.remember_states = true table.insert(self.rnns, rnn) self.net:add(rnn) if self.batchnorm == 1 then local view_in = nn.View(1, 1, -1):setNumInputDims(3) table.insert(self.bn_view_in, view_in) self.net:add(view_in) self.net:add(nn.BatchNormalization(H)) local view_out = nn.View(1, -1):setNumInputDims(2) table.insert(self.bn_view_out, view_out) self.net:add(view_out) end if self.dropout > 0 then self.net:add(nn.Dropout(self.dropout)) end end -- After all the RNNs run, we will have a tensor of shape (N, T, H); -- we want to apply a 1D temporal convolution to predict scores for each -- vocab element, giving a tensor of shape (N, T, V). Unfortunately -- nn.TemporalConvolution is SUPER slow, so instead we will use a pair of -- views (N, T, H) -> (NT, H) and (NT, V) -> (N, T, V) with a nn.Linear in -- between. Unfortunately N and T can change on every minibatch, so we need -- to set them in the forward pass. self.view1 = nn.View(1, 1, -1):setNumInputDims(3) self.view2 = nn.View(1, -1):setNumInputDims(2) self.net:add(self.view1) self.net:add(nn.Linear(H, V)) self.net:add(self.view2) end function LM:updateOutput(input) local N, T = input:size(1), input:size(2) self.view1:resetSize(N * T, -1) self.view2:resetSize(N, T, -1) for _, view_in in ipairs(self.bn_view_in) do view_in:resetSize(N * T, -1) end for _, view_out in ipairs(self.bn_view_out) do view_out:resetSize(N, T, -1) end return self.net:forward(input) end function LM:backward(input, gradOutput, scale) return self.net:backward(input, gradOutput, scale) end function LM:parameters() return self.net:parameters() end function LM:training() self.net:training() parent.training(self) end function LM:evaluate() self.net:evaluate() parent.evaluate(self) end function LM:resetStates() for i, rnn in ipairs(self.rnns) do rnn:resetStates() end end function LM:encode_string(s) local encoded = torch.LongTensor(#s) for i = 1, #s do local token = s:sub(i, i) local idx = self.token_to_idx[token] assert(idx ~= nil, 'Got invalid idx') encoded[i] = idx end return encoded end function LM:decode_string(encoded) assert(torch.isTensor(encoded) and encoded:dim() == 1) local s = '' for i = 1, encoded:size(1) do local idx = encoded[i] local token = self.idx_to_token[idx] s = s .. token end return s end --[[ Sample from the language model. Note that this will reset the states of the underlying RNNs. Inputs: - init: String of length T0 - max_length: Number of characters to sample Returns: - sampled: (1, max_length) array of integers, where the first part is init. --]] function LM:sample(kwargs) local T = utils.get_kwarg(kwargs, 'length', 100) local start_text = utils.get_kwarg(kwargs, 'start_text', '') local verbose = utils.get_kwarg(kwargs, 'verbose', 0) local sample = utils.get_kwarg(kwargs, 'sample', 1) local temperature = utils.get_kwarg(kwargs, 'temperature', 1) local sampled = torch.LongTensor(1, T) self:resetStates() local scores, first_t if #start_text > 0 then if verbose > 0 then print('Seeding with: "' .. start_text .. '"') end local x = self:encode_string(start_text):view(1, -1) local T0 = x:size(2) sampled[{{}, {1, T0}}]:copy(x) scores = self:forward(x)[{{}, {T0, T0}}] first_t = T0 + 1 else if verbose > 0 then print('Seeding with uniform probabilities') end local w = self.net:get(1).weight scores = w.new(1, 1, self.vocab_size):fill(1) first_t = 1 end local _, next_char = nil, nil for t = first_t, T do if sample == 0 then _, next_char = scores:max(3) next_char = next_char[{{}, {}, 1}] else local probs = torch.div(scores, temperature):double():exp():squeeze() probs:div(torch.sum(probs)) next_char = torch.multinomial(probs, 1):view(1, 1) end sampled[{{}, {t, t}}]:copy(next_char) scores = self:forward(next_char) end self:resetStates() return self:decode_string(sampled[1]) end function LM:clearState() self.net:clearState() end
mit
johnmccabe/dockercraft
world/Plugins/Core/main.lua
5
3147
-- main.lua -- Implements the main plugin entrypoint -- Configuration -- Use prefixes or not. -- If set to true, messages are prefixed, e. g. "[FATAL]". If false, messages are colored. g_UsePrefixes = true -- Global variables Messages = {} WorldsSpawnProtect = {} WorldsWorldLimit = {} WorldsWorldDifficulty = {} lastsender = {} -- Called by MCServer on plugin start to initialize the plugin function Initialize(Plugin) Plugin:SetName( "Core" ) Plugin:SetVersion( 15 ) -- Register for all hooks needed cPluginManager:AddHook(cPluginManager.HOOK_CHAT, OnChat) cPluginManager:AddHook(cPluginManager.HOOK_CRAFTING_NO_RECIPE, OnCraftingNoRecipe) cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_DESTROYED, OnDisconnect); cPluginManager:AddHook(cPluginManager.HOOK_KILLING, OnKilling) cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_BREAKING_BLOCK, OnPlayerBreakingBlock) cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_JOINED, OnPlayerJoined) cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_MOVING, OnPlayerMoving) cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_PLACING_BLOCK, OnPlayerPlacingBlock) cPluginManager:AddHook(cPluginManager.HOOK_SPAWNING_ENTITY, OnSpawningEntity) cPluginManager:AddHook(cPluginManager.HOOK_TAKE_DAMAGE, OnTakeDamage) -- Bind ingame commands: -- Load the InfoReg shared library: dofile(cPluginManager:GetPluginsPath() .. "/InfoReg.lua") -- Bind all the commands: RegisterPluginInfoCommands(); -- Bind all the console commands: RegisterPluginInfoConsoleCommands(); -- Load settings: IniFile = cIniFile() IniFile:ReadFile("settings.ini") HardCore = IniFile:GetValueSet("GameMode", "Hardcore", "false") IniFile:WriteFile("settings.ini") -- Load SpawnProtection and WorldLimit settings for individual worlds: cRoot:Get():ForEachWorld( function (a_World) LoadWorldSettings(a_World) end ) -- Initialize the banlist, load its DB, do whatever processing it needs on startup: InitializeBanlist() -- Initialize the whitelist, load its DB, do whatever processing it needs on startup: InitializeWhitelist() -- Initialize the Item Blacklist (the list of items that cannot be obtained using the give command) IntializeItemBlacklist( Plugin ) -- Add webadmin tabs: Plugin:AddWebTab("Manage Server", HandleRequest_ManageServer) Plugin:AddWebTab("Server Settings", HandleRequest_ServerSettings) Plugin:AddWebTab("Chat", HandleRequest_Chat) Plugin:AddWebTab("Players", HandleRequest_Players) Plugin:AddWebTab("Whitelist", HandleRequest_WhiteList) Plugin:AddWebTab("Permissions", HandleRequest_Permissions) Plugin:AddWebTab("Plugins", HandleRequest_ManagePlugins) Plugin:AddWebTab("Time & Weather", HandleRequest_Weather) Plugin:AddWebTab("Ranks", HandleRequest_Ranks) Plugin:AddWebTab("Player Ranks", HandleRequest_PlayerRanks) LoadMotd() WEBLOGINFO("Core is initialized") LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion()) return true end function OnDisable() LOG( "Disabled Core!" ) end
apache-2.0
UnfortunateFruit/darkstar
scripts/zones/AlTaieu/mobs/Ru_aern.lua
9
2744
----------------------------------- -- Area: Al'Taieu -- NPC: Ru_aern ----------------------------------- require("scripts/globals/missions"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) if(killer:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and killer:getVar("PromathiaStatus") == 2)then switch (mob:getID()) : caseof { -- South Tower [16912829] = function (x) killer:setVar("Ru_aern_1-1KILL",1); end, [16912830] = function (x) killer:setVar("Ru_aern_1-2KILL",1); end, [16912831] = function (x) killer:setVar("Ru_aern_1-3KILL",1); end, -- West Tower [16912832] = function (x) killer:setVar("Ru_aern_2-1KILL",1); end, [16912833] = function (x) killer:setVar("Ru_aern_2-2KILL",1); end, [16912834] = function (x) killer:setVar("Ru_aern_2-3KILL",1); end, -- East Tower [16912835] = function (x) killer:setVar("Ru_aern_3-1KILL",1); end, [16912836] = function (x) killer:setVar("Ru_aern_3-2KILL",1); end, [16912837] = function (x) killer:setVar("Ru_aern_3-3KILL",1); end, } if (killer:getVar("Ru_aern_1-1KILL") == 1 and killer:getVar("Ru_aern_1-2KILL") == 1 and killer:getVar("Ru_aern_1-3KILL") == 1)then killer:setVar("[SEA][AlTieu]SouthTower",1); clearTowerVars(killer, 1); end if (killer:getVar("Ru_aern_2-1KILL") == 1 and killer:getVar("Ru_aern_2-2KILL") == 1 and killer:getVar("Ru_aern_2-3KILL") == 1)then killer:setVar("[SEA][AlTieu]WestTower",1); clearTowerVars(killer, 2); end if (killer:getVar("Ru_aern_3-1KILL") == 1 and killer:getVar("Ru_aern_3-2KILL") == 1 and killer:getVar("Ru_aern_3-3KILL") == 1)then killer:setVar("[SEA][AlTieu]EastTower",1); clearTowerVars(killer, 3); end end end; function clearTowerVars (player, towerNum) player:setVar("Ru_aern_"..towerNum.."-1KILL",0); player:setVar("Ru_aern_"..towerNum.."-2KILL",0); player:setVar("Ru_aern_"..towerNum.."-3KILL",0); end
gpl-3.0
nesstea/darkstar
scripts/zones/Southern_San_dOria/npcs/Phamelise.lua
12
2168
----------------------------------- -- Area: Southern San d'Oria -- NPC: Phamelise -- Only sells when San d'Oria controlls Zulkheim Region ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/events/harvest_festivals"); require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/globals/conquest"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == 1) then if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then player:messageSpecial(FLYER_REFUSED); end else onHalloweenTrade(player,trade,npc); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(ZULKHEIM); if (RegionOwner ~= SANDORIA) then player:showText(npc,PHAMELISE_CLOSED_DIALOG); else player:showText(npc,PHAMELISE_OPEN_DIALOG); stock = {0x1114,44, --Giant Sheep Meat 0x026e,44, --Dried Marjoram 0x0262,55, --San d'Orian Flour 0x0263,36, --Rye Flour 0x0730,1840, --Semolina 0x110e,22, --La Theine Cabbage 0x111a,55} --Selbina Milk showShop(player,SANDORIA,stock); 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
UnfortunateFruit/darkstar
scripts/zones/Horlais_Peak/npcs/Burning_Circle.lua
12
1985
----------------------------------- -- Area: Horlais Peak -- NPC: Burning Circle -- Horlais Peak Burning Circle -- @pos -509 158 -211 139 ------------------------------------- package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Horlais_Peak/TextIDs"); --- 0: The Rank 2 Final Mission --- 1: Tails of Woe --- 2: Dismemberment Brigade --- 3: The Secret Weapon (Sandy Mission 7-2) --- 4: Hostile Herbivores --- 5: Shattering Stars (WAR) --- 6: Shattering Stars (BLM) --- 7: Shattering Stars (RNG) --- 8: Carapace Combatants --- 9: Shooting Fish --- 10: Dropping like Flies --- 11: Horns of War --- 12: Under Observation --- 13: Eye of the Tiger --- 14: Shots in the Dark --- 15: Double Dragonian --- 16: Today's Horoscope --- 17: Contaminated Colosseum ----------------------------------- -- 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))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
nesstea/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Elnonde.lua
13
1610
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Elnonde -- @zone 80 -- @pos 86 2 -0 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 2) then local mask = player:getVar("GiftsOfGriffonPlumes"); if (trade:hasItemQty(2528,1) and trade:getItemCount() == 1 and not player:getMaskBit(mask,5)) then player:startEvent(0x01E) -- Gifts of Griffon Trade end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0267); -- Default Dialogue 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 == 0x01E) then -- Gifts Of Griffon Trade player:tradeComplete(); local mask = player:getVar("GiftsOfGriffonPlumes"); player:setMaskBit(mask,"GiftsOfGriffonPlumes",5,true); end end;
gpl-3.0
bowlofstew/Macaroni
Next/Tests/Features/LanguageFeatures/Source/SimpleGenerator.lua
2
9860
function printMem(blah) local mem = collectgarbage("count"); print("MEMORY " .. blah .. ":" .. mem); collectgarbage("collect"); end printMem("BEGIN"); require "Macaroni.Generator.Output.Path"; require "Macaroni.Model.Member"; require "Macaroni.Model.Node"; require "Macaroni.Model.Context"; require "Macaroni.Model.Type"; require "Macaroni.Model.TypeArgument"; require "Macaroni.Model.TypeArgumentList"; require "Macaroni.Model.TypeList"; require "Macaroni.Model.Cpp.VariableAssignment"; Macaroni.Model.TypeNames = { Class = "Class", Constructor="Constructor", Function="Function", Namespace = "Namespace", Primitive="Primitive", Variable="Variable" }; printMem("After registration."); local Context = Macaroni.Model.Context; local Node = Macaroni.Model.Node; local Type = Macaroni.Model.Type; local TypeArgument = Macaroni.Model.TypeArgument; local TypeArgumentList = Macaroni.Model.TypeArgumentList; local TypeNames = Macaroni.Model.TypeNames; local VariableAssignment = Macaroni.Model.Cpp.VariableAssignment; printMem("Local module aliasing."); function Generate(context, path) print "Generating H Files\n"; iterateNodes(context.Root.Children, path); end function iterateNodes(nodeChildren, path) for i = 1, #(nodeChildren) do n = nodeChildren[i]; parseNode(n, path); end end function parseClass(node, path) printMem("parseClass"); assert(node.Member.TypeName == TypeNames.Class); local filePath = path:NewPath(".h"); local cg = ClassGenerator.new{node = node, path = filePath}; cg:parse(); end function parseNamespace(node, path) printMem("parseNamespace"); assert(node.Member.TypeName == TypeNames.Namespace); printMem("parseNamespace 2"); path:CreateDirectory(); printMem("parseNamespace 3"); iterateNodes(node.Children, path); printMem("parseNamespace 4"); end function parseNode(node, path) printMem("parseNode"); print("~~~ " .. node.FullName); local m = node.Member; if (m == nil) then return; end local typeName = m.TypeName; print(" " .. typeName); local newPath = path:NewPath("/" .. node.Name); --if (newPath.IsDirectory) then -- newPath.CreateDirectory(); --end local handlerFunc = nil; if (typeName == TypeNames.Namespace) then handlerFunc = parseNamespace; elseif (typeName == TypeNames.Class) then handlerFunc = parseClass; end if (handlerFunc ~= nil) then handlerFunc(node, newPath); else print(" ~ Skipping"); end end ClassGenerator = { isNested = false, node = nil, tabs = 0, writer = nil, new = function(args) assert(args.node ~= nil); if (args.path == nil) then assert(args.writer ~= nil); else --TODO: Somehow calling C++ NewFileWriter() method currently results in entire Lua call from C++ ending. local writer, errorMsg, errorNumber = io.open(args.path.AbsolutePath, 'w+'); --args.path:NewFileWriter(); if (writer == nil) then error(tostring(errorNumber) .. " " .. errorMsg, 2); end args.writer = writer; end setmetatable(args, ClassGenerator); ClassGenerator.__index = ClassGenerator; return args; end, addTabs = function(self, tabCount) self.tabs = self.tabs + tabCount; end, classBegin = function(self) self.writer:write("class " .. self.node.Name .. "\n"); self.writer:write("{\n"); self:addTabs(1); end, classBody = function(self) self:classBegin(); self:iterateClassMembers(self.node.Children); self:classEnd(); end, classEnd = function(self) self.writer:write("} // End of class " .. self.node.Name .. "\n"); self:addTabs(-1); end, getGuardName = function(self) local guardName = "MACARONI_COMPILE_GUARD_" .. self.node:GetPrettyFullName("_") .. "_H"; return guardName; end, includeGuardFooter = function(self) self.writer:write("#endif // end of " .. self:getGuardName()); end, includeGuardHeader = function(self) local guardName = self:getGuardName(); self.writer:write("#ifndef " .. guardName .. "\n"); self.writer:write("#define " .. guardName .. "\n"); end, includeStatements = function(self) -- alas, this is impossible. -- The NodePtrList type needs LuaGlue so the property can be accessed from the Class member. end, iterateClassMembers = function(self, nodeChildren) for i=1, #nodeChildren do node = nodeChildren[i]; self:parseMember(node); end end, namespaceBegin = function(self) local fs = self.node.FullName; local names = Node.SplitComplexName(fs); for i = 1, #names - 1 do self.writer:write("namespace " .. names[i] .. " { "); end self.writer:write("\n"); end, namespaceEnd = function(self) local names = Node.SplitComplexName(self.node.FullName); for i,v in pairs(names) do self:write("} "); end self:write("// End namespace "); self:write("\n"); end, -- Entry function. parse = function(self) if (not self.isNested) then self:includeGuardHeader(); self.writer:write('\n'); self:includeStatements(); self.writer:write('\n'); self:namespaceBegin(); self.writer:write('\n'); end self:classBody(); if (not self.isNested) then self.writer:write('\n'); self:namespaceEnd(); self.writer:write('\n'); self:includeGuardFooter(); end end, ["parse" .. TypeNames.Constructor] = function(self, node) self:writeTabs(); self:write(self.node.Name .. "("); self:writeArgumentList(node); self:write(");\n"); end, ["parse" .. TypeNames.Function] = function(self, node) self:writeTabs(); local func = node.Member; self:writeVariableInfo(func.ReturnType); self:write(func.ReturnType.Node.FullName); self:write(" " .. node.Name .. "("); self:writeArgumentList(node); self:write(");\n"); end, parseMember = function(self, node) local m = node.Member; if (m == nil) then self:writeTabs(); self:write("// No member info- " .. node.Name .. "\n"); end local typeName = m.TypeName; local handlerFunc = nil; if (typeName == TypeNames.Class) then -- Pass the new generator the same writer as this class. ClassGenerator.New({isNested = true, node = node, writer = self.writer}); handlerFunc = self.parseClass; else handlerFunc = self["parse" .. typeName]; end if (handlerFunc ~= nil) then handlerFunc(self, node); else self:writeTabs(); self:write("// ~ Have no way to handle node " .. node.Name .. " with Member type " .. typeName .. ".\n"); end end, ["parse" .. TypeNames.Namespace] = function(self) self:writeTabs(); self:write("//TODO: Create parseNamespace functionality for Namespaces within classes."); end, ["parse" .. TypeNames.Variable] = function(self, node) self:writeTabs(); local variable = node.Member; self:writeVariableInfo(variable); self:write(variable.Type.Node.FullName .. " "); self:write(node.Name .. ";\n"); end, write = function(self, text) if (type(text) ~= "string") then error("String was expected in call to write, but got " .. type(text) .. " instead.", 2); end --print("DEBUG:" .. debug.traceback()); self.writer:write(text); end, writeArgumentList = function(self, node) local seenOne = false; for i = 1, #(node.Children) do local c = node.Children[i]; if (c.Member.TypeName == TypeNames.Variable) then if (seenOne) then self:write(", "); else seenOne = true; end self:writeVariableInfo(c.Member); self:write(c.Member.Type.Node.FullName); self:write(" "); self:write(c.Name); end end end, writeTabs = function(self) for i = 1, self.tabs do self.writer:write('\t'); end end, writeVariableInfo = function(self, variable) if (variable.Type == nil) then self:write("/* variable's type was NIL!? '_'*? For node:" .. variable.Node.FullName .. "*/ "); return; end if (variable.Type.Const) then self:write("const "); end if (variable.Type.Pointer) then self:write("* "); end if (variable.Type.Reference) then self:write("& "); end if (variable.Type.ConstPointer) then self:write("const "); end end, };
apache-2.0
plajjan/snabbswitch
lib/ljsyscall/test/openbsd.lua
18
1414
-- OpenBSD specific tests local function init(S) local helpers = require "syscall.helpers" local types = S.types local c = S.c local abi = S.abi local bit = require "syscall.bit" local ffi = require "ffi" local t, pt, s = types.t, types.pt, types.s local assert = helpers.assert local function fork_assert(cond, err, ...) -- if we have forked we need to fail in main thread not fork if not cond then print(tostring(err)) print(debug.traceback()) S.exit("failure") end if cond == true then return ... end return cond, ... end local function assert_equal(...) collectgarbage("collect") -- force gc, to test for bugs return assert_equals(...) end local teststring = "this is a test string" local size = 512 local buf = t.buffer(size) local tmpfile = "XXXXYYYYZZZ4521" .. S.getpid() local tmpfile2 = "./666666DDDDDFFFF" .. S.getpid() local tmpfile3 = "MMMMMTTTTGGG" .. S.getpid() local longfile = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" .. S.getpid() local efile = "./tmpexXXYYY" .. S.getpid() .. ".sh" local largeval = math.pow(2, 33) -- larger than 2^32 for testing local mqname = "ljsyscallXXYYZZ" .. S.getpid() local clean = function() S.rmdir(tmpfile) S.unlink(tmpfile) S.unlink(tmpfile2) S.unlink(tmpfile3) S.unlink(longfile) S.unlink(efile) end local test = {} return test end return {init = init}
apache-2.0
UnfortunateFruit/darkstar
scripts/globals/items/dish_of_spaghetti_arrabbiata.lua
35
1719
----------------------------------------- -- ID: 5211 -- Item: dish_of_spaghetti_arrabbiata -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength 5 -- Vitality 2 -- Intelligence -7 -- Attack % 22 -- Attack Cap 120 -- Store TP 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5211); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 5); target:addMod(MOD_VIT, 2); target:addMod(MOD_INT, -7); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 120); target:addMod(MOD_FOOD_HPP, 12); target:addMod(MOD_FOOD_HP_CAP, 150); target:addMod(MOD_STORETP, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 5); target:delMod(MOD_VIT, 2); target:delMod(MOD_INT, -7); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 120); target:delMod(MOD_FOOD_HPP, 12); target:delMod(MOD_FOOD_HP_CAP, 150); target:delMod(MOD_STORETP, 5); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Apollyon/bcnms/NE_Apollyon.lua
35
1113
----------------------------------- -- Area: Appolyon -- Name: NE_Apollyon ----------------------------------- require("scripts/globals/limbus"); require("scripts/globals/keyitems"); -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[NE_Apollyon]UniqueID",GenerateLimbusKey()); HideArmouryCrates(GetInstanceRegion(1292),APPOLLYON_SE_NE); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("limbusbitmap",0); player:setVar("characterLimbusKey",GetServerVariable("[NE_Apollyon]UniqueID")); player:setVar("LimbusID",1292); player:delKeyItem(COSMOCLEANSE); player:delKeyItem(BLACK_CARD); end; -- Leaving by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then player:setPos(643,0.1,-600); ResetPlayerLimbusVariable(player) end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Beadeaux/npcs/The_Mute.lua
19
1257
----------------------------------- -- Area: Beadeaux -- NPC: ??? -- @pos -166.230 -1 -73.685 147 ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Beadeaux/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local duration = math.random(600,900); if(player:getQuestStatus(BASTOK,THE_CURSE_COLLECTOR) == QUEST_ACCEPTED and player:getVar("cCollectSilence") == 0) then player:setVar("cCollectSilence",1); end player:addStatusEffect(EFFECT_SILENCE,0,0,duration); 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
UnfortunateFruit/darkstar
scripts/zones/Eastern_Altepa_Desert/TextIDs.lua
5
1060
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6382; -- Obtained: <item>. GIL_OBTAINED = 6383; -- Obtained <number> gil. KEYITEM_OBTAINED = 6385; -- Obtained key item: <keyitem>. BEASTMEN_BANNER = 7117; -- There is a beastmen's banner. FISHING_MESSAGE_OFFSET = 7537; -- You can't fish here. ALREADY_OBTAINED_TELE = 7641; -- You already possess the gate crystal for this telepoint. -- Conquest CONQUEST = 7204; -- You've earned conquest points! -- Quest Dialog SENSE_OF_FOREBODING = 6397; -- You are suddenly overcome with a sense of foreboding... NOTHING_OUT_OF_ORDINARY = 7647; -- There is nothing out of the ordinary here. -- conquest Base CONQUEST_BASE = 7036; -- Tallying conquest results... --chocobo digging DIG_THROW_AWAY = 7550; -- You dig up$, but your inventory is full. You regretfully throw the # away. FIND_NOTHING = 7552; -- You dig and you dig, but find nothing.
gpl-3.0
UnfortunateFruit/darkstar
scripts/commands/hp.lua
26
1049
--------------------------------------------------------------------------------------------------- -- func: !hp <amount> <player> -- desc: Sets the GM or target players health. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "is" }; function onTrigger(player, hp, target) if (hp == nil) then player:PrintToPlayer("You must enter a valid amount."); player:PrintToPlayer( "@hp <amount> <player>" ); return; end if (target == nil) then if (player:getHP() > 0) then player:setHP(hp); end else local targ = GetPlayerByName(target); if (targ ~= nil) then if (targ:getHP() > 0) then targ:setHP(hp); end else player:PrintToPlayer( string.format( "Player named '%s' not found!", target ) ); player:PrintToPlayer( "@hp <amount> <player>" ); end end end
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Castle_Oztroja/npcs/relic.lua
42
1845
----------------------------------- -- Area: Castle Oztroja -- NPC: <this space intentionally left blank> -- @pos -104 -73 85 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/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") == 18263 and trade:getItemCount() == 4 and trade:hasItemQty(18263,1) and trade:hasItemQty(1571,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1457,1)) then player:startEvent(59,18264); 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 == 59) then if (player:getFreeSlotsCount() < 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18264); player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1456); else player:tradeComplete(); player:addItem(18264); player:addItem(1456,30); player:messageSpecial(ITEM_OBTAINED,18264); player:messageSpecial(ITEMS_OBTAINED,1456,30); player:setVar("RELIC_IN_PROGRESS",0); end end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Caedarva_Mire/npcs/Runic_Portal.lua
25
2671
----------------------------------- -- Area: Caedarva Mire -- NPC: Runic Portal -- Caedarva Mire Teleporter Back to Aht Urhgan Whitegate -- @pos -264 -6 -28 79 (Dvucca) -- @pos 524 -28 -503 79 (Azouph) ----------------------------------- package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Caedarva_Mire/TextIDs"); require("scripts/globals/teleports"); require("scripts/globals/missions"); require("scripts/globals/besieged"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local X = player:getXPos(); local Z = player:getZPos(); if ((X < -258.512 and X > -270.512) and (Z < -22.285 and Z > -34.285)) then -- Dvucca Staging Point if (player:getCurrentMission(TOAU) == IMMORTAL_SENTRIES and player:getVar("AhtUrganStatus") == 1) then player:startEvent(125); elseif (player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then if (hasRunicPortal(player,2) == 1) then player:startEvent(134); else player:startEvent(125); end else player:messageSpecial(RESPONSE); end else -- Azouph Staging Point if (player:getCurrentMission(TOAU) == IMMORTAL_SENTRIES and player:getVar("AhtUrganStatus") == 1) then player:startEvent(124); elseif (player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then if (hasRunicPortal(player,1) == 1) then player:startEvent(134); else player:startEvent(124); end else player:messageSpecial(RESPONSE); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 124 and option == 1) then player:addNationTeleport(AHTURHGAN,2); toChamberOfPassage(player); elseif (csid == 125 and option == 1) then player:addNationTeleport(AHTURHGAN,4); toChamberOfPassage(player); elseif ((csid == 134 or 131) and option == 1) then toChamberOfPassage(player); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Gusgen_Mines/npcs/Treasure_Chest.lua
13
3763
----------------------------------- -- Area: Gusgen Mines -- NPC: Treasure Chest -- Involved In Quest: The Goblin Tailor -- @zone 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/treasure"); require("scripts/zones/Gusgen_Mines/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --trade:hasItemQty(1031,1); -- Treasure Key --trade:hasItemQty(1115,1); -- Skeleton Key --trade:hasItemQty(1023,1); -- Living Key --trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1031,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: The Goblin Tailor Quest ----------- if (player:getQuestStatus(JEUNO,THE_GOBLIN_TAILOR) >= QUEST_ACCEPTED and VanadielRSELocation() == 1 and VanadielRSERace() == player:getRace() and player:hasKeyItem(MAGICAL_PATTERN) == false) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then local respawn = false; -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then respawn = true; player:addKeyItem(MAGICAL_PATTERN); player:messageSpecial(KEYITEM_OBTAINED,MAGICAL_PATTERN); else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID(),respawn); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1031); 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
nesstea/darkstar
scripts/globals/abilities/divine_waltz.lua
19
2310
----------------------------------- -- Ability: Divine Waltz -- Heals party members within area of effect. -- Obtained: Dancer Level 25 -- TP Required: 40% -- Recast Time: 00:13 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (target:getHP() == 0) then return MSGBASIC_CANNOT_ON_THAT_TARG,0; elseif (player:hasStatusEffect(EFFECT_SABER_DANCE)) then return MSGBASIC_UNABLE_TO_USE_JA2, 0; elseif (player:hasStatusEffect(EFFECT_TRANCE)) then return 0,0; elseif (player:getTP() < 400) then return MSGBASIC_NOT_ENOUGH_TP,0; else -- Apply waltz recast modifiers if (player:getMod(MOD_WALTZ_RECAST)~=0) then local recastMod = -130 * (player:getMod(MOD_WALTZ_RECAST)); -- 650 ms per 5% (per merit) if (recastMod < 0) then --TODO end end return 0,0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance, and only deduct once instead of for each target. if (player:getID() == target:getID() and player:hasStatusEffect(EFFECT_TRANCE) == false) then player:delTP(400); end; -- Grabbing variables. local vit = target:getStat(MOD_VIT); local chr = player:getStat(MOD_CHR); local mjob = player:getMainJob(); --19 for DNC main. local sjob = player:getSubJob(); local cure = 0; -- Performing sj mj check. if (mjob == 19) then cure = (vit+chr)*0.25+60; end if (sjob == 19) then cure = (vit+chr)*0.125+60; end -- Apply waltz modifiers cure = math.floor(cure * (1.0 + (player:getMod(MOD_WALTZ_POTENTCY)/100))); -- Cap the final amount to max HP. if ((target:getMaxHP() - target:getHP()) < cure) then cure = (target:getMaxHP() - target:getHP()); end -- Applying server mods.... cure = cure * CURE_POWER; target:restoreHP(cure); target:wakeUp(); player:updateEnmityFromCure(target,cure); return cure; end;
gpl-3.0
VurtualRuler98/kswep2-NWI
lua/weapons/weapon_kswepi2_m40a1/shared.lua
1
3534
--[[ Copyright 2015 vurtual VurtualRuler98@gmail.com vurtual.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. ]]-- if (SERVER) then AddCSLuaFile("shared.lua") end if (CLIENT) then SWEP.PrintName = "ins2 M40A1" SWEP.Author = "vurtual" SWEP.Slot = 2 SWEP.SlotPos = 0 end SWEP.Anims = SWEP.Anims or {} SWEP.Category = "KSwep Primary" SWEP.Base = "weapon_kswep" SWEP.Primary.Delay = 0.3 SWEP.IronSightHeight=2.8 SWEP.Primary.Damage = 40 SWEP.Primary.Spread = 0.0021 SWEP.Spawnable = true SWEP.DefaultZerodata = { mils=false, bc=0.393, min=100, max=100, step=0, default=100, battlesight=false } SWEP.MuzzleVelMod=1.04 SWEP.MagClass="Box" SWEP.DrawOnce=false SWEP.AdminSpawnable = true SWEP.ViewModel = "models/weapons/v_m40a1.mdl" SWEP.WorldModel = "models/weapons/w_snip_awp.mdl" SWEP.FlashlightModel="models/weapons/upgrades/a_flashlight_band.mdl" SWEP.LaserModel="models/weapons/upgrades/a_laser_band.mdl" SWEP.UseHands = false SWEP.MagSize = 5 SWEP.MaxMags = 5 SWEP.MaxMagsBonus = 20 SWEP.Primary.ClipSize = SWEP.MagSize SWEP.Caliber = "vammo_762x51_mk316mod0" SWEP.MagType = "box_762x51" SWEP.SingleClips=true SWEP.ReloadClipSize=20 SWEP.Primary.Sound = Sound("Weapon_m40a1.Single") SWEP.Primary.SoundSup = Sound("Weapon_m40a1.SingleSilenced") SWEP.Primary.SoundEmpty = Sound("weapon_m40a1.Empty") SWEP.ViewModelFlip = false SWEP.Secondary.Ammo = "" SWEP.CurrentlyReloading=0 SWEP.ReloadAnimTime=0 SWEP.RecoilMassModifier=0.075 SWEP.HandlingModifier=180 SWEP.InsAnims=true SWEP.Auto=false SWEP.Firemode=true SWEP.HoldType="ar2" SWEP.HoldOpen=false SWEP.Length=44 SWEP.OpenBolt=true SWEP.SingleReloadFiringPin=true SWEP.LengthSup=10 SWEP.Suppressable=true SWEP.SuppressorModel="models/weapons/upgrades/a_suppressor_sec.mdl" SWEP.MuzzleVelModSup= 1.01 SWEP.RecoilModSup=1 SWEP.SpreadModSup=0 SWEP.ReloadEjectsRound=true SWEP.IdleType="passive" SWEP.SelectFire=false --SWEP.MidReloadAnimEmpty=ACT_VM_RELOAD_INSERT_PULL SWEP.Anims.StartReloadAnim = ACT_VM_RELOAD SWEP.Anims.MidReloadAnim = ACT_VM_RELOAD_INSERT SWEP.Anims.EndReloadAnim = ACT_VM_RELOAD_END --SWEP.MidReloadAnimEmpty=ACT_VM_RELOADEMPTY --SWEP.SafetyAnim=ACT_VM_FIREMODE --SWEP.SingleReloadChambers=true SWEP.SingleReload=true SWEP.IronSightsPos = Vector(-2.81, -4, 0.18) SWEP.IronSightsAng = Vector(0.1, 0, 0) SWEP.ScopeOffsetPos=Vector(0,0,-0.052) SWEP.ScopeOffsetAng=Vector(0,0,0) SWEP.InsNoIronAnim=true SWEP.MergeAttachments = { } SWEP.DefaultSight="models/weapons/upgrades/a_standard_m40.mdl" SWEP.InsAttachments=true SWEP.Anims.InitialDrawAnim=ACT_VM_READY SWEP.CanFlashlight=true SWEP.UseDelayForBolt=true SWEP.WaitShot=false function SWEP:ReloadAct(force) self:ReloadTube() end function SWEP:DiscoverModelAnims() self:SetAnim("ShootAnim",self:DiscoverAnim("ACT_VM_PRIMARYATTACK_START")) self:SetAnim("IronShootAnim",self:DiscoverAnim("ACT_VM_ISHOOT_START")) self:SetAnim("RunAnim",self:DiscoverAnim("ACT_VM_SPRINT")) self:SetAnim("BoltAnim",self:DiscoverAnim("ACT_VM_PRIMARYATTACK_END")) self:SetAnim("BoltAnimIron",self:DiscoverAnim("ACT_VM_ISHOOT_END")) end
apache-2.0
UnfortunateFruit/darkstar
scripts/zones/Alzadaal_Undersea_Ruins/npcs/qm4.lua
8
1196
----------------------------------- -- Area: Alzadaal Undersea Ruins -- NPC: ??? (Spawn Wulgaru(ZNM T2)) -- @pos -22 -4 204 72 ----------------------------------- package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(2597,1) and trade:getItemCount() == 1) then -- Trade Opalus Gem player:tradeComplete(); SpawnMob(17072179,180):updateClaim(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/cream_puff.lua
18
1265
----------------------------------------- -- ID: 5718 -- Item: Cream Puff -- Food Effect: 30 mintutes, All Races ----------------------------------------- -- Intelligence +7 -- HP -10 -- Resist Slow ----------------------------------------- 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,5718); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_INT, 7); target:addMod(MOD_HP, -10); target:addMod(MOD_SLOWRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_INT, 7); target:delMod(MOD_HP, -10); target:delMod(MOD_SLOWRES, 5); end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/garpike.lua
18
1307
----------------------------------------- -- ID: 5472 -- Item: Garpike -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 3 -- Mind -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5472); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_MND, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_MND, -5); end;
gpl-3.0
FailcoderAddons/supervillain-ui
SVUI_UnitFrames/libs/Plugins/oUF_KungFu/oUF_KungFu.lua
1
8759
--GLOBAL NAMESPACE local _G = _G; --LUA local unpack = _G.unpack; local select = _G.select; local assert = _G.assert; local error = _G.error; local print = _G.print; local pairs = _G.pairs; local next = _G.next; local tostring = _G.tostring; local type = _G.type; if select(2, UnitClass('player')) ~= "MONK" then return end --BLIZZARD API local UnitStagger = _G.UnitStagger; local UnitPower = _G.UnitPower; local UnitPowerMax = _G.UnitPowerMax; local UnitHealthMax = _G.UnitHealthMax; local UnitHasVehicleUI = _G.UnitHasVehicleUI; local GetLocale = _G.GetLocale; local GetShapeshiftFormID = _G.GetShapeshiftFormID; local UnitAura = _G.UnitAura; local UnitHasVehiclePlayerFrameUI = _G.UnitHasVehiclePlayerFrameUI; local MonkStaggerBar = _G.MonkStaggerBar; local SPELL_POWER_CHI = Enum.PowerType.Chi; -- _G.SPELL_POWER_CHI wasn't resolving properly to 12 the way it needed to local parent, ns = ... local oUF = ns.oUF local floor = math.floor; local DM_L = {}; if GetLocale() == "enUS" then DM_L["Stagger"] = "Stagger" DM_L["Light Stagger"] = "Light Stagger" DM_L["Moderate Stagger"] = "Moderate Stagger" DM_L["Heavy Stagger"] = "Heavy Stagger" elseif GetLocale() == "frFR" then DM_L["Stagger"] = "Report" DM_L["Light Stagger"] = "Report mineur" DM_L["Moderate Stagger"] = "Report mod??" DM_L["Heavy Stagger"] = "Report majeur" elseif GetLocale() == "itIT" then DM_L["Stagger"] = "Noncuranza" DM_L["Light Stagger"] = "Noncuranza Parziale" DM_L["Moderate Stagger"] = "Noncuranza Moderata" DM_L["Heavy Stagger"] = "Noncuranza Totale" elseif GetLocale() == "deDE" then DM_L["Stagger"] = "Staffelung" DM_L["Light Stagger"] = "Leichte Staffelung" DM_L["Moderate Stagger"] = "Moderate Staffelung" DM_L["Heavy Stagger"] = "Schwere Staffelung" elseif GetLocale() == "zhCN" then DM_L["Stagger"] = "醉拳" DM_L["Light Stagger"] = "轻度醉拳" DM_L["Moderate Stagger"] = "中度醉拳" DM_L["Heavy Stagger"] = "重度醉拳" elseif GetLocale() == "ruRU" then DM_L["Stagger"] = "Пошатывание" DM_L["Light Stagger"] = "Легкое пошатывание" DM_L["Moderate Stagger"] = "Умеренное пошатывание" DM_L["Heavy Stagger"] = "Сильное пошатывание" else DM_L["Stagger"] = "Stagger" DM_L["Light Stagger"] = "Light Stagger" DM_L["Moderate Stagger"] = "Moderate Stagger" DM_L["Heavy Stagger"] = "Heavy Stagger" end local STANCE_OF_THE_STURY_OX_ID = 23; local DEFAULT_BREW_COLOR = {0.91, 0.75, 0.25, 0.5}; local BREW_COLORS = { [124275] = {0, 1, 0, 1}, -- Light [124274] = {1, 0.5, 0, 1}, -- Moderate [124273] = {1, 0, 0, 1}, -- Heavy }; local DEFAULT_STAGGER_COLOR = {1, 1, 1, 0.5}; local STAGGER_COLORS = { [124275] = {0.2, 0.8, 0.2, 1}, -- Light [124274] = {1.0, 0.8, 0.2, 1}, -- Moderate [124273] = {1.0, 0.4, 0.2, 1}, -- Heavy }; local STAGGER_DEBUFFS = { [124275] = true, -- Light [124274] = true, -- Moderate [124273] = true, -- Heavy }; local CURRENT_STAGGER_COLOR = {1, 1, 1, 0.5}; local CURRENT_BREW_COLOR = {0.91, 0.75, 0.25, 0.5}; local CHI_COLORS = { [1] = {.57, .63, .35, 1}, [2] = {.47, .63, .35, 1}, [3] = {.37, .63, .35, 1}, [4] = {.27, .63, .33, 1}, [5] = {.17, .63, .33, 1}, [6] = {0, .63, .33, 1}, } local function getStaggerAmount() for i = 1, 40 do local _, _, _, _, _, _, _, _, _, _, spellID, _, _, _, amount = UnitDebuff("player", i) if STAGGER_DEBUFFS[spellID] then if (spellID) then CURRENT_STAGGER_COLOR = STAGGER_COLORS[spellID] or DEFAULT_STAGGER_COLOR CURRENT_BREW_COLOR = BREW_COLORS[spellID] or DEFAULT_BREW_COLOR else CURRENT_STAGGER_COLOR = DEFAULT_STAGGER_COLOR CURRENT_BREW_COLOR = DEFAULT_BREW_COLOR end return amount end end return 0 end local Update = function(self, event, unit) if(unit and unit ~= self.unit) then return end local bar = self.KungFu local stagger = bar.DrunkenMaster local spec = GetSpecialization() if(bar.PreUpdate) then bar:PreUpdate(event) end local light = UnitPower("player", SPELL_POWER_CHI) local numPoints = UnitPowerMax("player", SPELL_POWER_CHI) if UnitHasVehicleUI("player") then bar:Hide() else bar:Show() end if spec == 3 then -- magic number 3 is windwalker if bar.numPoints ~= numPoints then if numPoints == 6 then bar[5]:Show() bar[6]:Show() elseif numPoints == 5 then bar[5]:Show() bar[6]:Hide() else bar[5]:Hide() bar[6]:Hide() end end end for i = 1, 6 do local orb = bar[i] if(orb) then if i <= light then orb:Show() else orb:Hide() end end end bar.numPoints = numPoints if(stagger.available) then local staggering = getStaggerAmount() if staggering == 0 then stagger:SetValue(0) stagger:FadeOut() else stagger:FadeIn() local health = UnitHealth("player") local maxHealth = UnitHealthMax("player") local staggerTotal = UnitStagger("player") if staggerTotal == 0 and staggering > 0 then staggerTotal = staggering * 10 end local staggerPercent = staggerTotal / maxHealth * 100 local currentStagger = floor(staggerPercent) stagger:SetMinMaxValues(0, 100) if(staggerPercent == 0) then stagger:SetStatusBarColor(unpack(DEFAULT_BREW_COLOR)) else stagger:SetStatusBarColor(unpack(CURRENT_BREW_COLOR)) end stagger:SetValue(staggerPercent) -- local icon = stagger.icon -- if(icon) then -- icon:SetVertexColor(unpack(CURRENT_STAGGER_COLOR)) -- end if(stagger.PostUpdate) then stagger:PostUpdate(maxHealth, currentStagger, staggerPercent) end end end if(bar.PostUpdate) then bar:PostUpdate(event) end end local ProxyDisable = function(self, element) if(element:IsShown()) then element:Hide() end element.available = false; self:UnregisterEvent('UNIT_AURA', Update) end local ProxyEnable = function(self, element) if(not element.isEnabled) then element.available = false; return end element:Show() element.available = true; self:RegisterEvent('UNIT_AURA', Update) end local Visibility = function(self, ...) local bar = self.KungFu; local stagger = bar.DrunkenMaster; if(STANCE_OF_THE_STURY_OX_ID ~= GetShapeshiftFormID() or UnitHasVehiclePlayerFrameUI("player")) then ProxyDisable(self, stagger) else ProxyEnable(self, stagger) return Update(self, ...) end end local Path = function(self, ...) return (self.KungFu.Override or Visibility)(self, ...) end local ForceUpdate = function(element) return Path(element.__owner, "ForceUpdate", element.__owner.unit) end local function Enable(self, unit) if(unit ~= 'player') then return end local bar = self.KungFu local maxBars = UnitPowerMax("player", SPELL_POWER_CHI) if bar then local stagger = bar.DrunkenMaster stagger.__owner = self stagger.ForceUpdate = ForceUpdate self:RegisterEvent("PLAYER_ENTERING_WORLD", Update) self:RegisterEvent("UNIT_POWER_UPDATE", Update) self:RegisterEvent("PLAYER_LEVEL_UP", Update) self:RegisterEvent('UNIT_DISPLAYPOWER', Path) self:RegisterEvent('UPDATE_SHAPESHIFT_FORM', Path) for i = 1, 6 do if not bar[i]:GetStatusBarTexture() then bar[i]:SetStatusBarTexture([=[Interface\TargetingFrame\UI-StatusBar]=]) end bar[i]:SetStatusBarColor(unpack(CHI_COLORS[i])) bar[i]:SetFrameLevel(bar:GetFrameLevel() + 1) bar[i]:GetStatusBarTexture():SetHorizTile(false) end bar.numPoints = maxBars if(stagger:IsObjectType'StatusBar' and not stagger:GetStatusBarTexture()) then stagger:SetStatusBarTexture(0.91, 0.75, 0.25) end stagger:SetStatusBarColor(unpack(DEFAULT_BREW_COLOR)) stagger:SetMinMaxValues(0, 100) stagger:SetValue(0) MonkStaggerBar.Hide = MonkStaggerBar.Show MonkStaggerBar:UnregisterEvent'PLAYER_ENTERING_WORLD' MonkStaggerBar:UnregisterEvent'PLAYER_SPECIALIZATION_CHANGED' MonkStaggerBar:UnregisterEvent'UNIT_DISPLAYPOWER' MonkStaggerBar:UnregisterEvent'UPDATE_VEHICLE_ACTIONBAR' MonkStaggerBar:UnregisterEvent'UNIT_EXITED_VEHICLE' return true end end local function Disable(self) if self.KungFu then self:UnregisterEvent("PLAYER_ENTERING_WORLD", Update) self:UnregisterEvent("UNIT_POWER_UPDATE", Update) self:UnregisterEvent("PLAYER_LEVEL_UP", Update) self:UnregisterEvent("UNIT_DISPLAYPOWER", Path) self:UnregisterEvent('UPDATE_SHAPESHIFT_FORM', Path) MonkStaggerBar.Show = nil MonkStaggerBar:Show() MonkStaggerBar:UnregisterEvent'PLAYER_ENTERING_WORLD' MonkStaggerBar:UnregisterEvent'PLAYER_SPECIALIZATION_CHANGED' MonkStaggerBar:UnregisterEvent'UNIT_DISPLAYPOWER' MonkStaggerBar:UnregisterEvent'UPDATE_VEHICLE_ACTIONBAR' MonkStaggerBar:UnregisterEvent'UNIT_EXITED_VEHICLE' end end oUF:AddElement('KungFu', Update, Enable, Disable)
mit
UnfortunateFruit/darkstar
scripts/zones/Northern_San_dOria/npcs/Pellimie.lua
38
1025
----------------------------------- -- Area: Northern San d'Oria -- NPC: Pellimie -- Type: Standard Dialogue NPC -- @zone: 231 -- @pos 145.459 0.000 131.540 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,PELLIMIE_DIALOG); 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
nesstea/darkstar
scripts/zones/Port_San_dOria/npcs/Crilde.lua
13
1354
----------------------------------- -- Area: Port San d'Oria -- NPC: Crilde -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x239); 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
DigiTechs/ROBLOXIRCBot
plugins/version.lua
1
3440
-- version plugin -- returns ROBLOX versions on '!versions' local http = require("http") local url = "http://setup.%sroblox%s.com/version" local surl = "http://setup.%sroblox%s.com/versionQTStudio" local timeout = 60*60 -- every hour local verfile = "version.txt" local timefile = "ver-time.txt" local time do local f = io.open(timefile, "r") if f then time = tonumber(f:read("*a")) f:close() else time = os.time() end end local function VersionCommand(client, user, channel, place) local pl if not place[1] then place[1] = "production" end if place[1] ~= "production" then pl = place[1].."." end local succ, version = http.get(string.format(url, pl or "", pl and "labs" or "")) if version then client:sendChat(channel or user.nick, string.format("%s: ROBLOX Player for %s is currently %s", user.nick, place[1], version)) else client:sendChat(channel or user.nick, string.format("%s: Unknown subdomain: %s", user.nick, place[1])) end end local function StudioVersionCommand(client, user, channel, place) local pl if not place[1] then place[1] = "production" end if place[1] ~= "production" then pl = place[1].."." end local succ, version = http.get(string.format(surl, pl or "", pl and "labs" or "")) if version then client:sendChat(channel or user.nick, string.format("%s: ROBLOX Studio for %s is currently %s", user.nick, place[1], version)) else client:sendChat(channel or user.nick, string.format("%s: Unknown subdomain: %s", user.nick, place[1])) end end local function check(client) local succ, cli = http.get(string.format(url, "", "")) local succ, stu = http.get(string.format(surl, "", "")) local f, err = io.open(verfile, "r") local ccli, cstu if f then --print(f, err) f:seek("set") ccli = f:read("*l") cstu = f:read("*l") f:close() end --print("Current client:", ccli) --print("Current studio:", cstu) if ccli and ccli ~= cli then print("Client update") for channel, _ in next, client.channels do client:sendChat(channel, string.format("ROBLOX Player updated from version %s to version %s", ccli, cli)) end end if cstu and cstu ~= stu then print("Studio update") for channel, _ in next, client.channels do client:sendChat(channel, string.format("ROBLOX Studio updated from version %s to version %s", cstu, stu)) end end if ccli ~= cli or cstu ~= stu then -- one changed, write to file local f = io.open(verfile, "w") f:write(cli,"\n",stu,"\n") f:close() end end local function DoVersionCheck(client) if os.time() - time > timeout then check(client) time = os.time() end end local function OverrideCheckCommand(client, user, channel, msg) if client:isop(user) then if msg[1] == "doTest" then print("Doing force-update test...") local f = io.open(verfile, "w") f:write("test","\n","test","\n") f:close() end check(client) end end local function LastCheckCommand(client, user, channel, msg) client:sendChat(channel or user.nick, string.format("%s: Updates were last checked at %s", user.nick, os.date("!%c", time))) end return function(client) client:hookCommand("version", VersionCommand) client:hookCommand("studioVer", StudioVersionCommand) client:hookCommand("checkOverride", OverrideCheckCommand) client:hookCommand("lastCheck", LastCheckCommand) client:hook("OnRaw", function() DoVersionCheck(client) end) end, function(client) local f = io.open(timefile, "w") f:write(time) f:close() end
mit
zuzuf/TA3D
src/ta3d/src/luajit/lib/dis_arm.lua
2
15032
---------------------------------------------------------------------------- -- LuaJIT ARM disassembler module. -- -- Copyright (C) 2005-2010 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- It disassembles most user-mode ARMv7 instructions -- NYI: Advanced SIMD and VFP instructions. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local concat = table.concat local bit = require("bit") local band, bor, ror, tohex = bit.band, bit.bor, bit.ror, bit.tohex local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift ------------------------------------------------------------------------------ -- Opcode maps ------------------------------------------------------------------------------ local map_loadc = { shift = 9, mask = 7, [5] = { shift = 0, mask = 0 -- NYI VFP load/store. }, _ = { shift = 0, mask = 0 -- NYI ldc, mcrr, mrrc. }, } local map_datac = { shift = 24, mask = 1, [0] = { shift = 9, mask = 7, [5] = { shift = 0, mask = 0 -- NYI VFP data. }, _ = { shift = 0, mask = 0 -- NYI cdp, mcr, mrc. }, }, "svcT", } local map_loadcu = { shift = 0, mask = 0, -- NYI unconditional CP load/store. } local map_datacu = { shift = 0, mask = 0, -- NYI unconditional CP data. } local map_simddata = { shift = 0, mask = 0, -- NYI SIMD data. } local map_simdload = { shift = 0, mask = 0, -- NYI SIMD load/store, preload. } local map_preload = { shift = 0, mask = 0, -- NYI preload. } local map_media = { shift = 20, mask = 31, [0] = false, { --01 shift = 5, mask = 7, [0] = "sadd16DNM", "sasxDNM", "ssaxDNM", "ssub16DNM", "sadd8DNM", false, false, "ssub8DNM", }, { --02 shift = 5, mask = 7, [0] = "qadd16DNM", "qasxDNM", "qsaxDNM", "qsub16DNM", "qadd8DNM", false, false, "qsub8DNM", }, { --03 shift = 5, mask = 7, [0] = "shadd16DNM", "shasxDNM", "shsaxDNM", "shsub16DNM", "shadd8DNM", false, false, "shsub8DNM", }, false, { --05 shift = 5, mask = 7, [0] = "uadd16DNM", "uasxDNM", "usaxDNM", "usub16DNM", "uadd8DNM", false, false, "usub8DNM", }, { --06 shift = 5, mask = 7, [0] = "uqadd16DNM", "uqasxDNM", "uqsaxDNM", "uqsub16DNM", "uqadd8DNM", false, false, "uqsub8DNM", }, { --07 shift = 5, mask = 7, [0] = "uhadd16DNM", "uhasxDNM", "uhsaxDNM", "uhsub16DNM", "uhadd8DNM", false, false, "uhsub8DNM", }, { --08 shift = 5, mask = 7, [0] = "pkhbtDNMU", false, "pkhtbDNMU", { shift = 16, mask = 15, [15] = "sxtb16DMU", _ = "sxtab16DNMU", }, "pkhbtDNMU", "selDNM", "pkhtbDNMU", }, false, { --0a shift = 5, mask = 7, [0] = "ssatDxMu", "ssat16DxM", "ssatDxMu", { shift = 16, mask = 15, [15] = "sxtbDMU", _ = "sxtabDNMU", }, "ssatDxMu", false, "ssatDxMu", }, { --0b shift = 5, mask = 7, [0] = "ssatDxMu", "revDM", "ssatDxMu", { shift = 16, mask = 15, [15] = "sxthDMU", _ = "sxtahDNMU", }, "ssatDxMu", "rev16DM", "ssatDxMu", }, { --0c shift = 5, mask = 7, [3] = { shift = 16, mask = 15, [15] = "uxtb16DMU", _ = "uxtab16DNMU", }, }, false, { --0e shift = 5, mask = 7, [0] = "usatDwMu", "usat16DwM", "usatDwMu", { shift = 16, mask = 15, [15] = "uxtbDMU", _ = "uxtabDNMU", }, "usatDwMu", false, "usatDwMu", }, { --0f shift = 5, mask = 7, [0] = "usatDwMu", "rbitDM", "usatDwMu", { shift = 16, mask = 15, [15] = "uxthDMU", _ = "uxtahDNMU", }, "usatDwMu", "revshDM", "usatDwMu", }, { --10 shift = 12, mask = 15, [15] = { shift = 5, mask = 7, "smuadNMS", "smuadxNMS", "smusdNMS", "smusdxNMS", }, _ = { shift = 5, mask = 7, [0] = "smladNMSD", "smladxNMSD", "smlsdNMSD", "smlsdxNMSD", }, }, false, false, false, { --14 shift = 5, mask = 7, [0] = "smlaldDNMS", "smlaldxDNMS", "smlsldDNMS", "smlsldxDNMS", }, { --15 shift = 5, mask = 7, [0] = { shift = 12, mask = 15, [15] = "smmulNMS", _ = "smmlaNMSD", }, { shift = 12, mask = 15, [15] = "smmulrNMS", _ = "smmlarNMSD", }, false, false, false, false, "smmlsNMSD", "smmlsrNMSD", }, false, false, { --18 shift = 5, mask = 7, [0] = { shift = 12, mask = 15, [15] = "usad8NMS", _ = "usada8NMSD", }, }, false, { --1a shift = 5, mask = 3, [2] = "sbfxDMvw", }, { --1b shift = 5, mask = 3, [2] = "sbfxDMvw", }, { --1c shift = 5, mask = 3, [0] = { shift = 0, mask = 15, [15] = "bfcDvX", _ = "bfiDMvX", }, }, { --1d shift = 5, mask = 3, [0] = { shift = 0, mask = 15, [15] = "bfcDvX", _ = "bfiDMvX", }, }, { --1e shift = 5, mask = 3, [2] = "ubfxDMvw", }, { --1f shift = 5, mask = 3, [2] = "ubfxDMvw", }, } local map_load = { shift = 21, mask = 9, { shift = 20, mask = 5, [0] = "strtDL", "ldrtDL", [4] = "strbtDL", [5] = "ldrbtDL", }, _ = { shift = 20, mask = 5, [0] = "strDL", "ldrDL", [4] = "strbDL", [5] = "ldrbDL", } } local map_load1 = { shift = 4, mask = 1, [0] = map_load, map_media, } local map_loadm = { shift = 20, mask = 1, [0] = { shift = 23, mask = 3, [0] = "stmdaNR", "stmNR", { shift = 16, mask = 63, [45] = "pushR", _ = "stmdbNR", }, "stmibNR", }, { shift = 23, mask = 3, [0] = "ldmdaNR", { shift = 16, mask = 63, [61] = "popR", _ = "ldmNR", }, "ldmdbNR", "ldmibNR", }, } local map_data = { shift = 21, mask = 15, [0] = "andDNPs", "eorDNPs", "subDNPs", "rsbDNPs", "addDNPs", "adcDNPs", "sbcDNPs", "rscDNPs", "tstNP", "teqNP", "cmpNP", "cmnNP", "orrDNPs", "movDPs", "bicDNPs", "mvnDPs", } local map_mul = { shift = 21, mask = 7, [0] = "mulNMSs", "mlaNMSDs", "umaalDNMS", "mlsDNMS", "umullDNMSs", "umlalDNMSs", "smullDNMSs", "smlalDNMSs", } local map_sync = { shift = 20, mask = 15, -- NYI: brackets around N. R(D+1) for ldrexd/strexd. [0] = "swpDMN", false, false, false, "swpbDMN", false, false, false, "strexDMN", "ldrexDN", "strexdDN", "ldrexdDN", "strexbDMN", "ldrexbDN", "strexhDN", "ldrexhDN", } local map_mulh = { shift = 21, mask = 3, [0] = { shift = 5, mask = 3, [0] = "smlabbNMSD", "smlatbNMSD", "smlabtNMSD", "smlattNMSD", }, { shift = 5, mask = 3, [0] = "smlawbNMSD", "smulwbNMS", "smlawtNMSD", "smulwtNMS", }, { shift = 5, mask = 3, [0] = "smlalbbDNMS", "smlaltbDNMS", "smlalbtDNMS", "smlalttDNMS", }, { shift = 5, mask = 3, [0] = "smulbbNMS", "smultbNMS", "smulbtNMS", "smulttNMS", }, } local map_misc = { shift = 4, mask = 7, -- NYI: decode PSR bits of msr. [0] = { shift = 21, mask = 1, [0] = "mrsD", "msrM", }, { shift = 21, mask = 3, "bxM", false, "clzDM", }, { shift = 21, mask = 3, "bxjM", }, { shift = 21, mask = 3, "blxM", }, false, { shift = 21, mask = 3, [0] = "qaddDMN", "qsubDMN", "qdaddDMN", "qdsubDMN", }, false, { shift = 21, mask = 3, "bkptK", }, } local map_datar = { shift = 4, mask = 9, [9] = { shift = 5, mask = 3, [0] = { shift = 24, mask = 1, [0] = map_mul, map_sync, }, { shift = 20, mask = 1, [0] = "strhDL", "ldrhDL", }, { shift = 20, mask = 1, [0] = "ldrdDL", "ldrsbDL", }, { shift = 20, mask = 1, [0] = "strdDL", "ldrshDL", }, }, _ = { shift = 20, mask = 25, [16] = { shift = 7, mask = 1, [0] = map_misc, map_mulh, }, _ = { shift = 0, mask = 0xffffffff, [bor(0xe1a00000)] = "nop", _ = map_data, } }, } local map_datai = { shift = 20, mask = 31, -- NYI: decode PSR bits of msr. Decode imm12. [16] = "movwDW", [20] = "movtDW", [18] = { shift = 0, mask = 0xf00ff, [0] = "nopv6", _ = "msrNW", }, [22] = "msrNW", _ = map_data, } local map_branch = { shift = 24, mask = 1, [0] = "bB", "blB" } local map_condins = { [0] = map_datar, map_datai, map_load, map_load1, map_loadm, map_branch, map_loadc, map_datac } -- NYI: setend. local map_uncondins = { [0] = false, map_simddata, map_simdload, map_preload, false, "blxB", map_loadcu, map_datacu, } ------------------------------------------------------------------------------ local map_gpr = { [0] = "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc", } local map_cond = { [0] = "eq", "ne", "hs", "lo", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al", } local map_shift = { [0] = "lsl", "lsr", "asr", "ror", } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local pos = ctx.pos local extra = "" if ctx.rel then local sym = ctx.symtab[ctx.rel] if sym then extra = "\t->"..sym elseif band(ctx.op, 0x0e000000) ~= 0x0a000000 then extra = "\t; 0x"..tohex(ctx.rel) end end if ctx.hexdump > 0 then ctx.out(format("%08x %s %-5s %s%s\n", ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra)) else ctx.out(format("%08x %-5s %s%s\n", ctx.addr+pos, text, concat(operands, ", "), extra)) end ctx.pos = pos + 4 end -- Fallback for unknown opcodes. local function unknown(ctx) return putop(ctx, ".long", { "0x"..tohex(ctx.op) }) end -- Format operand 2 of load/store opcodes. local function fmtload(ctx, op, pos) local base = map_gpr[band(rshift(op, 16), 15)] local x, ofs local ext = (band(op, 0x04000000) == 0) if not ext and band(op, 0x02000000) == 0 then ofs = band(op, 4095) if band(op, 0x00800000) == 0 then ofs = -ofs end if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end ofs = "#"..ofs elseif ext and band(op, 0x00400000) ~= 0 then ofs = band(op, 15) + band(rshift(op, 4), 0xf0) if band(op, 0x00800000) == 0 then ofs = -ofs end if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end ofs = "#"..ofs else ofs = map_gpr[band(op, 15)] if ext or band(op, 0xfe0) == 0 then elseif band(op, 0xfe0) == 0x60 then ofs = format("%s, rrx", ofs) else local sh = band(rshift(op, 7), 31) if sh == 0 then sh = 32 end ofs = format("%s, %s #%d", ofs, map_shift[band(rshift(op, 5), 3)], sh) end if band(op, 0x00800000) == 0 then ofs = "-"..ofs end end if ofs == "#0" then x = format("[%s]", base) elseif band(op, 0x01000000) == 0 then x = format("[%s], %s", base, ofs) else x = format("[%s, %s]", base, ofs) end if band(op, 0x01200000) == 0x01200000 then x = x.."!" end return x end -- Disassemble a single instruction. local function disass_ins(ctx) local pos = ctx.pos local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4) local op = bor(lshift(b3, 24), lshift(b2, 16), lshift(b1, 8), b0) local operands = {} local suffix = "" local last, name, pat ctx.op = op ctx.rel = nil local cond = rshift(op, 28) local opat if cond == 15 then opat = map_uncondins[band(rshift(op, 25), 7)] else if cond ~= 14 then suffix = map_cond[cond] end opat = map_condins[band(rshift(op, 25), 7)] end while type(opat) ~= "string" do if not opat then return unknown(ctx) end opat = opat[band(rshift(op, opat.shift), opat.mask)] or opat._ end name, pat = match(opat, "^([a-z0-9]*)(.*)") for p in gmatch(pat, ".") do local x = nil if p == "D" then x = map_gpr[band(rshift(op, 12), 15)] elseif p == "N" then x = map_gpr[band(rshift(op, 16), 15)] elseif p == "S" then x = map_gpr[band(rshift(op, 8), 15)] elseif p == "M" then x = map_gpr[band(op, 15)] elseif p == "P" then if band(op, 0x02000000) ~= 0 then x = ror(band(op, 255), 2*band(rshift(op, 8), 15)) else x = map_gpr[band(op, 15)] if band(op, 0xff0) ~= 0 then operands[#operands+1] = x local s = map_shift[band(rshift(op, 5), 3)] local r = nil if band(op, 0xf90) == 0 then if s == "ror" then s = "rrx" else r = "#32" end elseif band(op, 0x10) == 0 then r = "#"..band(rshift(op, 7), 31) else r = map_gpr[band(rshift(op, 8), 15)] end if name == "mov" then name = s; x = r elseif r then x = format("%s %s", s, r) else x = s end end end elseif p == "L" then x = fmtload(ctx, op, pos, false) elseif p == "B" then local addr = ctx.addr + pos + 8 + arshift(lshift(op, 8), 6) if cond == 15 then addr = addr + band(rshift(op, 23), 2) end ctx.rel = addr x = "0x"..tohex(addr) elseif p == "R" then if band(op, 0x00200000) ~= 0 and #operands == 1 then operands[1] = operands[1].."!" end local t = {} for i=0,15 do if band(rshift(op, i), 1) == 1 then t[#t+1] = map_gpr[i] end end x = "{"..concat(t, ", ").."}" elseif p == "W" then x = band(op, 0x0fff) + band(rshift(op, 4), 0xf000) elseif p == "T" then x = "#0x"..tohex(band(op, 0x00ffffff), 6) elseif p == "U" then x = band(rshift(op, 7), 31) if x == 0 then x = nil end elseif p == "u" then x = band(rshift(op, 7), 31) if band(op, 0x40) == 0 then if x == 0 then x = nil else x = "lsl #"..x end else if x == 0 then x = "asr #32" else x = "asr #"..x end end elseif p == "v" then x = band(rshift(op, 7), 31) elseif p == "w" then x = band(rshift(op, 16), 31) elseif p == "x" then x = band(rshift(op, 16), 31) + 1 elseif p == "X" then x = band(rshift(op, 16), 31) - last + 1 elseif p == "K" then x = "#0x"..tohex(band(rshift(op, 4), 0x0000fff0) + band(op, 15), 4) elseif p == "s" then if band(op, 0x00100000) ~= 0 then suffix = "s"..suffix end else assert(false) end if x then last = x if type(x) == "number" then x = "#"..x end operands[#operands+1] = x end end return putop(ctx, name..suffix, operands) end ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code ctx.pos = ofs ctx.rel = nil while ctx.pos < stop do disass_ins(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create_(code, addr, out) local ctx = {} ctx.code = code ctx.addr = addr or 0 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 8 return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass_(code, addr, out) create_(code, addr, out):disass() end -- Return register name for RID. local function regname_(r) return map_gpr[r] end -- Public module functions. module(...) create = create_ disass = disass_ regname = regname_
gpl-2.0
dany-sj/Kings_Bot
bot/nod32bot.lua
1
11132
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '2' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "all", "anti_ads", "anti_bot", "anti_spam", "anti_chat", "banhammer", "boobs", "bot_manager", "botnumber", "broadcast", "calc", "download_media", "feedback", "get", "google", "gps", "ingroup", "inpm", "inrealm", "invite", "leave_ban", "linkpv", "location", "lock_join", "anti_fosh", "left_group", "owners", "plugins", "set", "spam", "stats", "support", "filterworld", "server_manager", "time", "version" }, sudo_users = {233477700},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[ https://github.com/BH-YAGHI/NOD32-BOT.git channel : @Nod32team sodu : @behrooZyaghi ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Grt a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] ch: @Nod32team ]], help_text = [[ 👑kk [username|id] [آیدی،کد،ریپلای] ﹍▁▂▃▃▄▅▅▆▌▍▍▎ 👑bn [ username|id] [آیدی،کد،ریپلای] ﹍▁▁▃▄▄▅▆▇▌▎▎▏ 👑unbn [id] [کد،ایدی،ریپلای ﹍▁▁▂▃▄▅▅▆▌▎▎▏ 😈who دریافت لیست افراد گروه 👑mods دریافت لیست مدیران گروه ﹍▁▁▂▃▄▅▆▌▍▎▏▏ 👑stmod [username] تنظیم مدیر ﹍▁▂▂▃▃▃▄▍▎▎ 👑rmmod [username] حذف مدیر 👑kickme حذف کردن خود از گروه ﹍▁▂▃▄▅▆▍▎▏▏ 👑about توظیحات گروه ﹍▁▂▃▄▅▆▍▍▎▎ 👑stphoto تنظیم عکس گروه ﹍▁▃▄▅▆▇▍▎▎▏ 👑stnam [name] تنظیم نام گروه ﹍▁▂▃▄▅▆▇▍▎▎ 👑rules قوانین گروه ﹍▁▂▃▄▅▆▇▍▎▏▏ 👑id دریافت ای دی تلگرامی خود ﹍▁▂▃▄▅▆▇▍▎▏ 👑hlp راهنمای دستورات بات ﹍▁▂▃▄▅▆▇▌▎▎▏ 😈lock [member|name|bots|leave] قفل [افراد گروه|نام|بات|خروج] 👽unlock [member|name|bots|leave] ازاد کردن قفل [افراد گروه|نام|بات|خروج] ﹍▁▂▃▄▅▆▇▌▍▎▏ 👿st rules [text] گذاشتن قوانین در گروه خود ﹍▁▂▃▄▅▆▇▄▍▍▎▎ 👹st about [text] گذاشتن توضیحات گروه خود ﹍▁▂▃▄▅▆▇▌▍▎ 💀sting تنظیمات گروه ﹍▁▂▃▄▅▆▇▌▍▎▎ 💀nwlink لینک جدید ﹍▁▂▃▄▅▆▇▋▍▎▏ 😈link لینک ﹍▁▂▃▄▅▆▇▌▍▎▏ 👑oner 👑دریافت ایدی صاحب گروه 💀stoner [id] افزودن مدیر به گروه ﹍▂▃▄▅▆▇▍▎▏ 👑stflod [value تنظیم حساسیت اسپ ﹍▂▃▄▅▆▇▍▎▏ 😈bnlis لیست بنشده ها ﹍▁▂▄▄▅▆▇█▉▊▋▌▎▏ همه دستورات بدون /.! کار میکند » فقط مدها، مالک و مدیر می تواند رباتها در گروه اضافه کنید » فقط ناظران و مالک می تواند ضربه، ممنوعیت، رفع ممنوعیت، لینک جدید, لینک، مجموعه عکس، مجموعه نام، قفل، باز کردن، قوانین مجموعه، مجموعه ای در مورد و دستورات تنظیمات استفاده کنید » تنها مالک می تواند شیء، تنظیم اونر استفاده، ترویج، تنزل رتبه و ورود دستورات ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
stewartmiles/flatbuffers
tests/MyGame/Example/Referrable.lua
12
1025
-- automatically generated by the FlatBuffers compiler, do not modify -- namespace: Example local flatbuffers = require('flatbuffers') local Referrable = {} -- the module local Referrable_mt = {} -- the class metatable function Referrable.New() local o = {} setmetatable(o, {__index = Referrable_mt}) return o end function Referrable.GetRootAsReferrable(buf, offset) local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) local o = Referrable.New() o:Init(buf, n + offset) return o end function Referrable_mt:Init(buf, pos) self.view = flatbuffers.view.New(buf, pos) end function Referrable_mt:Id() local o = self.view:Offset(4) if o ~= 0 then return self.view:Get(flatbuffers.N.Uint64, o + self.view.pos) end return 0 end function Referrable.Start(builder) builder:StartObject(1) end function Referrable.AddId(builder, id) builder:PrependUint64Slot(0, id, 0) end function Referrable.End(builder) return builder:EndObject() end return Referrable -- return the module
apache-2.0
bowlofstew/Macaroni
Main/Generators/Cpp/UnitBlockGenerator.lua
2
3090
require "Cpp/Common" require "Cpp/FileGenerator" require "Cpp/NodeInfo" UnitBlockGenerator = { isNested = false, tabs = 0, new = function(self) assert(self.writer ~= nil); assert(self.node.Element ~= nil); setmetatable(self, UnitBlockGenerator) self.block = self.node.Element assert(self.block.TypeName == "Block") return self end, usingStatements = function(self, block) local imports = block.ImportedNodes; for i = 1, #imports do local import = imports[i]; self:writeUsing(import); end end, WriteTopBlocks = function(self) if self.block.Id == "top" then self:writeBlockCodeBlock(self.block) end end, WriteBottomBlocks = function(self) if self.block.Id == "bottom" then self:writeBlockCodeBlock(self.block) end end, WriteIncludeStatements = function(self) if (self.block.Id == "h" or self.block.Id == "h-predef" or self.block.Id == "h-postdef") then self:writeIncludes(self.block) end end, WriteImplementationIncludeStatements = function(self) if self.block.Id == "cpp" or self.block.Id == "cpp-include" then self:writeIncludes(self.block) end if self.block.Id == "cpp-include" then self:writeBlockCodeBlock(self.block) end end, WriteUsingStatements = function(self) if self.block.Id == "cpp" then self:usingStatements(self.block) end end, WritePreDefinitionBlocks = function(self) if self.block.Id == "h-predef" then self:writeBlockCodeBlock(self.block) end end, WriteHeaderDefinitions = function(self) if self.block.Id == "h" then self:writeBlockCodeBlock(self.block) end end, WritePostDefinitionBlocks = function(self) if self.block.Id == "h-postdef" then self:writeBlockCodeBlock(self.block) end end, WriteImplementation = function(self) if self.block.Id == "cpp" then self:writeBlockCodeBlock(self.block) end end, writeIncludes = function(self, block) local imports = block.ImportedNodes; for i = 1, #imports do local import = imports[i]; if (import.Member ~= nil) then self:writeInclude(import); else self:write('// Skipping hollow imported node "' .. import.FullName .. '"' .. " \n"); end end end, writeInclude = function(self, import) local statement = IncludeFiles.createStatementForNode(import); if (statement ~= nil) then self:write(statement); end end, writeUsing = function(self, import) self:write(NodeInfoList[import].using); end, } Util.linkToSubClass(FileGenerator, UnitBlockGenerator);
apache-2.0
nesstea/darkstar
scripts/zones/Western_Altepa_Desert/mobs/King_Vinegarroon.lua
4
2205
----------------------------------- -- Area: Western Altepa Desert -- NM: King Vinegarroon ----------------------------------- require("scripts/globals/status"); require("scripts/globals/titles"); require("scripts/globals/weather"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobDrawIn ----------------------------------- function onMobDrawIn(mob, target) -- todo make him use AoE tp move mob:addTP(3000); end; ----------------------------------- -- onMobDisengage ----------------------------------- function onMobDisengage(mob, weather) if (weather ~= WEATHER_DUST_STORM and weather ~= WEATHER_SAND_STORM) then DespawnMob(mob:getID()); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) ally:addTitle(VINEGAR_EVAPORATOR); -- Set King_Vinegarroon's spawnpoint and respawn time (21-24 hours) UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random(75600,86400)); end; ----------------------------------- -- onAdditionalEffect ----------------------------------- function onAdditionalEffect(mob, player) local resist = applyResistanceAddEffect(mob,player,ELE_EARTH,EFFECT_PETRIFICATION); if (resist <= 0.5) then -- "Has an innate Additional Effect of Petrification on all of its physical attacks. " return 0,0,0; else local duration = 30; if (mob:getMainLvl() > player:getMainLvl()) then duration = duration + (mob:getMainLvl() - player:getMainLvl()) end duration = utils.clamp(duration,1,45); duration = duration * resist; if (not player:hasStatusEffect(EFFECT_PETRIFICATION)) then player:addStatusEffect(EFFECT_PETRIFICATION, 1, 0, duration); end return SUBEFFECT_PETRIFY, MSGBASIC_ADD_EFFECT_STATUS, EFFECT_PETRIFICATION; end end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/dolphin_staff.lua
41
1077
----------------------------------------- -- ID: 17134 -- Item: Dolphin Staff -- Additional Effect: Water Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(3,10); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_WATER, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_WATER,0); dmg = adjustForTarget(target,dmg,ELE_WATER); dmg = finalMagicNonSpellAdjustments(player,target,ELE_WATER,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_WATER_DAMAGE,message,dmg; end end;
gpl-3.0
Xileck/forgottenserver
data/talkactions/scripts/info.lua
21
1561
function onSay(player, words, param) if not player:getGroup():getAccess() then return true end local target = Player(param) if not target then player:sendCancelMessage("Player not found.") return false end if target:getAccountType() > player:getAccountType() then player:sendCancelMessage("You can not get info about this player.") return false end local targetIp = target:getIp() player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "Name: " .. target:getName()) player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "Access: " .. (target:getGroup():getAccess() and "1" or "0")) player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "Level: " .. target:getLevel()) player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "Magic Level: " .. target:getMagicLevel()) player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "Speed: " .. getCreatureSpeed(player:getId())) player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "Position: " .. string.format("(%0.5d / %0.5d / %0.3d)", target:getPosition().x, target:getPosition().y, target:getPosition().z)) player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "IP: " .. Game.convertIpToString(targetIp)) local players = {} for _, tmpPlayer in ipairs(Game.getPlayers()) do if tmpPlayer:getIp() == targetIp and tmpPlayer ~= target then players[#players + 1] = tmpPlayer:getName() .. " [" .. tmpPlayer:getLevel() .. "]" end end if #players > 0 then player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "Other players on same IP: " .. table.concat(players, ", ") .. ".") end return false end
gpl-2.0
nesstea/darkstar
scripts/globals/abilities/thunder_shot.lua
16
2989
----------------------------------- -- Ability: Thunder Shot -- Consumes a Thunder Card to enhance lightning-based debuffs. Deals lightning-based magic damage -- Shock Effect: Enhanced DoT and MND- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/weaponskills"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) --ranged weapon/ammo: You do not have an appropriate ranged weapon equipped. --no card: <name> cannot perform that action. if (player:getWeaponSkillType(SLOT_RANGED) ~= SKILL_MRK or player:getWeaponSkillType(SLOT_AMMO) ~= SKILL_MRK) then return 216,0; end if (player:hasItem(2180, 0) or player:hasItem(2974, 0)) then return 0,0; else return 71, 0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) local params = {}; params.includemab = true; local dmg = (2 * player:getRangedDmg() + player:getAmmoDmg() + player:getMod(MOD_QUICK_DRAW_DMG)) * 1 + player:getMod(MOD_QUICK_DRAW_DMG_PERCENT)/100; dmg = addBonusesAbility(player, ELE_LIGHTNING, target, dmg, params); dmg = dmg * applyResistanceAbility(player,target,ELE_LIGHTNING,SKILL_MRK, (player:getStat(MOD_AGI)/2) + player:getMerit(MERIT_QUICK_DRAW_ACCURACY)); dmg = adjustForTarget(target,dmg,ELE_LIGHTNING); target:takeWeaponskillDamage(player, dmg, SLOT_RANGED, 1, 0, 0); -- targetTPMult is 0 because Quick Draw gives no TP to the mob target:updateEnmityFromDamage(player,dmg); local effects = {}; local counter = 1; local shock = target:getStatusEffect(EFFECT_SHOCK); if (shock ~= nil) then effects[counter] = shock; counter = counter + 1; end local threnody = target:getStatusEffect(EFFECT_THRENODY); if (threnody ~= nil and threnody:getSubPower() == MOD_WATERRES) then effects[counter] = threnody; counter = counter + 1; end if counter > 1 then local effect = effects[math.random(1, counter-1)]; local duration = effect:getDuration(); local startTime = effect:getStartTime(); local tick = effect:getTick(); local power = effect:getPower(); local subpower = effect:getSubPower(); local tier = effect:getTier(); local effectId = effect:getType(); local subId = effect:getSubType(); power = power * 1.2; target:delStatusEffectSilent(effectId); target:addStatusEffect(effectId, power, tick, duration, subId, subpower, tier); local newEffect = target:getStatusEffect(effectId); newEffect:setStartTime(startTime); end local del = player:delItem(2180, 1) or player:delItem(2974, 1) target:updateClaim(player); return dmg; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/bataquiche.lua
35
1468
----------------------------------------- -- ID: 5168 -- Item: Bataquiche -- Food Effect: 30Min, All Races ----------------------------------------- -- Magic 8 -- Agility 1 -- Vitality -2 -- Ranged ATT % 7 -- Ranged ATT Cap 15 ----------------------------------------- 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,5168); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 8); target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -2); target:addMod(MOD_FOOD_RATTP, 7); target:addMod(MOD_FOOD_RATT_CAP, 15); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 8); target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -2); target:delMod(MOD_FOOD_RATTP, 7); target:delMod(MOD_FOOD_RATT_CAP, 15); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/spells/bluemagic/pollen.lua
10
1867
----------------------------------------- -- Spell: Pollen -- Restores HP -- Spell cost: 8 MP -- Monster Type: Vermin -- Spell Type: Magical (Light) -- Blue Magic Points: 1 -- Stat Bonus: CHR+1, HP+5 -- Level: 1 -- Casting Time: 2 seconds -- Recast Time: 5 seconds -- -- Combos: Resist Sleep ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local minCure = 14; local divisor = 1; local constant = -6; local power = getCurePowerOld(caster); local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,true); if(power > 99) then divisor = 57; constant = 33.125; elseif(power > 59) then divisor = 2; constant = 9; end final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); if(target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then --Applying server mods.... final = final * CURE_POWER; end local diff = (target:getMaxHP() - target:getHP()); if(final > diff) then final = diff; end target:addHP(final); if(target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then caster:updateEnmityFromCure(target,final); end spell:setMsg(7); return final; end;
gpl-3.0
rainyear/game-five-eliminate
hello.lua
10
6992
require "AudioEngine" -- for CCLuaEngine traceback function __G__TRACKBACK__(msg) print("----------------------------------------") print("LUA ERROR: " .. tostring(msg) .. "\n") print(debug.traceback()) print("----------------------------------------") end local function main() -- avoid memory leak collectgarbage("setpause", 100) collectgarbage("setstepmul", 5000) local cclog = function(...) print(string.format(...)) end require "hello2" cclog("result is " .. myadd(3, 5)) --------------- local visibleSize = CCDirector:sharedDirector():getVisibleSize() local origin = CCDirector:sharedDirector():getVisibleOrigin() -- add the moving dog local function creatDog() local frameWidth = 105 local frameHeight = 95 -- create dog animate local textureDog = CCTextureCache:sharedTextureCache():addImage("dog.png") local rect = CCRectMake(0, 0, frameWidth, frameHeight) local frame0 = CCSpriteFrame:createWithTexture(textureDog, rect) rect = CCRectMake(frameWidth, 0, frameWidth, frameHeight) local frame1 = CCSpriteFrame:createWithTexture(textureDog, rect) local spriteDog = CCSprite:createWithSpriteFrame(frame0) spriteDog.isPaused = false spriteDog:setPosition(origin.x, origin.y + visibleSize.height / 4 * 3) local animFrames = CCArray:create() animFrames:addObject(frame0) animFrames:addObject(frame1) local animation = CCAnimation:createWithSpriteFrames(animFrames, 0.5) local animate = CCAnimate:create(animation); spriteDog:runAction(CCRepeatForever:create(animate)) -- moving dog at every frame local function tick() if spriteDog.isPaused then return end local x, y = spriteDog:getPosition() if x > origin.x + visibleSize.width then x = origin.x else x = x + 1 end spriteDog:setPositionX(x) end CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(tick, 0, false) return spriteDog end -- create farm local function createLayerFarm() local layerFarm = CCLayer:create() -- add in farm background local bg = CCSprite:create("farm.jpg") bg:setPosition(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2) layerFarm:addChild(bg) -- add land sprite for i = 0, 3 do for j = 0, 1 do local spriteLand = CCSprite:create("land.png") spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2) layerFarm:addChild(spriteLand) end end -- add crop local frameCrop = CCSpriteFrame:create("crop.png", CCRectMake(0, 0, 105, 95)) for i = 0, 3 do for j = 0, 1 do local spriteCrop = CCSprite:createWithSpriteFrame(frameCrop); spriteCrop:setPosition(10 + 200 + j * 180 - i % 2 * 90, 30 + 10 + i * 95 / 2) layerFarm:addChild(spriteCrop) end end -- add moving dog local spriteDog = creatDog() layerFarm:addChild(spriteDog) -- handing touch events local touchBeginPoint = nil local function onTouchBegan(x, y) cclog("onTouchBegan: %0.2f, %0.2f", x, y) touchBeginPoint = {x = x, y = y} spriteDog.isPaused = true -- CCTOUCHBEGAN event must return true return true end local function onTouchMoved(x, y) cclog("onTouchMoved: %0.2f, %0.2f", x, y) if touchBeginPoint then local cx, cy = layerFarm:getPosition() layerFarm:setPosition(cx + x - touchBeginPoint.x, cy + y - touchBeginPoint.y) touchBeginPoint = {x = x, y = y} end end local function onTouchEnded(x, y) cclog("onTouchEnded: %0.2f, %0.2f", x, y) touchBeginPoint = nil spriteDog.isPaused = false end local function onTouch(eventType, x, y) if eventType == "began" then return onTouchBegan(x, y) elseif eventType == "moved" then return onTouchMoved(x, y) else return onTouchEnded(x, y) end end layerFarm:registerScriptTouchHandler(onTouch) layerFarm:setTouchEnabled(true) return layerFarm end -- create menu local function createLayerMenu() local layerMenu = CCLayer:create() local menuPopup, menuTools, effectID local function menuCallbackClosePopup() -- stop test sound effect AudioEngine.stopEffect(effectID) menuPopup:setVisible(false) end local function menuCallbackOpenPopup() -- loop test sound effect local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav") effectID = AudioEngine.playEffect(effectPath) menuPopup:setVisible(true) end -- add a popup menu local menuPopupItem = CCMenuItemImage:create("menu2.png", "menu2.png") menuPopupItem:setPosition(0, 0) menuPopupItem:registerScriptTapHandler(menuCallbackClosePopup) menuPopup = CCMenu:createWithItem(menuPopupItem) menuPopup:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2) menuPopup:setVisible(false) layerMenu:addChild(menuPopup) -- add the left-bottom "tools" menu to invoke menuPopup local menuToolsItem = CCMenuItemImage:create("menu1.png", "menu1.png") menuToolsItem:setPosition(0, 0) menuToolsItem:registerScriptTapHandler(menuCallbackOpenPopup) menuTools = CCMenu:createWithItem(menuToolsItem) local itemWidth = menuToolsItem:getContentSize().width local itemHeight = menuToolsItem:getContentSize().height menuTools:setPosition(origin.x + itemWidth/2, origin.y + itemHeight/2) layerMenu:addChild(menuTools) return layerMenu end -- play background music, preload effect -- uncomment below for the BlackBerry version -- local bgMusicPath = CCFileUtils:sharedFileUtils():fullPathForFilename("background.ogg") local bgMusicPath = CCFileUtils:sharedFileUtils():fullPathForFilename("background.mp3") AudioEngine.playMusic(bgMusicPath, true) local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav") AudioEngine.preloadEffect(effectPath) -- run local sceneGame = CCScene:create() sceneGame:addChild(createLayerFarm()) sceneGame:addChild(createLayerMenu()) CCDirector:sharedDirector():runWithScene(sceneGame) end xpcall(main, __G__TRACKBACK__)
apache-2.0
zuzuf/TA3D
src/ta3d/mods/ta3d/scripts/corgator.lua
2
4733
-- CORGATOR createUnitScript("corgator") __this:piece( "base", "body", "turret", "sleeve", "barrel", "firepoint", "tracks1", "tracks2", "tracks3", "tracks4" ) __this.moving = false __this.once = 0 __this.animCount = 0 local ANIM_SPEED = 0.05 local RESTORE_DELAY = 2.0 local TURRET_TURN_SPEED = 180 __this.SMOKEPIECE1 = __this.body __this.SMOKEPIECE2 = __this.turret #include "exptype.lh" #include "smokeunit.lh" #include "hitweap.lh" __this.RestoreAfterDelay = function(this, delay) this.restoreCount = this.restoreCount + 1 local ncall = this.restoreCount this:sleep( delay ) if ncall ~= this.restoreCount then return end this:turn( this.turret, y_axis, 0, 90 ) end __this.AnimationControl = function(this) local current_tracks = 0 while true do if this.moving or this.once > 0 then if current_tracks == 0 then this:show( this.tracks1 ) this:hide( this.tracks4 ) current_tracks = 1 elseif current_tracks == 1 then this:show( this.tracks2 ) this:hide( this.tracks1 ) current_tracks = 2 elseif current_tracks == 2 then this:show( this.tracks3 ) this:hide( this.tracks2 ) current_tracks = 3 elseif current_tracks == 3 then this:show( this.tracks4 ) this:hide( this.tracks3 ) current_tracks = 0 if this.once > 0 then this.once = this.once - 1 end end this.animCount = this.animCount + 1 end this:sleep( ANIM_SPEED ) end end __this.StartMoving = function(this) this.moving = true this.animCount = 0 end __this.StopMoving = function(this) this.moving = false -- I don't like insta braking. It's not perfect but works for most cases. -- Probably looks goofy when the unit is turtling around, i.e. does not get faster as time increases.. this.once = this.animCount * ANIM_SPEED / 1000 if this.once > 3 then this.once = 3 end end -- Weapons __this.AimFromPrimary = function(this) return this.firepoint end __this.QueryPrimary = function(this) return this.firepoint end __this.AimPrimary = function(this, heading, pitch) this:set_script_value("AimPrimary", false) heading = heading * TA2DEG this:turn( this.turret, y_axis, heading, TURRET_TURN_SPEED ) if this.aiming then return end this.aiming = true this:wait_for_turn( this.turret, y_axis ) this.aiming = false this:start_script( this.RestoreAfterDelay, this, RESTORE_DELAY ) this:set_script_value("AimPrimary", true) end __this.FirePrimary = function(this) this:move_piece_now( this.barrel, z_axis, -1 ) this:move( this.barrel, z_axis, 0, 7.5 ) this:wait_for_move( this.barrel, z_axis ) end __this.SweetSpot = function(this) return this.base end __this.Killed = function(this, severity) if severity >= 0 and severity < 25 then this:explode( this.barrel, BITMAPONLY + BITMAP ) this:explode( this.sleeve, BITMAPONLY + BITMAP ) this:explode( this.body, BITMAPONLY + BITMAP ) this:explode( this.turret, BITMAPONLY + BITMAP ) return 1 elseif severity >= 25 and severity < 50 then this:explode( this.barrel, FALL + BITMAP ) this:explode( this.sleeve, FALL + BITMAP ) this:explode( this.body, BITMAPONLY + BITMAP ) this:explode( this.turret, SHATTER + BITMAP ) return 2 elseif severity >= 50 and severity < 100 then this:explode( this.barrel, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.sleeve, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.body, BITMAPONLY + BITMAP ) this:explode( this.turret, SHATTER + BITMAP ) return 3 -- D-Gunned/Self-D elseif severity >= 100 then this:explode( this.barrel, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.sleeve, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) this:explode( this.body, SHATTER + BITMAP ) this:explode( this.turret, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP ) return 3 end end __this.Create = function(this) this.moving = false this.restoreCount = 0 this.aiming = false this:hide( this.tracks1 ) this:hide( this.tracks2 ) this:hide( this.tracks3 ) while this:get(BUILD_PERCENT_LEFT) > 0 do this:sleep( 0.25 ) end this:start_script( this.AnimationControl, this ) this:start_script( this.SmokeUnit, this ) end
gpl-2.0
nesstea/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Marquis_Cimeries.lua
2
1528
----------------------------------- -- Area: Dynamis Xarcabard -- MOB: Marquis Cimeries ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger"); if (mob:isInBattlefieldList() == false) then mob:addInBattlefieldList(); Animate_Trigger = Animate_Trigger + 512; SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger); if (Animate_Trigger == 32767) then SpawnMob(17330911); -- 142 SpawnMob(17330912); -- 143 SpawnMob(17330177); -- Dynamis Lord GetMobByID(17330183):setSpawn(-364,-35.661,17.254); -- Set Ying and Yang's spawn points to their initial spawn point. GetMobByID(17330184):setSpawn(-364,-35.974,24.254); SpawnMob(17330183); SpawnMob(17330184); activateAnimatedWeapon(); -- Change subanim of all animated weapon end end if (Animate_Trigger == 32767) then ally:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Windurst-Jeuno_Airship/npcs/Gabriele.lua
30
2313
----------------------------------- -- Area: Windurst-Jeuno Airship -- NPC: Gabriele -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Windurst-Jeuno_Airship/TextIDs"] = nil; require("scripts/zones/Windurst-Jeuno_Airship/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 4 do vHour = vHour - 6; end local message = WILL_REACH_WINDURST; if (vHour == -2) then if (vMin >= 47) then vHour = 3; message = WILL_REACH_JEUNO; else vHour = 0; end elseif (vHour == -1) then vHour = 2; message = WILL_REACH_JEUNO; elseif (vHour == 0) then vHour = 1; message = WILL_REACH_JEUNO; elseif (vHour == 1) then if (vMin <= 40) then vHour = 0; message = WILL_REACH_JEUNO; else vHour = 3; end elseif (vHour == 2) then vHour = 2; elseif (vHour == 3) then vHour = 1; end local vMinutes = 0; if (message == WILL_REACH_JEUNO) then vMinutes = (vHour * 60) + 47 - vMin; else -- WILL_REACH_WINDURST vMinutes = (vHour * 60) + 40 - vMin; end if (vMinutes <= 30) then if ( message == WILL_REACH_WINDURST) then message = IN_WINDURST_MOMENTARILY; else -- WILL_REACH_JEUNO message = IN_JEUNO_MOMENTARILY; end elseif (vMinutes < 60) then vHour = 0; end player:messageSpecial( message, math.floor((2.4 * vMinutes) / 60), math.floor( vMinutes / 60 + 0.5)); 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
UnfortunateFruit/darkstar
scripts/globals/items/bataquiche_+1.lua
35
1474
----------------------------------------- -- ID: 5169 -- Item: Bataquiche +1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Magic 10 -- Agility 1 -- Vitality -1 -- Ranged ATT % 7 -- Ranged ATT Cap 20 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5169); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 10); target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -1); target:addMod(MOD_FOOD_RATTP, 7); target:addMod(MOD_FOOD_RATT_CAP, 20); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 10); target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -1); target:delMod(MOD_FOOD_RATTP, 7); target:delMod(MOD_FOOD_RATT_CAP, 20); end;
gpl-3.0
JulioC/telegram-bot
plugins/help.lua
290
1653
do -- Returns true if is not empty local function has_usage_data(dict) if (dict.usage == nil or dict.usage == '') then return false end return true end -- Get commands for that plugin local function plugin_help(name) local plugin = plugins[name] if not plugin then return nil end local text = "" if (type(plugin.usage) == "table") then for ku,usage in pairs(plugin.usage) do text = text..usage..'\n' end text = text..'\n' elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage..'\n\n' end return text end -- !help command local function telegram_help() local text = "Plugin list: \n\n" -- Plugins names for name in pairs(plugins) do text = text..name..'\n' end text = text..'\n'..'Write "!help [plugin name]" for more info.' text = text..'\n'..'Or "!help all" to show all info.' return text end -- !help all command local function help_all() local ret = "" for name in pairs(plugins) do ret = ret .. plugin_help(name) end return ret end local function run(msg, matches) if matches[1] == "!help" then return telegram_help() elseif matches[1] == "!help all" then return help_all() else local text = plugin_help(matches[1]) if not text then text = telegram_help() end return text end end return { description = "Help plugin. Get info from other plugins. ", usage = { "!help: Show list of plugins.", "!help all: Show all commands for every plugin.", "!help [plugin name]: Commands for that plugin." }, patterns = { "^!help$", "^!help all", "^!help (.+)" }, run = run } end
gpl-2.0
nesstea/darkstar
scripts/zones/Davoi/npcs/_45i.lua
13
2256
----------------------------------- -- Area: Davoi -- NPC: Wailing Pond -- Used In Quest: Whence Blows the Wind -- @pos 380 0.1 -181 149 ----------------------------------- package.loaded["scripts/zones/Davoi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Davoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0034); 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 == 0x0034 and player:getVar("miniQuestForORB_CS") == 1) then local c = player:getVar("countRedPoolForORB"); if (c == 0) then player:setVar("countRedPoolForORB", c + 2); player:delKeyItem(WHITE_ORB); player:addKeyItem(PINK_ORB); player:messageSpecial(KEYITEM_OBTAINED, PINK_ORB); elseif (c == 1 or c == 4 or c == 8) then player:setVar("countRedPoolForORB", c + 2); player:delKeyItem(PINK_ORB); player:addKeyItem(RED_ORB); player:messageSpecial(KEYITEM_OBTAINED, RED_ORB); elseif (c == 5 or c == 9 or c == 12) then player:setVar("countRedPoolForORB", c + 2); player:delKeyItem(RED_ORB); player:addKeyItem(BLOOD_ORB); player:messageSpecial(KEYITEM_OBTAINED, BLOOD_ORB); elseif (c == 13) then player:setVar("countRedPoolForORB", c + 2); player:delKeyItem(BLOOD_ORB); player:addKeyItem(CURSED_ORB); player:messageSpecial(KEYITEM_OBTAINED, CURSED_ORB); player:addStatusEffect(EFFECT_PLAGUE,0,0,900); end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Leujaoam_Sanctum/IDs.lua
33
3149
Leujaoam = { text = { -- General Texts ITEM_CANNOT_BE_OBTAINED = 6378, -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6381, -- Obtained: <item> GIL_OBTAINED = 6384, -- Obtained <number> gil KEYITEM_OBTAINED = 6384, -- Obtained key item: <keyitem> -- Assault Texts ASSAULT_01_START = 7417, ASSAULT_02_START = 7418, ASSAULT_03_START = 7419, ASSAULT_04_START = 7420, ASSAULT_05_START = 7421, ASSAULT_06_START = 7422, ASSAULT_07_START = 7423, ASSAULT_08_START = 7424, ASSAULT_09_START = 7425, ASSAULT_10_START = 7426, TIME_TO_COMPLETE = 7477, MISSION_FAILED = 7478, RUNE_UNLOCKED_POS = 7479, RUNE_UNLOCKED = 7480, ASSAULT_POINTS_OBTAINED = 7481, TIME_REMAINING_MINUTES = 7482, TIME_REMAINING_SECONDS = 7483, PARTY_FALLEN = 7485 }, mobs = { -- Leujaoam Cleansing [1] = { LEUJAOAM_WORM1 = 17059841, LEUJAOAM_WORM2 = 17059842, LEUJAOAM_WORM3 = 17059843, LEUJAOAM_WORM4 = 17059844, LEUJAOAM_WORM5 = 17059845, LEUJAOAM_WORM6 = 17059846, LEUJAOAM_WORM7 = 17059847, LEUJAOAM_WORM8 = 17059848, LEUJAOAM_WORM9 = 17059849, LEUJAOAM_WORM10 = 17059850, LEUJAOAM_WORM11 = 17059851, LEUJAOAM_WORM12 = 17059852, LEUJAOAM_WORM13 = 17059853, LEUJAOAM_WORM14 = 17059854, LEUJAOAM_WORM14 = 17059855, } }, npcs = { ANCIENT_LOCKBOX = 17060014, RUNE_OF_RELEASE = 17060015, _1X1 = 17060116, _1X2 = 17060117, _1X3 = 17060118, _1X4 = 17060119, _1X5 = 17060120, _1X6 = 17060121, _1X7 = 17060122, _1X8 = 17060123, _1X9 = 17060124, _1XA = 17060125, _1XB = 17060126, _1XC = 17060127, _1XD = 17060128, _1XE = 17060129, _1XF = 17060130, _1XG = 17060131, _1XH = 17060132, _1XI = 17060133, _1XJ = 17060134, _1XK = 17060135, _1XL = 17060136, _1XM = 17060137, _1XN = 17060138, _1XO = 17060139, _1XP = 17060140, _1XQ = 17060141, _1XR = 17060142, _1XS = 17060143, _1XT = 17060144, _1XU = 17060145, _1XV = 17060146, _1XW = 17060147, _1XX = 17060148, _1XY = 17060149, _1XZ = 17060150, _JX0 = 17060151, _JX1 = 17060152, _JX2 = 17060153, _JX3 = 17060154, _JX4 = 17060155, _JX5 = 17060156, _JX6 = 17060157, _JX7 = 17060158, _JX8 = 17060159, _JX9 = 17060160, _JXA = 17060161, _JXB = 17060162, _JXC = 17060163, _JXD = 17060164, _JXE = 17060165, _JXF = 17060166, _JXG = 17060167, _JXH = 17060168, _JXI = 17060169, _JXJ = 17060170, _JXK = 17060171, } }
gpl-3.0
nesstea/darkstar
scripts/zones/Leafallia/npcs/HomePoint#1.lua
27
1260
----------------------------------- -- Area: Leafallia -- NPC: HomePoint#1 -- @pos 5.539 -0.434 8.133 281 ----------------------------------- package.loaded["scripts/zones/Leafallia/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Leafallia/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 112); 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
FailcoderAddons/supervillain-ui
SVUI_!Core/system/_docklets/garrison.lua
2
12629
--[[ ########################################################## S V U I By: Failcoder ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local select = _G.select; local assert = _G.assert; local type = _G.type; local error = _G.error; local pcall = _G.pcall; local print = _G.print; local ipairs = _G.ipairs; local pairs = _G.pairs; local tostring = _G.tostring; local tonumber = _G.tonumber; --STRING local string = _G.string; local upper = string.upper; local format = string.format; local find = string.find; local match = string.match; local gsub = string.gsub; --TABLE local table = _G.table; local tremove = _G.tremove; local twipe = _G.wipe; --MATH local math = _G.math; local min = math.min; local floor = math.floor local ceil = math.ceil local time = _G.time; local wipe = _G.wipe; --BLIZZARD API local CreateFrame = _G.CreateFrame; local InCombatLockdown = _G.InCombatLockdown; local GameTooltip = _G.GameTooltip; local ReloadUI = _G.ReloadUI; local hooksecurefunc = _G.hooksecurefunc; local IsAltKeyDown = _G.IsAltKeyDown; local IsShiftKeyDown = _G.IsShiftKeyDown; local IsControlKeyDown = _G.IsControlKeyDown; local IsModifiedClick = _G.IsModifiedClick; local PlaySound = _G.PlaySound; local PlaySoundFile = _G.PlaySoundFile; local PlayMusic = _G.PlayMusic; local StopMusic = _G.StopMusic; local ToggleFrame = _G.ToggleFrame; local ERR_NOT_IN_COMBAT = _G.ERR_NOT_IN_COMBAT; local RAID_CLASS_COLORS = _G.RAID_CLASS_COLORS; local CUSTOM_CLASS_COLORS = _G.CUSTOM_CLASS_COLORS; local C_Garrison = _G.C_Garrison; local GetTime = _G.GetTime; local GetItemCooldown = _G.GetItemCooldown; local GetItemCount = _G.GetItemCount; local GetItemInfo = _G.GetItemInfo; local GetSpellInfo = _G.GetSpellInfo; local IsSpellKnown = _G.IsSpellKnown; local GetGarrison = _G.GetGarrison; local GetProfessionInfo = _G.GetProfessionInfo; local GetCurrencyInfo = _G.GetCurrencyInfo; --[[ ########################################################## ADDON ########################################################## ]]-- local SV = select(2, ...) local L = SV.L local MOD = SV.Dock; local GarrisonData = {}; --[[ ########################################################## LOCALS ########################################################## ]]-- local function GetInProgressMissions() local garrisonMission = {} local types = { LE_FOLLOWER_TYPE_GARRISON_7_0, LE_FOLLOWER_TYPE_GARRISON_6_0, LE_FOLLOWER_TYPE_SHIPYARD_6_2 } for key, type in pairs(types) do local localMission = {} C_Garrison.GetInProgressMissions(localMission, type) for i = 1, #localMission do garrisonMission[#garrisonMission + 1] = localMission[i] end end return garrisonMission end local function GetCompleteMissions() local garrisonMission = {} local types = { LE_FOLLOWER_TYPE_GARRISON_7_0, LE_FOLLOWER_TYPE_GARRISON_6_0, LE_FOLLOWER_TYPE_SHIPYARD_6_2 } for key, type in pairs(types) do local localMission = {} C_Garrison.GetCompleteMissions(garrisonMission, type) for i = 1, #localMission do garrisonMission[#garrisonMission + 1] = localMission[i] end end return garrisonMission end local function GetDockCooldown(itemID) local start,duration = GetItemCooldown(itemID) local expires = duration - (GetTime() - start) if expires > 0.05 then local timeLeft = 0; local calc = 0; if expires < 4 then return format("|cffff0000%.1f|r", expires) elseif expires < 60 then return format("|cffffff00%d|r", floor(expires)) elseif expires < 3600 then timeLeft = ceil(expires / 60); calc = floor((expires / 60) + .5); return format("|cffff9900%dm|r", timeLeft) elseif expires < 86400 then timeLeft = ceil(expires / 3600); calc = floor((expires / 3600) + .5); return format("|cff66ffff%dh|r", timeLeft) else timeLeft = ceil(expires / 86400); calc = floor((expires / 86400) + .5); return format("|cff6666ff%dd|r", timeLeft) end else return "|cff6666ffReady|r" end end local GarrisonButton_OnEvent = function(self, event, ...) if(not InCombatLockdown()) then if (event == "GARRISON_HIDE_LANDING_PAGE") then self:SetDocked() elseif (event == "GARRISON_SHOW_LANDING_PAGE") then self:SetDocked(true) end end if((not self.StartAlert) or (not self.StopAlert)) then return end if ( event == "GARRISON_BUILDING_ACTIVATABLE" ) then self:StartAlert(); elseif ( event == "GARRISON_BUILDING_ACTIVATED" or event == "GARRISON_ARCHITECT_OPENED") then self:StopAlert(); elseif ( event == "GARRISON_MISSION_FINISHED" ) then self:StartAlert(); elseif ( event == "GARRISON_MISSION_NPC_OPENED" ) then self:StopAlert(); elseif ( event == "GARRISON_SHIPYARD_NPC_OPENED" ) then self:StopAlert(); elseif (event == "GARRISON_INVASION_AVAILABLE") then self:StartAlert(); elseif (event == "GARRISON_INVASION_UNAVAILABLE") then self:StopAlert(); elseif (event == "SHIPMENT_UPDATE") then local shipmentStarted = ...; if (shipmentStarted) then self:StartAlert(); end end end local function getColoredString(text, color) local hex = SV:HexColor(color) return ("|cff%s%s|r"):format(hex, text) end local function GetSafeData(fn) local t = fn(1) or {} for k,v in pairs(fn(2) or {}) do t[#t+1] = v end return t end local function GetActiveMissions() wipe(GarrisonData) local hasMission = false local inProgressMissions = {} local completedMissions = {} GameTooltip:AddLine(" ", 1, 1, 1) GameTooltip:AddLine("Active Missions", 1, 0.7, 0) for key,data in pairs(GetSafeData(C_Garrison.GetInProgressMissions)) do GarrisonData[data.missionID] = { name = data.name, level = data.level, seconds = data.durationSeconds, timeLeft = data.timeLeft, completed = false, isRare = data.isRare, type = data.type, } hasMission = true end for key,data in pairs(GetSafeData(C_Garrison.GetCompleteMissions)) do if(GarrisonData[data.missionID]) then GarrisonData[data.missionID].completed = true end end for key,data in pairs(GarrisonData) do local hex = data.isRare and "blue" or "green" local mission = ("%s|cff888888 - |r%s"):format(getColoredString(data.level, "yellow"), getColoredString(data.name, hex)); local remaining if (data.completed) then remaining = L["Complete!"] else remaining = ("%s %s"):format(data.timeLeft, getColoredString(" ("..SV:ParseSeconds(data.seconds)..")", "lightgrey")) end GameTooltip:AddDoubleLine(mission, remaining, 0, 1, 0, 1, 1, 1) hasMission = true end if(not hasMission) then GameTooltip:AddLine("None", 1, 0, 0) end end local function GetBuildingData() local hasBuildings = false local now = time(); local prefixed = false; local buildings = GetSafeData(C_Garrison.GetBuildings) for i = 1, #buildings do local buildingID = buildings[i].buildingID local plotID = buildings[i].plotID local id, name, texPrefix, icon, rank, isBuilding, timeStart, buildTime, canActivate, canUpgrade, isPrebuilt = C_Garrison.GetOwnedBuildingInfoAbbrev(plotID) local remaining; if(isBuilding) then local timeLeft = buildTime - (now - timeStart); if(canActivate or timeLeft < 0) then remaining = L["Complete!"] else remaining = ("Building %s"):format(getColoredString("("..SV:ParseSeconds(timeLeft)..")", "lightgrey")) end else local name, texture, shipmentCapacity, shipmentsReady, shipmentsTotal, creationTime, duration, timeleftString, itemName, itemIcon, itemQuality, itemID = C_Garrison.GetLandingPageShipmentInfo(buildingID) if(shipmentsReady and shipmentsReady > 0) then timeleftString = timeleftString or 'Unknown' remaining = ("Ready: %s, Next: %s"):format(getColoredString(shipmentsReady, "green"), getColoredString(timeleftString, "lightgrey")) elseif(timeleftString) then remaining = ("Next: %s"):format(getColoredString(timeleftString, "lightgrey")) end end if(remaining) then if(not prefixed) then GameTooltip:AddLine(" ", 1, 1, 1) GameTooltip:AddLine("Buildings / Work Orders", 1, 0.7, 0) prefixed = true end local building = ("|cffFF5500%s|r|cff888888 - |r|cffFFFF00Rank %s|r"):format(name, rank); GameTooltip:AddDoubleLine(building, remaining, 0, 1, 0, 1, 1, 1) end end end local SetGarrisonTooltip = function(self) if(not InCombatLockdown()) then C_Garrison.RequestLandingPageShipmentInfo() end local name, amount, tex, week, weekmax, maxed, discovered = GetCurrencyInfo(1220) local texStr = ("\124T%s:12\124t %d"):format(tex, amount) GameTooltip:AddDoubleLine(name, texStr, 1, 1, 0, 1, 1, 1) name, amount, tex, week, weekmax, maxed, discovered = GetCurrencyInfo(1155) texStr = ("\124T%s:12\124t %d"):format(tex, amount) GameTooltip:AddDoubleLine(name, texStr, 1, 1, 0, 1, 1, 1) name, amount, tex, week, weekmax, maxed, discovered = GetCurrencyInfo(824) texStr = ("\124T%s:12\124t %d"):format(tex, amount) GameTooltip:AddDoubleLine(name, texStr, 1, 1, 0, 1, 1, 1) name, amount, tex, week, weekmax, maxed, discovered = GetCurrencyInfo(1101) texStr = ("\124T%s:12\124t %d"):format(tex, amount) GameTooltip:AddDoubleLine(name, texStr, 1, 1, 0, 1, 1, 1) GetActiveMissions() GetBuildingData() if(self.StopAlert) then self:StopAlert() end local text1 = self:GetAttribute("tipText") local text2 = self:GetAttribute("tipExtraText") GameTooltip:AddLine(" ", 1, 1, 1) GameTooltip:AddDoubleLine("[Left-Click]", text1, 0, 1, 0, 1, 1, 1) if InCombatLockdown() then return end if(text2) then local remaining = GetDockCooldown(110560) GameTooltip:AddDoubleLine("[Right Click]", text2, 0, 1, 0, 1, 1, 1) GameTooltip:AddDoubleLine(L["Time Remaining"], remaining, 1, 0.5, 0, 1, 1, 1) end end local function LoadToolBarGarrison() local mmButton = _G.GarrisonLandingPageMinimapButton; if((not SV.db.Dock.dockTools.garrison) or (not mmButton) or MOD.GarrisonLoaded) then return end mmButton:FadeOut() if(InCombatLockdown()) then MOD.GarrisonNeedsUpdate = true; MOD:RegisterEvent("PLAYER_REGEN_ENABLED"); return end local garrison = SV.Dock:SetDockButton("BottomLeft", L["Landing Page"], "SVUI_Garrison", SV.media.dock.garrisonToolIcon, SetGarrisonTooltip, "SecureActionButtonTemplate") garrison:SetAttribute("type1", "click") garrison:SetAttribute("clickbutton", mmButton) local garrisonStone = GetItemInfo(110560); if(garrisonStone and type(garrisonStone) == "string") then garrison:SetAttribute("tipExtraText", L["Garrison Hearthstone"]) garrison:SetAttribute("type2", "macro") garrison:SetAttribute("macrotext", "/use [nomod] " .. garrisonStone) end mmButton:RemoveTextures() mmButton:ClearAllPoints() mmButton:SetAllPoints(garrison) mmButton:SetNormalTexture("") mmButton:SetPushedTexture("") mmButton:SetHighlightTexture("") mmButton:EnableMouse(false) garrison:RegisterEvent("GARRISON_HIDE_LANDING_PAGE"); garrison:RegisterEvent("GARRISON_SHOW_LANDING_PAGE"); garrison:RegisterEvent("GARRISON_BUILDING_ACTIVATABLE"); garrison:RegisterEvent("GARRISON_BUILDING_ACTIVATED"); garrison:RegisterEvent("GARRISON_ARCHITECT_OPENED"); garrison:RegisterEvent("GARRISON_MISSION_FINISHED"); garrison:RegisterEvent("GARRISON_MISSION_NPC_OPENED"); garrison:RegisterEvent("GARRISON_SHIPYARD_NPC_OPENED"); garrison:RegisterEvent("GARRISON_INVASION_AVAILABLE"); garrison:RegisterEvent("GARRISON_INVASION_UNAVAILABLE"); garrison:RegisterEvent("SHIPMENT_UPDATE"); garrison:SetScript("OnEvent", GarrisonButton_OnEvent); if(not mmButton:IsShown()) then garrison:SetDocked() end C_Garrison.RequestLandingPageShipmentInfo(); MOD.GarrisonLoaded = true end --[[ ########################################################## BUILD/UPDATE ########################################################## ]]-- function MOD:UpdateGarrisonTool() if((not SV.db.Dock.dockTools.garrison) or self.GarrisonLoaded) then return end LoadToolBarGarrison() end function MOD:LoadGarrisonTool() if((not SV.db.Dock.dockTools.garrison) or self.GarrisonLoaded or (not _G.GarrisonLandingPageMinimapButton)) then return end SV.Timers:ExecuteTimer(LoadToolBarGarrison, 5) end
mit
nesstea/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Kleh_Engyumoh.lua
13
1066
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Kleh Engyumoh -- Type: Standard NPC -- @zone: 94 -- @pos -54.962 -4.5 57.701 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01af); 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
nesstea/darkstar
scripts/zones/Uleguerand_Range/npcs/HomePoint#2.lua
27
1258
----------------------------------- -- Area: Uleguerand_Range -- NPC: HomePoint#2 -- @pos ----------------------------------- package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Uleguerand_Range/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 77); 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 == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
dpino/snabbswitch
src/apps/keyed_ipv6_tunnel/tunnel.lua
9
10003
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) -- http://tools.ietf.org/html/draft-mkonstan-keyed-ipv6-tunnel-01 -- TODO: generalize local AF_INET6 = 10 local ffi = require("ffi") local C = ffi.C local bit = require("bit") local app = require("core.app") local link = require("core.link") local lib = require("core.lib") local packet = require("core.packet") local config = require("core.config") local counter = require("core.counter") local macaddress = require("lib.macaddress") local pcap = require("apps.pcap.pcap") local basic_apps = require("apps.basic.basic_apps") local header_struct_ctype = ffi.typeof[[ struct { // ethernet char dmac[6]; char smac[6]; uint16_t ethertype; // ipv6 uint32_t flow_id; // version, tc, flow_id int16_t payload_length; int8_t next_header; uint8_t hop_limit; char src_ip[16]; char dst_ip[16]; // tunnel uint32_t session_id; char cookie[8]; } __attribute__((packed)) ]] local HEADER_SIZE = ffi.sizeof(header_struct_ctype) local header_array_ctype = ffi.typeof("uint8_t[?]") local next_header_ctype = ffi.typeof("uint8_t*") local cookie_ctype = ffi.typeof("uint64_t[1]") local pcookie_ctype = ffi.typeof("uint64_t*") local address_ctype = ffi.typeof("uint64_t[2]") local paddress_ctype = ffi.typeof("uint64_t*") local plength_ctype = ffi.typeof("int16_t*") local psession_id_ctype = ffi.typeof("uint32_t*") local DST_MAC_OFFSET = ffi.offsetof(header_struct_ctype, 'dmac') local SRC_IP_OFFSET = ffi.offsetof(header_struct_ctype, 'src_ip') local DST_IP_OFFSET = ffi.offsetof(header_struct_ctype, 'dst_ip') local COOKIE_OFFSET = ffi.offsetof(header_struct_ctype, 'cookie') local ETHERTYPE_OFFSET = ffi.offsetof(header_struct_ctype, 'ethertype') local LENGTH_OFFSET = ffi.offsetof(header_struct_ctype, 'payload_length') local NEXT_HEADER_OFFSET = ffi.offsetof(header_struct_ctype, 'next_header') local SESSION_ID_OFFSET = ffi.offsetof(header_struct_ctype, 'session_id') local FLOW_ID_OFFSET = ffi.offsetof(header_struct_ctype, 'flow_id') local HOP_LIMIT_OFFSET = ffi.offsetof(header_struct_ctype, 'hop_limit') local SESSION_COOKIE_SIZE = 12 -- 32 bit session and 64 bit cookie -- Next Header. -- Set to 0x73 to indicate that the next header is L2TPv3. local L2TPV3_NEXT_HEADER = 0x73 local header_template = header_array_ctype(HEADER_SIZE) -- fill header template with const values local function prepare_header_template () -- all bytes are zeroed after allocation -- IPv6 header_template[ETHERTYPE_OFFSET] = 0x86 header_template[ETHERTYPE_OFFSET + 1] = 0xDD -- Ver. Set to 0x6 to indicate IPv6. -- version is 4 first bits at this offset -- no problem to set others 4 bits to zeros - it is already zeros header_template[FLOW_ID_OFFSET] = 0x60 header_template[HOP_LIMIT_OFFSET] = 64 header_template[NEXT_HEADER_OFFSET] = L2TPV3_NEXT_HEADER -- For cases where both tunnel endpoints support one-stage resolution -- (IPv6 Address only), this specification recommends setting the -- Session ID to all ones for easy identification in case of troubleshooting. -- may be overridden by local_session options header_template[SESSION_ID_OFFSET] = 0xFF header_template[SESSION_ID_OFFSET + 1] = 0xFF header_template[SESSION_ID_OFFSET + 2] = 0xFF header_template[SESSION_ID_OFFSET + 3] = 0xFF end SimpleKeyedTunnel = { config = { -- string, ipv6 address local_address = {required=true}, remote_address = {required=true}, -- 8 bytes hex string local_cookie = {required=true}, remote_cookie = {required=true}, -- unsigned number, must fit to uint32_t local_session = {}, -- string, MAC address (for testing) default_gateway_MAC = {}, -- unsigned integer <= 255 hop_limit = {} }, shm = { rxerrors = {counter}, length_errors = {counter}, protocol_errors = {counter}, cookie_errors = {counter}, remote_address_errors = {counter}, local_address_errors = {counter} } } function SimpleKeyedTunnel:new (conf) assert( type(conf.local_cookie) == "string" and #conf.local_cookie <= 16, "local_cookie should be 8 bytes hex string" ) assert( type(conf.remote_cookie) == "string" and #conf.remote_cookie <= 16, "remote_cookie should be 8 bytes hex string" ) local header = header_array_ctype(HEADER_SIZE) ffi.copy(header, header_template, HEADER_SIZE) local local_cookie = lib.hexundump(conf.local_cookie, 8) ffi.copy( header + COOKIE_OFFSET, local_cookie, #local_cookie ) -- convert dest, sorce ipv6 addressed to network order binary local result = C.inet_pton(AF_INET6, conf.local_address, header + SRC_IP_OFFSET) assert(result == 1,"malformed IPv6 address: " .. conf.local_address) result = C.inet_pton(AF_INET6, conf.remote_address, header + DST_IP_OFFSET) assert(result == 1,"malformed IPv6 address: " .. conf.remote_address) -- store casted pointers for fast matching local remote_address = ffi.cast(paddress_ctype, header + DST_IP_OFFSET) local local_address = ffi.cast(paddress_ctype, header + SRC_IP_OFFSET) local remote_cookie = ffi.cast(pcookie_ctype, lib.hexundump(conf.remote_cookie, 8)) if conf.local_session then local psession = ffi.cast(psession_id_ctype, header + SESSION_ID_OFFSET) psession[0] = lib.htonl(conf.local_session) end if conf.default_gateway_MAC then local mac = assert(macaddress:new(conf.default_gateway_MAC)) ffi.copy(header + DST_MAC_OFFSET, mac.bytes, 6) end if conf.hop_limit then assert(type(conf.hop_limit) == 'number' and conf.hop_limit <= 255, "invalid hop limit") header[HOP_LIMIT_OFFSET] = conf.hop_limit end local o = { header = header, remote_address = remote_address, local_address = local_address, remote_cookie = remote_cookie[0] } return setmetatable(o, {__index = SimpleKeyedTunnel}) end function SimpleKeyedTunnel:push() -- encapsulation path local l_in = self.input.decapsulated local l_out = self.output.encapsulated assert(l_in and l_out) while not link.empty(l_in) do local p = link.receive(l_in) p = packet.prepend(p, self.header, HEADER_SIZE) local plength = ffi.cast(plength_ctype, p.data + LENGTH_OFFSET) plength[0] = lib.htons(SESSION_COOKIE_SIZE + p.length - HEADER_SIZE) link.transmit(l_out, p) end -- decapsulation path l_in = self.input.encapsulated l_out = self.output.decapsulated assert(l_in and l_out) while not link.empty(l_in) do local p = link.receive(l_in) -- match next header, cookie, src/dst addresses local drop = true repeat if p.length < HEADER_SIZE then counter.add(self.shm.length_errors) break end local next_header = ffi.cast(next_header_ctype, p.data + NEXT_HEADER_OFFSET) if next_header[0] ~= L2TPV3_NEXT_HEADER then counter.add(self.shm.protocol_errors) break end local cookie = ffi.cast(pcookie_ctype, p.data + COOKIE_OFFSET) if cookie[0] ~= self.remote_cookie then counter.add(self.shm.cookie_errors) break end local remote_address = ffi.cast(paddress_ctype, p.data + SRC_IP_OFFSET) if remote_address[0] ~= self.remote_address[0] or remote_address[1] ~= self.remote_address[1] then counter.add(self.shm.remote_address_errors) break end local local_address = ffi.cast(paddress_ctype, p.data + DST_IP_OFFSET) if local_address[0] ~= self.local_address[0] or local_address[1] ~= self.local_address[1] then counter.add(self.shm.local_address_errors) break end drop = false until true if drop then counter.add(self.shm.rxerrors) -- discard packet packet.free(p) else p = packet.shiftleft(p, HEADER_SIZE) link.transmit(l_out, p) end end end -- prepare header template to be used by all apps prepare_header_template() function selftest () print("Keyed IPv6 tunnel selftest") local ok = true local Synth = require("apps.test.synth").Synth local Match = require("apps.test.match").Match local tunnel_config = { local_address = "00::2:1", remote_address = "00::2:1", local_cookie = "12345678", remote_cookie = "12345678", default_gateway_MAC = "a1:b2:c3:d4:e5:f6" } -- should be symmetric for local "loop-back" test local c = config.new() config.app(c, "tunnel", SimpleKeyedTunnel, tunnel_config) config.app(c, "match", Match) config.app(c, "comparator", Synth) config.app(c, "source", Synth) config.link(c, "source.output -> tunnel.decapsulated") config.link(c, "comparator.output -> match.comparator") config.link(c, "tunnel.encapsulated -> tunnel.encapsulated") config.link(c, "tunnel.decapsulated -> match.rx") app.configure(c) app.main({duration = 0.0001, report = {showapps=true,showlinks=true}}) -- Check results if #engine.app_table.match:errors() ~= 0 then ok = false end local c = config.new() config.app(c, "source", basic_apps.Source) config.app(c, "tunnel", SimpleKeyedTunnel, tunnel_config) config.app(c, "sink", basic_apps.Sink) config.link(c, "source.output -> tunnel.decapsulated") config.link(c, "tunnel.encapsulated -> tunnel.encapsulated") config.link(c, "tunnel.decapsulated -> sink.input") app.configure(c) print("run simple one second benchmark ...") app.main({duration = 1}) if not ok then print("selftest failed") os.exit(1) end print("selftest passed") end
apache-2.0
akdor1154/awesome
lib/awful/menu.lua
1
21713
-------------------------------------------------------------------------------- --- A menu for awful -- -- @author Damien Leone &lt;damien.leone@gmail.com&gt; -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @author dodo -- @copyright 2008, 2011 Damien Leone, Julien Danjou, dodo -- @release @AWESOME_VERSION@ -- @module awful.menu -------------------------------------------------------------------------------- local wibox = require("wibox") local button = require("awful.button") local util = require("awful.util") local spawn = require("awful.spawn") local tags = require("awful.tag") local keygrabber = require("awful.keygrabber") local client_iterate = require("awful.client").iterate local beautiful = require("beautiful") local dpi = require("beautiful").xresources.apply_dpi local object = require("gears.object") local surface = require("gears.surface") local protected_call = require("gears.protected_call") local cairo = require("lgi").cairo local setmetatable = setmetatable local tonumber = tonumber local string = string local ipairs = ipairs local pairs = pairs local print = print local table = table local type = type local math = math local capi = { screen = screen, mouse = mouse, client = client } local screen = require("awful.screen") local menu = { mt = {} } local table_update = function (t, set) for k, v in pairs(set) do t[k] = v end return t end --- Key bindings for menu navigation. -- Keys are: up, down, exec, enter, back, close. Value are table with a list of valid -- keys for the action, i.e. menu_keys.up = { "j", "k" } will bind 'j' and 'k' -- key to up action. This is common to all created menu. -- @class table -- @name menu_keys menu.menu_keys = { up = { "Up", "k" }, down = { "Down", "j" }, back = { "Left", "h" }, exec = { "Return" }, enter = { "Right", "l" }, close = { "Escape" } } local function load_theme(a, b) a = a or {} b = b or {} local ret = {} local fallback = beautiful.get() if a.reset then b = fallback end if a == "reset" then a = fallback end ret.border = a.border_color or b.menu_border_color or b.border_normal or fallback.menu_border_color or fallback.border_normal ret.border_width= a.border_width or b.menu_border_width or b.border_width or fallback.menu_border_width or fallback.border_width or 0 ret.fg_focus = a.fg_focus or b.menu_fg_focus or b.fg_focus or fallback.menu_fg_focus or fallback.fg_focus ret.bg_focus = a.bg_focus or b.menu_bg_focus or b.bg_focus or fallback.menu_bg_focus or fallback.bg_focus ret.fg_normal = a.fg_normal or b.menu_fg_normal or b.fg_normal or fallback.menu_fg_normal or fallback.fg_normal ret.bg_normal = a.bg_normal or b.menu_bg_normal or b.bg_normal or fallback.menu_bg_normal or fallback.bg_normal ret.submenu_icon= a.submenu_icon or b.menu_submenu_icon or b.submenu_icon or fallback.menu_submenu_icon or fallback.submenu_icon ret.submenu = a.submenu or b.menu_submenu or b.submenu or fallback.menu_submenu or fallback.submenu or "▶" ret.height = a.height or b.menu_height or b.height or fallback.menu_height or 16 ret.width = a.width or b.menu_width or b.width or fallback.menu_width or 100 ret.font = a.font or b.font or fallback.font for _, prop in ipairs({"width", "height", "menu_width"}) do if type(ret[prop]) ~= "number" then ret[prop] = tonumber(ret[prop]) end end return ret end local function item_position(_menu, child) local a, b = "height", "width" local dir = _menu.layout.dir or "y" if dir == "x" then a, b = b, a end local in_dir, other = 0, _menu[b] local num = util.table.hasitem(_menu.child, child) if num then for i = 0, num - 1 do local item = _menu.items[i] if item then other = math.max(other, item[b]) in_dir = in_dir + item[a] end end end local w, h = other, in_dir if dir == "x" then w, h = h, w end return w, h end local function set_coords(_menu, s, m_coords) local s_geometry = s.workarea local screen_w = s_geometry.x + s_geometry.width local screen_h = s_geometry.y + s_geometry.height _menu.width = _menu.wibox.width _menu.height = _menu.wibox.height _menu.x = _menu.wibox.x _menu.y = _menu.wibox.y if _menu.parent then local w, h = item_position(_menu.parent, _menu) w = w + _menu.parent.theme.border_width _menu.y = _menu.parent.y + h + _menu.height > screen_h and screen_h - _menu.height or _menu.parent.y + h _menu.x = _menu.parent.x + w + _menu.width > screen_w and _menu.parent.x - _menu.width or _menu.parent.x + w else if m_coords == nil then m_coords = capi.mouse.coords() m_coords.x = m_coords.x + 1 m_coords.y = m_coords.y + 1 end _menu.y = m_coords.y < s_geometry.y and s_geometry.y or m_coords.y _menu.x = m_coords.x < s_geometry.x and s_geometry.x or m_coords.x _menu.y = _menu.y + _menu.height > screen_h and screen_h - _menu.height or _menu.y _menu.x = _menu.x + _menu.width > screen_w and screen_w - _menu.width or _menu.x end _menu.wibox.x = _menu.x _menu.wibox.y = _menu.y end local function set_size(_menu) local in_dir, other, a, b = 0, 0, "height", "width" local dir = _menu.layout.dir or "y" if dir == "x" then a, b = b, a end for _, item in ipairs(_menu.items) do other = math.max(other, item[b]) in_dir = in_dir + item[a] end _menu[a], _menu[b] = in_dir, other if in_dir > 0 and other > 0 then _menu.wibox[a] = in_dir _menu.wibox[b] = other return true end return false end local function check_access_key(_menu, key) for i, item in ipairs(_menu.items) do if item.akey == key then _menu:item_enter(i) _menu:exec(i, { exec = true }) return end end if _menu.parent then check_access_key(_menu.parent, key) end end local function grabber(_menu, _, key, event) if event ~= "press" then return end local sel = _menu.sel or 0 if util.table.hasitem(menu.menu_keys.up, key) then local sel_new = sel-1 < 1 and #_menu.items or sel-1 _menu:item_enter(sel_new) elseif util.table.hasitem(menu.menu_keys.down, key) then local sel_new = sel+1 > #_menu.items and 1 or sel+1 _menu:item_enter(sel_new) elseif sel > 0 and util.table.hasitem(menu.menu_keys.enter, key) then _menu:exec(sel) elseif sel > 0 and util.table.hasitem(menu.menu_keys.exec, key) then _menu:exec(sel, { exec = true }) elseif util.table.hasitem(menu.menu_keys.back, key) then _menu:hide() elseif util.table.hasitem(menu.menu_keys.close, key) then menu.get_root(_menu):hide() else check_access_key(_menu, key) end end function menu:exec(num, opts) opts = opts or {} local item = self.items[num] if not item then return end local cmd = item.cmd if type(cmd) == "table" then local action = cmd.cmd if #cmd == 0 then if opts.exec and action and type(action) == "function" then action() end return end if not self.child[num] then self.child[num] = menu.new(cmd, self) end local can_invoke_action = opts.exec and action and type(action) == "function" and (not opts.mouse or (opts.mouse and (self.auto_expand or (self.active_child == self.child[num] and self.active_child.wibox.visible)))) if can_invoke_action then local visible = action(self.child[num], item) if not visible then menu.get_root(self):hide() return else self.child[num]:update() end end if self.active_child and self.active_child ~= self.child[num] then self.active_child:hide() end self.active_child = self.child[num] if not self.active_child.visible then self.active_child:show() end elseif type(cmd) == "string" then menu.get_root(self):hide() spawn(cmd) elseif type(cmd) == "function" then local visible, action = cmd(item, self) if not visible then menu.get_root(self):hide() else self:update() if self.items[num] then self:item_enter(num, opts) end end if action and type(action) == "function" then action() end end end function menu:item_enter(num, opts) opts = opts or {} local item = self.items[num] if num == nil or self.sel == num or not item then return elseif self.sel then self:item_leave(self.sel) end --print("sel", num, menu.sel, item.theme.bg_focus) item._background:set_fg(item.theme.fg_focus) item._background:set_bg(item.theme.bg_focus) self.sel = num if self.auto_expand and opts.hover then if self.active_child then self.active_child:hide() self.active_child = nil end if type(item.cmd) == "table" then self:exec(num, opts) end end end function menu:item_leave(num) --print("leave", num) local item = self.items[num] if item then item._background:set_fg(item.theme.fg_normal) item._background:set_bg(item.theme.bg_normal) end end --- Show a menu. -- @param args The arguments -- @param args.coords Menu position defaulting to mouse.coords() function menu:show(args) args = args or {} local coords = args.coords or nil local s = capi.screen[screen.focused()] if not set_size(self) then return end set_coords(self, s, coords) keygrabber.run(self._keygrabber) self.wibox.visible = true end --- Hide a menu popup. function menu:hide() -- Remove items from screen for i = 1, #self.items do self:item_leave(i) end if self.active_child then self.active_child:hide() self.active_child = nil end self.sel = nil keygrabber.stop(self._keygrabber) self.wibox.visible = false end --- Toggle menu visibility. -- @param args The arguments -- @param args.coords Menu position {x,y} function menu:toggle(args) if self.wibox.visible then self:hide() else self:show(args) end end --- Update menu content function menu:update() if self.wibox.visible then self:show({ coords = { x = self.x, y = self.y } }) end end --- Get the elder parent so for example when you kill -- it, it will destroy the whole family. function menu:get_root() return self.parent and menu.get_root(self.parent) or self end --- Add a new menu entry. -- args.* params needed for the menu entry constructor. -- @param args The item params -- @param args.new (Default: awful.menu.entry) The menu entry constructor. -- @param[opt] args.theme The menu entry theme. -- @param[opt] index The index where the new entry will inserted. function menu:add(args, index) if not args then return end local theme = load_theme(args.theme or {}, self.theme) args.theme = theme args.new = args.new or menu.entry local item = protected_call(args.new, self, args) if (not item) or (not item.widget) then print("Error while checking menu entry: no property widget found.") return end item.parent = self item.theme = item.theme or theme item.width = item.width or theme.width item.height = item.height or theme.height wibox.widget.base.check_widget(item.widget) item._background = wibox.widget.background() item._background:set_widget(item.widget) item._background:set_fg(item.theme.fg_normal) item._background:set_bg(item.theme.bg_normal) -- Create bindings item._background:buttons(util.table.join( button({}, 3, function () self:hide() end), button({}, 1, function () local num = util.table.hasitem(self.items, item) self:item_enter(num, { mouse = true }) self:exec(num, { exec = true, mouse = true }) end ))) item._mouse = function () local num = util.table.hasitem(self.items, item) self:item_enter(num, { hover = true, moue = true }) end item.widget:connect_signal("mouse::enter", item._mouse) if index then self.layout:reset() table.insert(self.items, index, item) for _, i in ipairs(self.items) do self.layout:add(i._background) end else table.insert(self.items, item) self.layout:add(item._background) end if self.wibox then set_size(self) end return item end --- Delete menu entry at given position -- @param num The position in the table of the menu entry to be deleted; can be also the menu entry itself function menu:delete(num) if type(num) == "table" then num = util.table.hasitem(self.items, num) end local item = self.items[num] if not item then return end item.widget:disconnect_signal("mouse::enter", item._mouse) item.widget.visible = false table.remove(self.items, num) if self.sel == num then self:item_leave(self.sel) self.sel = nil end self.layout:reset() for _, i in ipairs(self.items) do self.layout:add(i._background) end if self.child[num] then self.child[num]:hide() if self.active_child == self.child[num] then self.active_child = nil end table.remove(self.child, num) end if self.wibox then set_size(self) end end -------------------------------------------------------------------------------- --- Build a popup menu with running clients and show it. -- @tparam[opt] table args Menu table, see `new()` for more information. -- @tparam[opt] table item_args Table that will be merged into each item, see -- `new()` for more information. -- @tparam[opt] func filter A function taking a client as an argument and -- returning `true` or `false` to indicate whether the client should be -- included in the menu. -- @return The menu. function menu.clients(args, item_args, filter) local cls_t = {} for c in client_iterate(filter or function() return true end) do cls_t[#cls_t + 1] = { c.name or "", function () if not c:isvisible() then tags.viewmore(c:tags(), c.screen) end c:emit_signal("request::activate", "menu.clients", {raise=true}) end, c.icon } if item_args then if type(item_args) == "function" then util.table.merge(cls_t[#cls_t], item_args(c)) else util.table.merge(cls_t[#cls_t], item_args) end end end args = args or {} args.items = args.items or {} util.table.merge(args.items, cls_t) local m = menu.new(args) m:show(args) return m end -------------------------------------------------------------------------------- --- Default awful.menu.entry constructor -- @param parent The parent menu (TODO: This is apparently unused) -- @param args the item params -- @return table with 'widget', 'cmd', 'akey' and all the properties the user wants to change function menu.entry(parent, args) -- luacheck: no unused args args = args or {} args.text = args[1] or args.text or "" args.cmd = args[2] or args.cmd args.icon = args[3] or args.icon local ret = {} -- Create the item label widget local label = wibox.widget.textbox() local key = '' label:set_font(args.theme.font) label:set_markup(string.gsub( util.escape(args.text), "&amp;(%w)", function (l) key = string.lower(l) return "<u>" .. l .. "</u>" end, 1)) -- Set icon if needed local icon, iconbox local margin = wibox.layout.margin() margin:set_widget(label) if args.icon then icon = surface.load(args.icon) end if icon then local iw = icon:get_width() local ih = icon:get_height() if iw > args.theme.width or ih > args.theme.height then local w, h if ((args.theme.height / ih) * iw) > args.theme.width then w, h = args.theme.height, (args.theme.height / iw) * ih else w, h = (args.theme.height / ih) * iw, args.theme.height end -- We need to scale the image to size w x h local img = cairo.ImageSurface(cairo.Format.ARGB32, w, h) local cr = cairo.Context(img) cr:scale(w / iw, h / ih) cr:set_source_surface(icon, 0, 0) cr:paint() icon = img end iconbox = wibox.widget.imagebox() if iconbox:set_image(icon) then margin:set_left(dpi(2)) else iconbox = nil end end if not iconbox then margin:set_left(args.theme.height + dpi(2)) end -- Create the submenu icon widget local submenu if type(args.cmd) == "table" then if args.theme.submenu_icon then submenu = wibox.widget.imagebox() submenu:set_image(args.theme.submenu_icon) else submenu = wibox.widget.textbox() submenu:set_font(args.theme.font) submenu:set_text(args.theme.submenu) end end -- Add widgets to the wibox local left = wibox.layout.fixed.horizontal() if iconbox then left:add(iconbox) end -- This contains the label left:add(margin) local layout = wibox.layout.align.horizontal() layout:set_left(left) if submenu then layout:set_right(submenu) end return table_update(ret, { label = label, sep = submenu, icon = iconbox, widget = layout, cmd = args.cmd, akey = key, }) end -------------------------------------------------------------------------------- --- Create a menu popup. -- @param args Table containing the menu informations. -- -- * Key items: Table containing the displayed items. Each element is a table by default (when element 'new' is awful.menu.entry) containing: item name, triggered action, submenu table or function, item icon (optional). -- * Keys theme.[fg|bg]_[focus|normal], theme.border_color, theme.border_width, theme.submenu_icon, theme.height and theme.width override the default display for your menu and/or of your menu entry, each of them are optional. -- * Key auto_expand controls the submenu auto expand behaviour by setting it to true (default) or false. -- -- @param parent Specify the parent menu if we want to open a submenu, this value should never be set by the user. -- @usage -- The following function builds and shows a menu of clients that match -- -- a particular rule. -- -- Bound to a key, it can be used to select from dozens of terminals open on -- -- several tags. -- -- When using @{rules.match_any} instead of @{rules.match}, -- -- a menu of clients with different classes could be build. -- -- function terminal_menu () -- terms = {} -- for i, c in pairs(client.get()) do -- if awful.rules.match(c, {class = "URxvt"}) then -- terms[i] = -- {c.name, -- function() -- awful.tag.viewonly(c.first_tag) -- client.focus = c -- end, -- c.icon -- } -- end -- end -- awful.menu(terms):show() -- end function menu.new(args, parent) args = args or {} args.layout = args.layout or wibox.layout.flex.vertical local _menu = table_update(object(), { item_enter = menu.item_enter, item_leave = menu.item_leave, get_root = menu.get_root, delete = menu.delete, update = menu.update, toggle = menu.toggle, hide = menu.hide, show = menu.show, exec = menu.exec, add = menu.add, child = {}, items = {}, parent = parent, layout = args.layout(), theme = load_theme(args.theme or {}, parent and parent.theme) }) if parent then _menu.auto_expand = parent.auto_expand elseif args.auto_expand ~= nil then _menu.auto_expand = args.auto_expand else _menu.auto_expand = true end -- Create items for _, v in ipairs(args) do _menu:add(v) end if args.items then for _, v in pairs(args.items) do _menu:add(v) end end _menu._keygrabber = function (...) grabber(_menu, ...) end _menu.wibox = wibox({ ontop = true, fg = _menu.theme.fg_normal, bg = _menu.theme.bg_normal, border_color = _menu.theme.border, border_width = _menu.theme.border_width, type = "popup_menu" }) _menu.wibox.visible = false _menu.wibox:set_widget(_menu.layout) set_size(_menu) _menu.x = _menu.wibox.x _menu.y = _menu.wibox.y return _menu end function menu.mt:__call(...) return menu.new(...) end return setmetatable(menu, menu.mt) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
nesstea/darkstar
scripts/zones/Bastok_Markets/npcs/Olwyn.lua
13
1406
----------------------------------- -- Area: Bastok Markets -- NPC: Olwyn -- Standard Merchant NPC -- -- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape ----------------------------------- require("scripts/globals/events/harvest_festivals"); require("scripts/globals/shop"); package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) onHalloweenTrade(player,trade,npc) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,OLWYN_SHOP_DIALOG); stock = { 0x1020, 445,1, --Ether 0x1037, 736,2, --Echo Drops 0x1010, 837,2, --Potion 0x1036, 2387,3, --Eye Drops 0x1034, 290,3 --Antidote } showNationShop(player, BASTOK, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
jj918160/cocos2d-x-samples
samples/KillBug/src/cocos/cocos2d/functions.lua
46
17161
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] function printLog(tag, fmt, ...) local t = { "[", string.upper(tostring(tag)), "] ", string.format(tostring(fmt), ...) } print(table.concat(t)) end function printError(fmt, ...) printLog("ERR", fmt, ...) print(debug.traceback("", 2)) end function printInfo(fmt, ...) if type(DEBUG) ~= "number" or DEBUG < 2 then return end printLog("INFO", fmt, ...) end local function dump_value_(v) if type(v) == "string" then v = "\"" .. v .. "\"" end return tostring(v) end function dump(value, desciption, nesting) if type(nesting) ~= "number" then nesting = 3 end local lookupTable = {} local result = {} local traceback = string.split(debug.traceback("", 2), "\n") print("dump from: " .. string.trim(traceback[3])) local function dump_(value, desciption, indent, nest, keylen) desciption = desciption or "<var>" local spc = "" if type(keylen) == "number" then spc = string.rep(" ", keylen - string.len(dump_value_(desciption))) end if type(value) ~= "table" then result[#result +1 ] = string.format("%s%s%s = %s", indent, dump_value_(desciption), spc, dump_value_(value)) elseif lookupTable[tostring(value)] then result[#result +1 ] = string.format("%s%s%s = *REF*", indent, dump_value_(desciption), spc) else lookupTable[tostring(value)] = true if nest > nesting then result[#result +1 ] = string.format("%s%s = *MAX NESTING*", indent, dump_value_(desciption)) else result[#result +1 ] = string.format("%s%s = {", indent, dump_value_(desciption)) local indent2 = indent.." " local keys = {} local keylen = 0 local values = {} for k, v in pairs(value) do keys[#keys + 1] = k local vk = dump_value_(k) local vkl = string.len(vk) if vkl > keylen then keylen = vkl end values[k] = v end table.sort(keys, function(a, b) if type(a) == "number" and type(b) == "number" then return a < b else return tostring(a) < tostring(b) end end) for i, k in ipairs(keys) do dump_(values[k], k, indent2, nest + 1, keylen) end result[#result +1] = string.format("%s}", indent) end end end dump_(value, desciption, "- ", 1) for i, line in ipairs(result) do print(line) end end function printf(fmt, ...) print(string.format(tostring(fmt), ...)) end function checknumber(value, base) return tonumber(value, base) or 0 end function checkint(value) return math.round(checknumber(value)) end function checkbool(value) return (value ~= nil and value ~= false) end function checktable(value) if type(value) ~= "table" then value = {} end return value end function isset(hashtable, key) local t = type(hashtable) return (t == "table" or t == "userdata") and hashtable[key] ~= nil end local setmetatableindex_ setmetatableindex_ = function(t, index) if type(t) == "userdata" then local peer = tolua.getpeer(t) if not peer then peer = {} tolua.setpeer(t, peer) end setmetatableindex_(peer, index) else local mt = getmetatable(t) if not mt then mt = {} end if not mt.__index then mt.__index = index setmetatable(t, mt) elseif mt.__index ~= index then setmetatableindex_(mt, index) end end end setmetatableindex = setmetatableindex_ function clone(object) local lookup_table = {} local function _copy(object) if type(object) ~= "table" then return object elseif lookup_table[object] then return lookup_table[object] end local newObject = {} lookup_table[object] = newObject for key, value in pairs(object) do newObject[_copy(key)] = _copy(value) end return setmetatable(newObject, getmetatable(object)) end return _copy(object) end function class(classname, ...) local cls = {__cname = classname} local supers = {...} for _, super in ipairs(supers) do local superType = type(super) assert(superType == "nil" or superType == "table" or superType == "function", string.format("class() - create class \"%s\" with invalid super class type \"%s\"", classname, superType)) if superType == "function" then assert(cls.__create == nil, string.format("class() - create class \"%s\" with more than one creating function", classname)); -- if super is function, set it to __create cls.__create = super elseif superType == "table" then if super[".isclass"] then -- super is native class assert(cls.__create == nil, string.format("class() - create class \"%s\" with more than one creating function or native class", classname)); cls.__create = function() return super:create() end else -- super is pure lua class cls.__supers = cls.__supers or {} cls.__supers[#cls.__supers + 1] = super if not cls.super then -- set first super pure lua class as class.super cls.super = super end end else error(string.format("class() - create class \"%s\" with invalid super type", classname), 0) end end cls.__index = cls if not cls.__supers or #cls.__supers == 1 then setmetatable(cls, {__index = cls.super}) else setmetatable(cls, {__index = function(_, key) local supers = cls.__supers for i = 1, #supers do local super = supers[i] if super[key] then return super[key] end end end}) end if not cls.ctor then -- add default constructor cls.ctor = function() end end cls.new = function(...) local instance if cls.__create then instance = cls.__create(...) else instance = {} end setmetatableindex(instance, cls) instance.class = cls instance:ctor(...) return instance end cls.create = function(_, ...) return cls.new(...) end return cls end local iskindof_ iskindof_ = function(cls, name) local __index = rawget(cls, "__index") if type(__index) == "table" and rawget(__index, "__cname") == name then return true end if rawget(cls, "__cname") == name then return true end local __supers = rawget(cls, "__supers") if not __supers then return false end for _, super in ipairs(__supers) do if iskindof_(super, name) then return true end end return false end function iskindof(obj, classname) local t = type(obj) if t ~= "table" and t ~= "userdata" then return false end local mt if t == "userdata" then if tolua.iskindof(obj, classname) then return true end mt = tolua.getpeer(obj) else mt = getmetatable(obj) end if mt then return iskindof_(mt, classname) end return false end function import(moduleName, currentModuleName) local currentModuleNameParts local moduleFullName = moduleName local offset = 1 while true do if string.byte(moduleName, offset) ~= 46 then -- . moduleFullName = string.sub(moduleName, offset) if currentModuleNameParts and #currentModuleNameParts > 0 then moduleFullName = table.concat(currentModuleNameParts, ".") .. "." .. moduleFullName end break end offset = offset + 1 if not currentModuleNameParts then if not currentModuleName then local n,v = debug.getlocal(3, 1) currentModuleName = v end currentModuleNameParts = string.split(currentModuleName, ".") end table.remove(currentModuleNameParts, #currentModuleNameParts) end return require(moduleFullName) end function handler(obj, method) return function(...) return method(obj, ...) end end function math.newrandomseed() local ok, socket = pcall(function() return require("socket") end) if ok then math.randomseed(socket.gettime() * 1000) else math.randomseed(os.time()) end math.random() math.random() math.random() math.random() end function math.round(value) value = checknumber(value) return math.floor(value + 0.5) end local pi_div_180 = math.pi / 180 function math.angle2radian(angle) return angle * pi_div_180 end local pi_mul_180 = math.pi * 180 function math.radian2angle(radian) return radian / pi_mul_180 end function io.exists(path) local file = io.open(path, "r") if file then io.close(file) return true end return false end function io.readfile(path) local file = io.open(path, "r") if file then local content = file:read("*a") io.close(file) return content end return nil end function io.writefile(path, content, mode) mode = mode or "w+b" local file = io.open(path, mode) if file then if file:write(content) == nil then return false end io.close(file) return true else return false end end function io.pathinfo(path) local pos = string.len(path) local extpos = pos + 1 while pos > 0 do local b = string.byte(path, pos) if b == 46 then -- 46 = char "." extpos = pos elseif b == 47 then -- 47 = char "/" break end pos = pos - 1 end local dirname = string.sub(path, 1, pos) local filename = string.sub(path, pos + 1) extpos = extpos - pos local basename = string.sub(filename, 1, extpos - 1) local extname = string.sub(filename, extpos) return { dirname = dirname, filename = filename, basename = basename, extname = extname } end function io.filesize(path) local size = false local file = io.open(path, "r") if file then local current = file:seek() size = file:seek("end") file:seek("set", current) io.close(file) end return size end function table.nums(t) local count = 0 for k, v in pairs(t) do count = count + 1 end return count end function table.keys(hashtable) local keys = {} for k, v in pairs(hashtable) do keys[#keys + 1] = k end return keys end function table.values(hashtable) local values = {} for k, v in pairs(hashtable) do values[#values + 1] = v end return values end function table.merge(dest, src) for k, v in pairs(src) do dest[k] = v end end function table.insertto(dest, src, begin) begin = checkint(begin) if begin <= 0 then begin = #dest + 1 end local len = #src for i = 0, len - 1 do dest[i + begin] = src[i + 1] end end function table.indexof(array, value, begin) for i = begin or 1, #array do if array[i] == value then return i end end return false end function table.keyof(hashtable, value) for k, v in pairs(hashtable) do if v == value then return k end end return nil end function table.removebyvalue(array, value, removeall) local c, i, max = 0, 1, #array while i <= max do if array[i] == value then table.remove(array, i) c = c + 1 i = i - 1 max = max - 1 if not removeall then break end end i = i + 1 end return c end function table.map(t, fn) for k, v in pairs(t) do t[k] = fn(v, k) end end function table.walk(t, fn) for k,v in pairs(t) do fn(v, k) end end function table.filter(t, fn) for k, v in pairs(t) do if not fn(v, k) then t[k] = nil end end end function table.unique(t, bArray) local check = {} local n = {} local idx = 1 for k, v in pairs(t) do if not check[v] then if bArray then n[idx] = v idx = idx + 1 else n[k] = v end check[v] = true end end return n end string._htmlspecialchars_set = {} string._htmlspecialchars_set["&"] = "&amp;" string._htmlspecialchars_set["\""] = "&quot;" string._htmlspecialchars_set["'"] = "&#039;" string._htmlspecialchars_set["<"] = "&lt;" string._htmlspecialchars_set[">"] = "&gt;" function string.htmlspecialchars(input) for k, v in pairs(string._htmlspecialchars_set) do input = string.gsub(input, k, v) end return input end function string.restorehtmlspecialchars(input) for k, v in pairs(string._htmlspecialchars_set) do input = string.gsub(input, v, k) end return input end function string.nl2br(input) return string.gsub(input, "\n", "<br />") end function string.text2html(input) input = string.gsub(input, "\t", " ") input = string.htmlspecialchars(input) input = string.gsub(input, " ", "&nbsp;") input = string.nl2br(input) return input end function string.split(input, delimiter) input = tostring(input) delimiter = tostring(delimiter) if (delimiter=='') then return false end local pos,arr = 0, {} -- for each divider found for st,sp in function() return string.find(input, delimiter, pos, true) end do table.insert(arr, string.sub(input, pos, st - 1)) pos = sp + 1 end table.insert(arr, string.sub(input, pos)) return arr end function string.ltrim(input) return string.gsub(input, "^[ \t\n\r]+", "") end function string.rtrim(input) return string.gsub(input, "[ \t\n\r]+$", "") end function string.trim(input) input = string.gsub(input, "^[ \t\n\r]+", "") return string.gsub(input, "[ \t\n\r]+$", "") end function string.ucfirst(input) return string.upper(string.sub(input, 1, 1)) .. string.sub(input, 2) end local function urlencodechar(char) return "%" .. string.format("%02X", string.byte(char)) end function string.urlencode(input) -- convert line endings input = string.gsub(tostring(input), "\n", "\r\n") -- escape all characters but alphanumeric, '.' and '-' input = string.gsub(input, "([^%w%.%- ])", urlencodechar) -- convert spaces to "+" symbols return string.gsub(input, " ", "+") end function string.urldecode(input) input = string.gsub (input, "+", " ") input = string.gsub (input, "%%(%x%x)", function(h) return string.char(checknumber(h,16)) end) input = string.gsub (input, "\r\n", "\n") return input end function string.utf8len(input) local len = string.len(input) local left = len local cnt = 0 local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc} while left ~= 0 do local tmp = string.byte(input, -left) local i = #arr while arr[i] do if tmp >= arr[i] then left = left - i break end i = i - 1 end cnt = cnt + 1 end return cnt end function string.formatnumberthousands(num) local formatted = tostring(checknumber(num)) local k while true do formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') if k == 0 then break end end return formatted end
mit
UnfortunateFruit/darkstar
scripts/globals/weaponskills/fast_blade.lua
30
1345
----------------------------------- -- Fast Blade -- Sword weapon skill -- Skill Level: 5 -- Delivers a two-hit attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Soil Gorget. -- Aligned with the Soil Belt. -- Element: None -- Modifiers: STR:20% ; DEX:20% -- 100%TP 200%TP 300%TP -- 1.00 1.50 2.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 2; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; params.str_wsc = 0.2; params.dex_wsc = 0.2; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.4; params.dex_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
nesstea/darkstar
scripts/zones/Labyrinth_of_Onzozo/npcs/Grounds_Tome.lua
30
1104
----------------------------------- -- Area: Labyrinth of Onzozo -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_LABYRINTH_OF_ONZOZO,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,771,772,773,774,775,776,0,0,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,771,772,773,774,775,776,0,0,0,0,GOV_MSG_LABYRINTH_OF_ONZOZO); end;
gpl-3.0
Mashape/kong
kong/cmd/config.lua
1
4459
local DB = require "kong.db" local log = require "kong.cmd.utils.log" local pl_path = require "pl.path" local pl_file = require "pl.file" local kong_global = require "kong.global" local declarative = require "kong.db.declarative" local conf_loader = require "kong.conf_loader" local kong_yml = require "kong.templates.kong_yml" local INIT_FILE = "kong.yml" local accepted_formats = { yaml = true, json = true, lua = true, } local function db_export(filename, conf) if pl_file.access_time(filename) then error(filename .. " already exists. Will not overwrite it.") end local fd, err = io.open(filename, "w") if not fd then return nil, err end local ok, err = declarative.export_from_db(fd) if not ok then error(err) end fd:close() os.exit(0) end local function generate_init() if pl_file.access_time(INIT_FILE) then error(INIT_FILE .. " already exists in the current directory.\n" .. "Will not overwrite it.") end pl_file.write(INIT_FILE, kong_yml) end local function execute(args) if args.command == "init" then generate_init() os.exit(0) end log.disable() -- retrieve default prefix or use given one local conf = assert(conf_loader(args.conf, { prefix = args.prefix })) log.enable() if pl_path.exists(conf.kong_env) then -- load <PREFIX>/kong.conf containing running node's config conf = assert(conf_loader(conf.kong_env)) end args.command = args.command:gsub("%-", "_") if args.command == "db_import" and conf.database == "off" then error("'kong config db_import' only works with a database.\n" .. "When using database=off, reload your declarative configuration\n" .. "using the /config endpoint.") end if args.command == "db_export" and conf.database == "off" then error("'kong config db_export' only works with a database.") end package.path = conf.lua_package_path .. ";" .. package.path local dc, err = declarative.new_config(conf) if not dc then error(err) end _G.kong = kong_global.new() kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK local db = assert(DB.new(conf)) assert(db:init_connector()) assert(db:connect()) assert(db.plugins:load_plugin_schemas(conf.loaded_plugins)) _G.kong.db = db if args.command == "db_export" then return db_export(args[1] or "kong.yml", conf) end if args.command == "db_import" or args.command == "parse" then local filename = args[1] if not filename then error("expected a declarative configuration file; see `kong config --help`") end local dc_table, err, _, vers = dc:parse_file(filename, accepted_formats) if not dc_table then error("Failed parsing:\n" .. err) end if args.command == "db_import" then log("parse successful, beginning import") local ok, err = declarative.load_into_db(dc_table) if not ok then error("Failed importing:\n" .. err) end log("import successful") -- send anonymous report if reporting is not disabled if conf.anonymous_reports then local kong_reports = require "kong.reports" kong_reports.configure_ping(conf) kong_reports.toggle(true) local report = { decl_fmt_version = vers } kong_reports.send("config-db-import", report) end else -- parse log("parse successful") end os.exit(0) end error("unknown command '" .. args.command .. "'") end local lapp = [[ Usage: kong config COMMAND [OPTIONS] Use declarative configuration files with Kong. The available commands are: init Generate an example config file to get you started. db_import <file> Import a declarative config file into the Kong database. db_export <file> Export the Kong database into a declarative config file. parse <file> Parse a declarative config file (check its syntax) but do not load it into Kong. Options: -c,--conf (optional string) Configuration file. -p,--prefix (optional string) Override prefix directory. ]] return { lapp = lapp, execute = execute, sub_commands = { init = true, db_import = true, db_export = true, parse = true, }, }
apache-2.0
mostsun1987/codis
extern/redis-2.8.13/deps/lua/test/life.lua
888
2635
-- life.lua -- original by Dave Bollinger <DBollinger@compuserve.com> posted to lua-l -- modified to use ANSI terminal escape sequences -- modified to use for instead of while local write=io.write ALIVE="¥" DEAD="þ" ALIVE="O" DEAD="-" function delay() -- NOTE: SYSTEM-DEPENDENT, adjust as necessary for i=1,10000 do end -- local i=os.clock()+1 while(os.clock()<i) do end end function ARRAY2D(w,h) local t = {w=w,h=h} for y=1,h do t[y] = {} for x=1,w do t[y][x]=0 end end return t end _CELLS = {} -- give birth to a "shape" within the cell array function _CELLS:spawn(shape,left,top) for y=0,shape.h-1 do for x=0,shape.w-1 do self[top+y][left+x] = shape[y*shape.w+x+1] end end end -- run the CA and produce the next generation function _CELLS:evolve(next) local ym1,y,yp1,yi=self.h-1,self.h,1,self.h while yi > 0 do local xm1,x,xp1,xi=self.w-1,self.w,1,self.w while xi > 0 do local sum = self[ym1][xm1] + self[ym1][x] + self[ym1][xp1] + self[y][xm1] + self[y][xp1] + self[yp1][xm1] + self[yp1][x] + self[yp1][xp1] next[y][x] = ((sum==2) and self[y][x]) or ((sum==3) and 1) or 0 xm1,x,xp1,xi = x,xp1,xp1+1,xi-1 end ym1,y,yp1,yi = y,yp1,yp1+1,yi-1 end end -- output the array to screen function _CELLS:draw() local out="" -- accumulate to reduce flicker for y=1,self.h do for x=1,self.w do out=out..(((self[y][x]>0) and ALIVE) or DEAD) end out=out.."\n" end write(out) end -- constructor function CELLS(w,h) local c = ARRAY2D(w,h) c.spawn = _CELLS.spawn c.evolve = _CELLS.evolve c.draw = _CELLS.draw return c end -- -- shapes suitable for use with spawn() above -- HEART = { 1,0,1,1,0,1,1,1,1; w=3,h=3 } GLIDER = { 0,0,1,1,0,1,0,1,1; w=3,h=3 } EXPLODE = { 0,1,0,1,1,1,1,0,1,0,1,0; w=3,h=4 } FISH = { 0,1,1,1,1,1,0,0,0,1,0,0,0,0,1,1,0,0,1,0; w=5,h=4 } BUTTERFLY = { 1,0,0,0,1,0,1,1,1,0,1,0,0,0,1,1,0,1,0,1,1,0,0,0,1; w=5,h=5 } -- the main routine function LIFE(w,h) -- create two arrays local thisgen = CELLS(w,h) local nextgen = CELLS(w,h) -- create some life -- about 1000 generations of fun, then a glider steady-state thisgen:spawn(GLIDER,5,4) thisgen:spawn(EXPLODE,25,10) thisgen:spawn(FISH,4,12) -- run until break local gen=1 write("\027[2J") -- ANSI clear screen while 1 do thisgen:evolve(nextgen) thisgen,nextgen = nextgen,thisgen write("\027[H") -- ANSI home cursor thisgen:draw() write("Life - generation ",gen,"\n") gen=gen+1 if gen>2000 then break end --delay() -- no delay end end LIFE(40,20)
bsd-3-clause
nesstea/darkstar
scripts/zones/Lower_Jeuno/npcs/Pawkrix.lua
13
1254
----------------------------------- -- Area: Lower Jeuno -- NPC: -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,PAWKRIX_SHOP_DIALOG); stock = {0x0277,36, -- Horo Flour 0x116A,276, -- Goblin Bread 0x11BB,650, -- Goblin Pie 0x118F,35, -- Goblin Chocolate 0x11BF,1140, -- Goblin Mushpot 0x03B8,515, -- Poison Flour 0x04D7,490} -- Goblin Doll showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
FailcoderAddons/supervillain-ui
SVUI_!Core/language/taiwanese_ui.lua
3
39900
local L = Librarian("Linguist"):Lang("zhTW"); if not L then return; end L["Conversation"] = "對話" L["General"] = "綜合" L["LocalDefense"] = "本地防務" L["LookingForGroup"] = "尋求組隊" L["Trade"] = "交易" L["WorldDefense"] = "世界防務" L["S_Conversation"] = "話" L["S_General"] = "綜" L["S_LocalDefense"] = "本" L["S_LookingForGroup"] = "尋" L["S_Trade"] = "交" L["S_WorldDefense"] = "世" L["Hearthstone"] = true; --[[LOGIN MESSAGE]]-- L["LOGIN_MSG"] = "歡迎使用 |cffFFFF1ASVUI|r! 让您的 %s 和你 %s." L["LOGIN_MSG2"] = "|cffAA78FF%s|r 版, 請輸入/sv 進入設定介面." --[[OPTION MESSAGES]]-- L["AURAS_DESC"] = "小地圖旁的光環圖示設定." L["BAGS_DESC"] = "調整 SVUI 背包設定." L["CHAT_DESC"] = "對話框架設定." L["STATS_DESC"] = "Configure docked stat panels."; L["SVUI_DESC"] = "SVUI 為一套功能完整, 可用來替換 WOW 原始介面的 UI 套件" L["NAMEPLATE_DESC"] = "修改血條設定." L["PANEL_DESC"] = "調整左、右對話框的尺寸, 此設定將會影響對話與背包框架的尺寸." L["ART_DESC"] = "調整外觀設定." L["TOGGLEART_DESC"] = "啟用 / 停用此外觀." L["TOOLTIP_DESC"] = "浮動提示資訊設定選項." L["TEXT_FORMAT_DESC"] = "Select the formatting of this text" L["import"] = "現有的設定檔" L["import_desc"] = "你可以通過在文本框內輸入一個名字創立一個新的設定檔,也可以選擇一個已經存在的設定檔。" L["import_sub"] = "從當前可用的設定檔裏面選擇一個。" L["copy_name"] = "複製自" L["copy_desc"] = "從當前某個已保存的設定檔複製到當前正使用的設定檔。" L["current"] = "Current Profile:" L["default"] = "預設" L["delete"] = "刪除一個設定檔" L["delete_confirm"] = "你確定要刪除所選擇的設定檔嗎?" L["delete_desc"] = "從資料庫裏刪除不再使用的設定檔,以節省空間,並且清理SavedVariables檔。" L["delete_sub"] = "從資料庫裏刪除一個設定檔。" L["intro"] = "你可以選擇一個活動的資料設定檔,這樣你的每個角色就可以擁有不同的設定值,可以給你的插件設定帶來極大的靈活性。" L["export"] = "新建" L["export_sub"] = "新建一個空的設定檔。" L["profiles"] = "設定檔" L["profiles_sub"] = "管理設定檔" L["reset"] = "重置設定檔" L["reset_desc"] = "將當前的設定檔恢復到它的預設值,用於你的設定檔損壞,或者你只是想重來的情況。" L["reset_sub"] = "將當前的設定檔恢復為預設值" L["SVUI_DockBottomCenter"] = "Bottom Data Dock" L["SVUI_DockTopCenter"] = "Top Data Dock" --[[REACTION TEXTS]]-- L[" is drinking."] = true; L["Leeeeeroy!"] = true; L["No Food: "] = "缺少食物Buff: " L["No Flask: "] = "缺少精煉藥劑: " L["All Buffed!"] = "已獲得所有增益!" L["Check food and flask"] = "檢查食物和精煉" L["Thanks for "] = "謝謝你的 " L[" received from "] = " 收到來自于 " L["GO!"] = "開始!" L["Pulling %s in %s.."] = "正在拉: %s, 倒數 %s.." L["Pull ABORTED!"] = "取消拉怪!" L["%s has prepared a %s - [%s]."] = "%s 放置了 %s - [%s]." L["%s has prepared a %s."] = "%s 放置了 %s" L["%s has put down a %s."] = "%s 放置了 %s" L["%s is casting %s."] = "%s 開啟了 %s" L["%s is casting %s. Click!"] = "%s 正在開啟 %s... 請點擊!" L["%s used a %s."] = "%s 使用了 %s." --[[FORMATTED INSTALLER TEXTS]]-- L["|cffD3CF00Recommended|r"] = true; L["Recommended: |cff99FF00Kaboom!|r"] = true; L["Recommended: |cff99FF00Super|r"] = true; L["Recommended: |cffFF0000Small Row!|r"] = true; L["Recommended: |cffFF0000Icon Lovers!|r"] = true; L["|cffFF9F00KABOOOOM!|r"] = true; L["|cffAF30FFThe Darkest Night|r"] = true; L["|cff00FFFFPlain and Simple|r"] = true; L["|cff00FFFFLets Do This|r"] = true; L["|cff00FFFFSimply Simple|r"] = true; L["|cff00FFFFEl Compacto|r"] = true; L["|cff00FFFFHealer Extraordinaire|r"] = true; L["|cff00FFFFLean And Clean|r"] = true; L["|cff00FFFFMore For Less|r"] = true; L["|cff00FFFFWhat Big Buttons You Have|r"] = true; L["|cff00FFFFThe Double Down|r"] = true; --[[NORMAL INSTALLER TEXTS]]-- L["This is SVUI version %s!"] = true; L["Before I can turn you loose, persuing whatever villainy you feel will advance your professional career ... I need to ask some questions and turn a few screws first."] = true; L["At any time you can get to the config options by typing the command /sv. For quick changes to frame, bar or color sets, call your henchman by clicking the button on the bottom right of your screen. (Its the one with his stupid face on it)"] = true; L["CHOOSE_OR_DIE"] = CHOOSE_FACTION.." "..OR_CAPS.." "..HIT.." "..CONTINUE; L["Whether you want to or not, you will be needing a communicator so other villains can either update you on their doings-of-evil or inform you about the MANY abilities of Chuck Norris"] = true; L["The chat windows function the same as standard chat windows, you can right click the tabs and drag them, rename them, slap them around, you know... whatever. Clickity-click to setup your chat windows."] = true; L["Your current resolution is %s, this is considered a %s resolution."] = true; L["This resolution requires that you change some settings to get everything to fit on your screen."] = true; L["Click the button below to resize your chat frames, unitframes, and reposition your actionbars."] = true; L["You may need to further alter these settings depending how low you resolution is."] = true; L["This resolution doesn't require that you change settings for the UI to fit on your screen."] = true; L["Click the button below to resize your chat frames, unitframes, and reposition your actionbars."] = true; L["This is completely optional."] = true; L["So what you think your better than me with your big monitor? HUH?!?!"] = true; L["Dont forget whos in charge here! But enjoy the incredible detail."] = true; L["Why are you playing this on what I would assume is a calculator display?"] = true; L["Enjoy the ONE incredible pixel that fits on this screen."] = true; L["Choose a theme layout you wish to use for your initial setup."] = true; L["You can always change fonts and colors of any element of SVUI from the in-game configuration."] = true; L["This theme tells the world that you are a villain who can put on a show "] = true; L["or better yet, you ARE the show!"] = true; L["Kaboom!"] = true; L["This theme indicates that you have no interest in wasting time"] = true; L["the dying begins NOW!"] = true; L["Darkness"] = true; L["This theme is for villains who take pride in their class"] = true; L["villains know how to reprezent!"] = true; L["This theme is for any villain who sticks to their traditions"] = true; L["you don't need fancyness to kick some ass!"] = true; L["Vintage"] = true; L["Layout"] = true; L["You can now choose what primary unitframe style you wish to use."] = true; L["This will change the layout of your unitframes (ie.. Player, Target, Pet, Party, Raid ...etc)."] = true; L["This layout is anything but minimal! Using this is like being at a rock concert"] = true; L["then annihilating the crowd with frickin lazer beams!"] = true; L["Super"] = true; L["This layout is for the villain who just wants to get things done!"] = true; L["But he still wants to see your face before he hits you!"] = true; L["Simple"] = true; L["Just the necessities so you can see more of the world around you."] = true; L["You dont need no fanciness getting in the way of world domination do you?"] = true; L["Compact"] = true; L["This has all the pizzaz of Super frames but uses Compact party and raid frames."] = true; L["Sometimes a little fifty-fifty goes a long way."] = true; L["Healer"] = true; L["Bar Setup"] = true; L["Choose a layout for your action bars."] = true; L["Sometimes you need big buttons, sometimes you don't. Your choice here."] = true; L["Lets keep it slim and deadly, not unlike a ninja sword."] = true; L["You dont ever even look at your bar hardly, so pick this one!"] = true; L["Small Row"] = true; L["Granted, you dont REALLY need the buttons due to your hotkey-leetness, you just like watching cooldowns!"] = true; L["Sure thing cowboy, your secret is safe with me!"] = true; L["Small X2"] = true; L["The better to PEW-PEW you with my dear!"] = true; L["When you have little time for mouse accuracy, choose this set!"] = true; L["Big Row"] = true; L["It's like dual-wielding two big reasons for your enemies to back the **** up!"] = true; L["Double your bars then double their size for maximum button goodness!"] = true; L["Big X2"] = true; L["Auras System"] = true; L["Select the type of aura system you want to use with SVUI's unitframes. The Icon Lovers set will display only icons and aurabars won't be used. The Vintage set will use the original game style and the Gimme Everything set does just what it says.... icons, bars and awesomeness."] = true; L["If you have an icon or aurabar that you don't want to display simply hold down shift and right click the icon for it to suffer a painful death."] = true; L["Vintage"] = true; L["Icon Lovers"] = true; L["The Works!"] = true; L["Installation Complete"] = true; L["Thats it! All done! Now we just need to hand these choices off to the henchmen so they can get you ready to (..insert evil tasks here..)!"] = true; L["Click the button below to reload and get on your way! Good luck villain!"] = true; L["THE_BUTTON_BELOW"] = "THE\nBUTTON\nBELOW"; --[[UI TEXTS]]-- L["Meanwhile"]=true; L["..at "]=true; L["A taint has occured that is preventing you from using the queue system. Please reload your user interface and try again."]="發生一個錯誤導致你無法使用隊列系統,請重新加載你的用戶界面,然後再試一次." L["Binding"]="綁定" L["Key"]="鍵" L["KEY_ALT"]="A" L["KEY_CTRL"]="C" L["KEY_DELETE"]="Del" L["KEY_HOME"]="Hm" L["KEY_INSERT"]="Ins" L["KEY_MOUSEBUTTON"]="M" L["KEY_MOUSEWHEELDOWN"]="MwD" L["KEY_MOUSEWHEELUP"]="MwU" L["KEY_NUMPAD"]="N" L["KEY_PAGEDOWN"]="PD" L["KEY_PAGEUP"]="PU" L["KEY_SHIFT"]="S" L["KEY_SPACE"]="SpB" L["No bindings set."]="未設定快捷綁定." L["Remove Bar %d Action Page"]="移除第 %d 快捷列" L["Trigger"]="觸發器" L["Delete Grays"]="刪除灰色物品" L["Hold Control + Right Click:"]='按住 Ctrl 並按滑鼠右鍵:' L["Hold Shift + Drag:"]='按住 Shift 並拖曳:' L["Hold Shift:"]="按住 Shift:" L["Purchase"]="購買銀行欄位" L["Reset Position"]='重設位置' L["Sort Bags"]="整理背包" L["Sort Tab"]=true; L["Stack Bags to Bank"]='物品堆疊至銀行' L["Stack Bank to Bags"]='物品堆疊至背包' L["Stack Items"]="堆疊物品" L["Temporary Move"]='移動背包' L["Toggle Bags"]='開啟/關閉背包' L["Vendor Grays"]="出售灰色物品" L["AFK"]="離開" L["DND"]="忙碌" L["G"]="公會" L["I"]='副本' L["IL"]='副本隊長' L["Invalid Target"]="無效的目標" L["O"]="幹部" L["P"]="隊伍" L["PL"]="隊長" L["R"]="團隊" L["RL"]="團隊隊長" L["RW"]="團隊警告" L["says"]="說" L["whispers"]="密語" L["yells"]="大喊" L["(Hold Shift) Memory Usage"]="(按住Shift) 記憶體使用量" L["AP"]="攻擊強度" L["AVD: "]="免傷: " L["Avoidance Breakdown"]="免傷統計" L["Bandwidth"]="頻寬" L["Bases Assaulted"]="已佔領基地" L["Bases Defended"]="已守住基地" L["Carts Controlled"]="已操控乘載器具" L["Character: "]="角色: " L["Chest"]="胸部" L["Combat Time"]="戰斗時間" L["copperabbrev"]="|cffeda55f銅|r" L["Defeated"]="已擊殺" L["Deficit:"]="赤字:" L["Demolishers Destroyed"]="已摧毀攻城器具" L["Download"]="下載" L["DPS"]="傷害輸出" L["Earned:"]="賺取:" L["Feet"]="腳部" L["Flags Captured"]="已奪取旗幟" L["Flags Returned"]="已交還旗幟" L["Friends List"]="好友列表" L["Friends"]="好友" L["Galleon"]="帆船" L["Gates Destroyed"]="已摧毀城門" L["goldabbrev"]="|cffffd700金|r" L["Graveyards Assaulted"]="已佔領墓地" L["Graveyards Defended"]="已守住墓地" L["Hands"]="手部" L["Head"]="頭部" L["Hit"]="命中" L["Home Latency:"]="本機延遲:" L["HP"]="生命值" L["HPS"]="治療輸出" L["Legs"]="腿部" L["lvl"]="等級" L["Main Hand"]="主手" L["Mitigation By Level: "]="等級減傷: " L["Nalak"]="納拉卡" L["No Guild"]="沒有公會" L["Offhand"]="副手" L["Oondasta"]="烏達斯塔" L["Orb Possessions"]="寶珠屬地" L["Profit:"]="利潤: " L["Reset Data: Hold Shift + Right Click"]="重置數據: 按住 Shift + 右鍵點擊" L["Saved Raid(s)"]="已有進度的副本" L["Server: "]="伺服器: " L["Session:"]="本次登入:" L["Sha of Anger"]="憤怒之煞" L["Shoulder"]="肩部" L["silverabbrev"]="|cffc7c7cf銀|r" L["SP"]="法術能量" L["Spent:"]="花費:" L["Stats For:"]="統計:" L["Total CPU:"]="CPU佔用" L["Total Memory:"]="總記憶體:" L["Total: "]="合計: " L["Towers Assaulted"]="已佔領哨塔" L["Towers Defended"]="已守住哨塔" L["Undefeated"]="未擊殺" L["Unhittable:"]="未命中:" L["Victory Points"]="勝利點數" L["Waist"]="腰部" L["World Boss(s)"]="世界首領" L["Wrist"]="護腕" L["%s: %s tried to call the protected function '%s'."]="%s: %s 嘗試調用保護函數'%s'." L["No locals to dump"]="沒有本地文件" L["%s is attempting to share his filters with you. Would you like to accept the request?"]="%s 試圖與你分享過濾器配置. 你是否接受?" L["%s is attempting to share the profile %s with you. Would you like to accept the request?"]="%s 試圖與你分享配置文件 %s. 你是否接受?" L["Data From: %s"]="數據來源: %s" L["Filter download complete from %s, would you like to apply changes now?"]="過濾器配置下載於 %s, 你是否現在變更?" L["Lord! It's a miracle! The download up and vanished like a fart in the wind! Try Again!"]="天啊! 太奇葩啦! 下載消失了! 就像是在風中放了個屁... 再試一次吧!" L["Profile download complete from %s, but the profile %s already exists. Change the name or else it will overwrite the existing profile."]="配置文件從 %s 下載完成, 但是配置文件 %s 已存在. 請更改名稱, 否則它會覆蓋你的現有配置文件." L["Profile download complete from %s, would you like to load the profile %s now?"]="配置文件從 %s 下載完成, 你是否要加載配置文件 %s?" L["Profile request sent. Waiting for response from player."]="已發送文件請求. 等待對方響應." L["Request was denied by user."]="請求被對方拒絕." L["Your profile was successfully recieved by the player."]="你的配置文件已被其他玩家成功接收." L["Auras Set"]="光環樣式設定" L["Auras System"]="光環樣式" L["Caster DPS"]="法系輸出" L["Chat Set"]="對話设置" L["Chat"]="對話" L["Choose a theme layout you wish to use for your initial setup."]="為你的個人設定選擇一個你喜歡的皮膚主題." L["Vintage"]="經典" L["Classic"]="經典" L["Click the button below to resize your chat frames, unitframes, and reposition your actionbars."]="點擊下面的按鈕調整對話框、單位框架的尺寸, 以及移動快捷列位置." L["Config Mode:"]="設定模式:" L["CVars Set"]="參數設定" L["CVars"]="參數" L["Gloom & Doom"]="黑暗" L["Disable"]="禁用" L["SVUI Installation"]="安裝 SVUI" L["Finished"]="設定完畢" L["Grid Size:"]="網格尺寸:" L["Healer"]="補師" L["High Resolution"]="高解析度" L["high"]="高" L["Icons Only"]="圖示" L["If you have an icon or aurabar that you don't want to display simply hold down shift and right click the icon for it to disapear."]="如果你有不想顯示的圖示或光環條, 你可以簡單的通過按住Shift右鍵點擊使它隱藏." L["Importance: |cff07D400High|r"]="重要性: |cff07D400高|r" L["Importance: |cffD3CF00Medium|r"]="重要性: |cffD3CF00中|r" L["Importance: |cffFF0000Low|r"]="重要性: |cffFF0000低|r" L["Installation Complete"]="安裝完畢" L["Integrated"]="整合" L["Layout Set"]="版面配置設定" L["Layout"]="介面佈局" L["Lock"]="鎖定" L["Low Resolution"]="低解析度" L["low"]="低" L["Frames unlocked. Move them now and click Lock when you are done."]="解除框架移動鎖定. 現在可以移動它們, 移好後請點擊「鎖定」." L["Nudge"]="微調" L["Physical DPS"]="物理輸出" L["Pixel Perfect Set"]="像素設置" L["Pixel Perfect"]="像素完美" L["Please click the button below so you can setup variables and ReloadUI."]="請按下方按鈕設定變數並重載介面." L["Please click the button below to setup your CVars."]="請按下方按鈕設定參數." L["Please press the continue button to go onto the next step."]="請按「繼續」按鈕,執行下一個步驟." L["Resolution Style Set"]="解析度樣式設定" L["Resolution"]="解析度" L["Select the type of aura system you want to use with SVUI's unitframes. The integrated system utilizes both aura-bars and aura-icons. The icons only system will display only icons and aurabars won't be used. The classic system will configure your auras to be default."]="選擇你想在頭像框架上使用的光環樣式. 集成樣式包含了光環條和圖示. 圖示樣式只包含圖示, 並且光環條將不再顯示." L["Setup Chat"]="設定對話視窗" L["Setup CVars"]="設定參數" L["Skip Process"]="略過" L["Sticky Frames"]="框架依附" L["Tank"]="坦克" L["The chat windows function the same as Blizzard standard chat windows, you can right click the tabs and drag them around, rename, etc. Please click the button below to setup your chat windows."]="對話視窗與WOW 原始對話視窗的操作方式相同, 你可以拖拉、移動分頁或重新命名分頁. 請按下方按鈕以設定對話視窗." L["The in-game configuration menu can be accesses by typing the /sv command or by clicking the 'C' button on the minimap. Press the button below if you wish to skip the installation process."]="若要進入內建設定選單, 請輸入/sv, 或者按一下小地圖旁的「C」按鈕.若要略過安裝程序, 請按下方按鈕." L["The Pixel Perfect option will change the overall apperance of your UI. Using Pixel Perfect is a slight performance increase over the traditional layout."]="像素完美選項將改變你的整體用戶界面, 使用像素完美能輕微提升傳統界面的性能." L["Theme Set"]="主題設置" L["Theme Setup"]="主題安裝" L["This install process will help you learn some of the features in SVUI has to offer and also prepare your user interface for usage."]="此安裝程序有助你瞭解SVUI 部份功能, 並可協助你預先設定UI." L["This is completely optional."]="此為選擇性功能." L["This part of the installation process sets up your chat windows names, positions and colors."]="此安裝步驟將會設定對話視窗的名稱、位置和顏色." L["This part of the installation process sets up your World of Warcraft default options it is recommended you should do this step for everything to behave properly."]="此安裝步驟將會設定 WOW 預設選項, 建議你執行此步驟, 以確保功能均可正常運作." L["This resolution doesn't require that you change settings for the UI to fit on your screen."]="這個解析度不需要你改動任何設定以適應你的屏幕." L["This resolution requires that you change some settings to get everything to fit on your screen."]="這個解析度需要你改變一些設定才能適應你的屏幕." L["This will change the layout of your unitframes, raidframes, and statistics."]="此材質適用於對話框架、下拉式選單等物件上." L["Trade"]="拾取/交易" L["Using this option will cause your borders around frames to be 1 pixel wide instead of 3 pixel. You may have to finish the installation to notice a differance. By default this is enable."]="此安裝步驟將會使你的周圍邊框幀是1像素寬而不是3像素, 你可能在安裝時已經注意到這一差異, 這是一個默認的啓用." L["Welcome to SVUI version %s!"]="歡迎使用 SVUI %s 版!" L["You are now finished with the installation process. If you are in need of technical support please visit us at http://www.wowinterface.com."]="已完成安裝程序. 小提示: 若想開啟微型選單, 請在小地圖按滑鼠中鍵. 如果沒有中鍵按鈕, 請按住Shift鍵, 並在小地圖按滑鼠右鍵. 如需技術支援請至http://www.wowinterface.com" L["You can always change fonts and colors of any element of SVUI from the in-game configuration."]="你可以在遊戲內的設定選項內更改SVUI的字體、顏色等設定." L["You can now choose what layout you wish to use based on your combat role."]="你現在可以根據你的戰鬥角色選擇合適的佈局." L["You may need to further alter these settings depending how low you resolution is."]="根據你的解析度你可能需要改動這些設定." L["Your current resolution is %s, this is considered a %s resolution."]="你當前的解析度是%s, 這被認為是個%s 解析度." L["Bars"]="條" L["Calendar"]="日曆" L["Can't Roll"]="無法需求此裝備" L["Disband Group"]="解散隊伍" L["Empty Slot"]="空欄位" L["Enable"]="啟用" L["Experience"]="經驗/聲望條" L["Fishy Loot"]="貪婪" L["Left Click:"]="滑鼠左鍵:" L["Raid Menu"]="團隊選單" L["Remaining:"]="剩餘:" L["Rested:"]="休息:" L["Right Click:"]="滑鼠右鍵:" L["Show BG Texts"]="顯示戰場資訊文字" L["Toggle Chat Frame"]="開關對話框架" L["Toggle Configuration"]="開啟/關閉設定" L["XP:"]="經驗:" L["You don't have permission to mark targets."]="你沒有標記目標的權限." L["ABOVE_THREAT_FORMAT"]='%s: %.0f%% [%.0f%% 以上 |cff%02x%02x%02x%s|r]' L[" Frames"]="框架" L["Alternative Power"]="特殊能量條框架" L["Arena Frames"]="競技場框架" L["Auras Frame"]="增益/減益 框架" L["Bags"]="背包" L["Bar "]="快捷列 " L["BNet Frame"]="戰網提示資訊" L["Special Ability Button"]="特殊技能鍵" L["Boss Frames"]="首領框架" L["Experience Bar"]="經驗條" L["Focus Castbar"]="焦點目標施法條" L["Focus Frame"]="焦點目標框架" L["FocusTarget Frame"]="焦點目標的目標框架" L["GM Ticket Frame"]="GM 對話框" L["Left Dock"]="左側對話框" L["Loot / Alert Frames"]="拾取 / 提醒框架" L["Loot Frame"]="拾取框架" L["Loss Control Icon"]="失去控制圖示" L["MA Frames"]="主助理框架" L["Micromenu"]="微型系統菜單" L["Minimap"]="小地圖" L["MT Frames"]="主坦克框架" L["Party Frames"]="隊伍框架" L["Pet Bar"]="寵物快捷列" L["Pet Frame"]="寵物框架" L["PetTarget Frame"]="寵物目標框架" L["Player Castbar"]="玩家施法條" L["Player Frame"]="玩家框架" L["Raid 1-"]="團隊 1-" L["Reputation Bar"]="聲望條" L["Right Dock"]="右側對話框" L["Stance Bar"]="姿態列" L["Target Castbar"]="目標施法條" L["Target Frame"]="目標框架" L["TargetTarget Frame"]="目標的目標框架" L["Tooltip"]="浮動提示" L["Totems"]="圖騰列" L["Vehicle Seat Frame"]="載具座位框" L["Watch Frame"]="任務追蹤框架" L["Weapons"]="武器(毒藥/強化等)" L["Discipline"]="戒律" L["Holy"]="神聖" L["Mistweaver"]='織霧' L["Restoration"]="恢復" L[" |cff00ff00bound to |r"]=" |cff00ff00綁定到 |r" L["%s frame(s) has a conflicting anchor point, please change either the buff or debuff anchor point so they are not attached to each other. Forcing the debuffs to be attached to the main unitframe until fixed."]=" %s 個框架錨點衝突, 請移動buff或者debuff錨點讓他們彼此不依附. 暫時強制debuff依附到主框架." L["All keybindings cleared for |cff00ff00%s|r."]="取消|cff00ff00%s|r 所有綁定的快捷​​鍵." L["Already Running.. Bailing Out!"]='正在運行' L["Battleground statistics temporarily hidden, to show type /bgstats."]='戰場資訊暫時隱藏, 你可以通過輸入/bgstats 或右鍵點擊小地圖旁「C」按鈕顯示.' L["Battleground statistics will now show again if you are inside a battleground."]="當你處於戰場時戰場資訊將再次顯示." L["Binds Discarded"]="取消綁定" L["Binds Saved"]="儲存綁定" L["Confused.. Try Again!"]='請再試一次!' L["Deleted %d gray items. Total Worth: %s"]="已刪除%d 個灰色物品. 總價值: %s" L["No gray items to delete."]="沒有可刪除的灰色物品." L["No gray items to sell."]="沒有可出售的灰色物品." L["The spell '%s' has been added to the BlackList unitframe aura filter."]='法術"%s"已經被添加到單位框架的光環過濾器中.' L["Vendored gray items for:"]="已售出灰色物品,共得:" L["You don't have enough money to repair."]="沒有足夠的資金來修復." L["You must be at a vendor."]="你必須與商人對話." L["Your items have been repaired for: "]="裝備已修復,共支出:" L["Your items have been repaired using guild bank funds for: "]="已使用公會資金修復裝備,共支出:" L["Your version of SVUI is out of date. You can download the latest version from http://www.wowinterface.com"]="SVUI 版本已過期, 請至http://www.wowinterface.com 下載最新版" L["|cFFE30000Lua error recieved. You can view the error message when you exit combat."]="|cFFE30000LUA錯誤已接收, 你可以在脫離戰鬥後檢查.|r" L["A setting you have changed will change an option for this character only. This setting that you have changed will be uneffected by changing user profiles. Changing this setting requires that you reload your User Interface."]="你所做的改動只會影響到使用這個插件的本角色, 你需要重新加載介面才能使改動生效." L["Are you sure you want to delete all your gray items?"]="是否確定要刪除所有灰色物品?" L["Are you sure you want to disband the group?"]="確定要解散隊伍?" L["Are you sure you want to reset every mover back to it's default position?"]="確定需要重置所有框架至默認位置?" L["Because of the mass confusion caused by the new aura system I've implemented a new step to the installation process. This is optional. If you like how your auras are setup go to the last step and click finished to not be prompted again. If for some reason you are prompted repeatedly please restart your game."]="由於大量的問題導致光環系統需要一個新的安裝過程. 這是可選的, 最後一步將設置你的光環. 點擊「完成」將不再提示. 如果由於某些原因反復提示, 請重新開啟遊戲." L["Can't buy anymore slots!"]="無法再購買更多銀行欄位!" L["Disable Warning"]='停用警告' L["Discard"]="取消" L["Do you swear not to post in technical support about something not working without first disabling the addon/package combination first?"]=true; L["Hover your mouse over any actionbutton or spellbook button to bind it. Press the escape key or right click to clear the current actionbutton's keybinding."]="移動滑鼠到快捷列或技能書按鈕上綁定快捷鍵.按ESC或滑鼠右鍵取消目前快捷鍵." L["I Swear"]='我承諾' L["Oh lord, you have got SVUI and Tukui both enable at the same time. Select an addon to disable."]="你不能同時啓用SVUI和Tukui, 請選擇一個禁用." L["One or more of the changes you have made require a ReloadUI."]="已變更一或多個設定, 需重載介面." L["One or more of the changes you have made will effect all characters using this addon. You will have to reload the user interface to see the changes you have made."]="你所做的改動可能會影響到使用這個插件的所有角色, 你需要重新加載介面才能使改動生效." L["Save"]="儲存" L["Using the healer layout it is highly recommended you download the addon Clique if you wish to have the click-to-heal function."]=true; L["You have changed the pixel perfect option. You will have to complete the installation process to remove any graphical bugs."]="你已改變了像素完美中的選項, 你必須完成安裝過程以消除任何圖形錯誤." L["You have changed your UIScale, however you still have the AutoScale option enable in SV. Press accept if you would like to disable the Auto Scale option."]="你改變了介面縮放比例, 然而SVUI的自動縮放選項是開啟的. 點擊接受以關閉SVUI的自動縮放." L["You must purchase a bank slot first!"]="你必需購買一個銀行背包欄位!" L["Count"]="計數" L["Targeted By:"]="同目標的有:" L["A raid marker feature is available by pressing Escape -> Keybinds scroll to the bottom under SVUI and setting a keybind for the raid marker."]="你可以通過按ESC鍵-> 按鍵設定, 滾動到SVUI設定下方設定一個快速標記的快捷鍵." L["SVUI has a dual spec feature which allows you to load different profiles based on your current spec on the fly. You can enable this from the profiles tab."]="SVUI可以根據你所使用的天賦自動套用不同的設定檔. 你可以在配置文件中使用此功能." L["For technical support visit us at http://www.wowinterface.com."]="如需技術支援請至http://www.wowinterface.com." L["If you accidently remove a chat frame you can always go the in-game configuration menu, press install, go to the chat portion and reset them."]="如果你不慎移除了對話框, 你可以重新安裝一次重置他們." L["If you are experiencing issues with SVUI try disabling all your addons except SVUI, remember SVUI is a full UI replacement addon, you cannot run two addons that do the same thing."]="如果你遇到問題, SVUI會嘗試禁用你除了SVUI之外的插件. 請記住你不能用不同的插件實現同一功能." L["The buff panel to the right of minimap is a list of your consolidated buffs. You can disable it in Buffs and Debuffs options of SV."]="小地圖右側的光環條是你的整合Buff條, 你可以在你的SVUI光環設定中關閉此功能." L["The focus unit can be set by typing /focus when you are targeting the unit you want to focus. It is recommended you make a macro to do this."]="你可以通過/focus 命令設定焦點目標." L["To move abilities on the actionbars by default hold shift + drag. You can change the modifier key from the actionbar options menu."]="你可以通過按住Shift拖動技能條中的按鍵. 你可以在Blizzard的快捷列設定中更改按鍵." L["To setup which channels appear in which chat frame, right click the chat tab and go to settings."]="你可以通過右鍵點擊對話框標籤欄設定你需要在對話框內顯示的頻道." L["Using the /farmmode <size> command will spawn a larger minimap on your screen that can be moved around, very useful when farming."]="使用/farmmode 命令可以切換小地圖的顯示模式為大型可移動小地圖, 這在你Farm的時候會很有用." L["You can access copy chat and chat menu functions by mouse over the top right corner of chat panel and left/right click on the button that will appear."]="你可以通過滑鼠滑過對話框右上角點擊複製圖示打開對話復制窗口." L["You can see someones average item level of their gear by holding shift and mousing over them. It should appear inside the tooltip."]="你可以通過按住Shift並將滑鼠滑過目標看到目標的裝備等級, 這將顯示在你的滑鼠提示框內." L["You can set your keybinds quickly by typing /kb."]="你可以通過輸入/kb 快速綁定按鍵." L["You can toggle the microbar by using your middle mouse button on the minimap you can also accomplish this by enabling the actual microbar located in the actionbar settings."]="你可以通過滑鼠中鍵點擊小地圖或在快捷列設定內選擇打開微型系統欄." L["You can use the /resetui command to reset all of your moveables. You can also use the command to reset a specific mover, /resetui <mover name>.\nExample: /resetui Player Frame"]="使用/resetui命令可以重置你的所有框架位置. 你也可以通過命令/resetui <框架名稱> 單獨重置某個框架.\n例如: /resetui Player Frame" L["Ghost"]="鬼魂" L["Offline"]="離線" L["ENH_LOGIN_MSG"]="您正在使用 |cff1784d1SVUI Enhanced|r version %s%s|r." L["Your version of SVUI is to old. Please, download the latest version from http://www.wowinterface.com."]="您的SVUI版本過低(需要 v6.51 或更高), 請前往http://www.wowinterface.com下載最新版本." L["Equipment"]="自動換裝" L["EQUIPMENT_DESC"]="當你切換專精或進入戰場時自動更換裝備, 你可以在選項中選擇相關的裝備模組." L["No Change"]="不改變" L["Specialization"]="專精" L["Enable/Disable the specialization switch."]="開啓/關閉 專精切換" L["Primary Talent"]="主專精" L["Choose the equipment set to use for your primary specialization."]="選擇當你使用主專精時的裝備模組." L["Secondary Talent"]="副專精" L["Choose the equipment set to use for your secondary specialization."]="選擇當你使用副專精時的裝備模組." L["Battleground"]="戰場" L["Enable/Disable the battleground switch."]="開啓/關閉 戰場切換" L["Equipment Set"]="裝備模組" L["Choose the equipment set to use when you enter a battleground or arena."]="選擇當你進入戰場時的裝備模組." L["You have equipped equipment set: "]="你已裝備此模組: " L["DURABILITY_DESC"]="調整設置人物窗口裝備耐久度顯示." L["Enable/Disable the display of durability information on the character screen."]="開啓/關閉 人物窗口裝備耐久度顯示." L["Damaged Only"]="受損顯示" L["Only show durabitlity information for items that are damaged."]="只在裝備受損時顯示耐久度." L["ITEMLEVEL_DESC"]="調整在角色資訊上顯示物品裝等的各種設定." L["Enable/Disable the display of item levels on the character screen."]="在角色資訊上顯示各裝備裝等" L["Miscellaneous"]="雜項" L["Equipment Set Overlay"]=true; L["Show the associated equipment sets for the items in your bags (or bank)."]="在你包包或銀行中顯示相關的套裝設定" L["Layout Transparency"]="定位器透明度" L["Changes the transparency of all the moveables."]="改變所有定位器的透明度" L["Automatic Role Assignment"]="自動設定角色定位" L["Enables the automatic role assignment based on specialization for party / raid members (only work when you are group leader or group assist)."]="當你是隊長或助理時根據隊員天賦自動指定其角色定位" L["Hide Role Icon in combat"]=true; L["All role icons (Damage/Healer/Tank) on the unit frames are hidden when you go into combat."]=true; L["GPS"]="GPS定位" L["Show the direction and distance to the selected party or raid member."]="顯示你與當前隊伍或團隊成員的方向与距離." L["Attack Icon"]="戰鬥標記" L["Show attack icon for units that are not tapped by you or your group, but still give kill credit when attacked."]="當目標不是被你或你的隊伍所開,但是可以取得任務道具,獎勵,道具時顯示一個戰鬥標記" L["Show class icon for units."]="顯是職業圖標" L["Above Minimap"]="小地圖之上" L["Location Digits"]="坐標位數" L["Number of digits for map location."]="坐標顯示的小數位數" L["Hide minimap while in combat."]="戰鬥中隱藏小地圖" L["FadeIn Delay"]="隱藏延遲" L["The time to wait before fading the minimap back in after combat hide. (0 = Disabled)"]="戰鬥開始後隱藏小地圖前的延遲時間 (0=停用)" L["Minimap Button Bar"]="小地圖按鈕整合列" L["Style Buttons"]="美化按鈕" L["Customize the minimap buttons in SVUI style."]="將小地圖圖標美化成SVUI風格." L["SVUI Style"]="美化風格" L["Change settings for how the minimap buttons are styled."]="改變美化設定." L["The size of the minimap buttons."]="小地圖圖標尺寸." L["No Anchor Bar"]="沒有錨點" L["Horizontal Anchor Bar"]="水平狀" L["Vertical Anchor Bar"]="垂直狀" L["Layout Direction"]=true; L["Normal is right to left or top to bottom, or select reversed to switch directions."]=true; L["Normal"]=true; L["Reversed"]=true; L["PvP Autorelease"]="PVP自動釋放靈魂" L["Automatically release body when killed inside a battleground."]="在戰場死亡後自動釋放靈魂." L["Track Reputation"]="聲望追蹤" L["Automatically change your watched faction on the reputation bar to the faction you got reputation points for."]="當你獲得某個陣營的聲望時, 將自動追蹤此陣營的聲望至經驗值欄位." L["Select Quest Reward"]="自動選取任務獎勵" L["Automatically select the quest reward with the highest vendor sell value."]="自動選取有最高賣價的任務獎勵物品" L["Item Level"]="物品等級" L["Target Range"]="目標距離" L["Distance"]="距離" L["Actionbar1DataPanel"]='快捷列 1 資訊框' L["Actionbar3DataPanel"]='快捷列 3 資訊框' L["Actionbar5DataPanel"]='快捷列 5 資訊框' L["Sunsong Ranch"]="日歌農莊" L["The Halfhill Market"]="半丘市集" L["Tilled Soil"]="開墾過的沃土" L["Right-click to drop the item."]="右鍵點擊需刪除的項目." L["Toolbox"]="農夫" L["Toolbox Portal Bar"]="農夫列:傳送" L["Toolbox Seed Bar"]="農夫列:種子" L["Toolbox Tools Bar"]="農夫列:工具" L["COMIX_DESC"]="Toggle the comic popups during combat" L["FARMING_MODE_DESC"]="調整設置以便你在日歌農莊更有效的耕作." L["SNACKS_DESC"]="" L["Toolbox Bars"]="農夫列" L["Enable/Disable the laborer bars."]="開啓/關閉 農夫快捷列." L["Only active buttons"]="只顯示有效的按鈕" L["Only show the buttons for the seeds, portals, tools you have in your bags."]="只顯示你背包中有的種子, 傳送和工具." L["Drop Tools"]="刪除工具" L["Automatically drop tools from your bags when leaving the farming area."]="當你離開農莊範圍時, 自動刪除背包中的工具." L["Seed Bar Direction"]="種子條方向" L["The direction of the seed bar buttons (Horizontal or Vertical)."]="種子條的方向 (水平或垂直)" L["Threat Text"]="威脅值文字" L["Display threat level as text on targeted, boss or mouseover nameplate."]="在首領或鼠標懸停的血條上顯示威脅等級文字." L["Target Count"]="目標記數" L["Display the number of party / raid members targetting the nameplate unit."]="在血調旁邊顯示隊伍/團隊成員中以其為目標的個數" L["Heal Glow"]="高亮治療" L["Direct AoE heals will let the unit frames of the affected party / raid members glow for the defined time period."]="受到直接性的範圍治療法術影響的隊伍/團隊成員會被高亮指定的時間" L["Glow Duration"]="高量持續時間" L["The amount of time the unit frames of party / raid members will glow when affected by a direct AoE heal."]="當隊伍/團隊成員受到直接性範圍治療法術石高亮持續的時間" L["Glow Color"]="高亮顏色" L["Raid Marker Bar"]="團隊標記列" L["Display a quick action bar for raid targets and world markers."]="顯示一個可以快速設定團隊標記與光柱的快捷列" L["Modifier Key"]="組合鍵" L["Set the modifier key for placing world markers."]="設定標示團隊光柱的組合鍵" L["Shift Key"]="Shift鍵" L["Ctrl Key"]="Ctrl鍵" L["Alt Key"]="Alt鍵" L["Raid Markers"]="團隊標記" L["Click to clear the mark."]="點選清除所有標記" L["Click to mark the target."]="點選以標記目標" L["%sClick to remove all worldmarkers."]="%s 清除了所有光柱" L["%sClick to place a worldmarker."]="%s 放置了一個光柱" L["WatchFrame"]="追蹤器" L["WATCHFRAME_DESC"]="Adjust the settings for the visibility of the watchframe (questlog) to your personal preference." L["Hidden"]="隱藏" L["Collapsed"]="收起" L["Settings"]="設定" L["City (Resting)"]="城市 (休息)" L["PvP"]=true; L["Arena"]="競技場" L["Party"]="隊伍" L["Raid"]="團隊" L["Progression Info"]=true; L["Display the players raid progression in the tooltip, this may not immediately update when mousing over a unit."]=true L["Artifact Power"]=true; L["Current Artifact Power:"]=true; L["Remaining:"]=true; L["Points to Spend:"]=true; L["No Artifact"]=true;
mit
inmation/library
mock/inmation.lua
1
1741
local standardLogic = {} function standardLogic.currenttime(localTimezone) if localTimezone then return os.time() else return os.time(os.date("!*t", os.time())) end end function standardLogic.gettime(time, format) if nil == format then format = "%Y-%m-%d %H:%M:%S" end if nil == time then error('bad argument #1 (string expected, got no value)') end if type(time) == 'number' then return os.date(format, time) else if type(time) == 'string' then assert(false, 'Not implemented') end end end function standardLogic.gettimeparts(time) local timeStr = standardLogic.gettime(time, "%Y-%m-%dT%H:%M:%S+01:00") local inYear, inMonth, inDay, inHour, inMinute, inSecond, inZone = string.match(timeStr, '^(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)(.-)$') return inYear, inMonth, inDay, inHour, inMinute, inSecond, inZone end function standardLogic.now() return standardLogic.currenttime() end function standardLogic.getself() return inmation end local overrides = {} inmation = {} setmetatable(inmation, {__index = function(_, name) print(name) -- First used overwritten implementation if nil ~= overrides[name] then return overrides[name] end -- Second use standard implementation if nil ~= standardLogic[name] then return standardLogic[name] end assert(nil, string.format("Method '%s' not implemented, make use of method 'inmation.setOverride(name, closure)' to add a custom implementation.", name)) end}) inmation.setOverride = function(name, closure) overrides[name] = closure end inmation.clearOverrides = function() overrides = {} end return inmation
mit
UnfortunateFruit/darkstar
scripts/zones/Port_Bastok/npcs/Hilda.lua
19
5047
----------------------------------- -- Area: Port Bastok -- NPC: Hilda -- Involved in Quest: Cid's Secret, Riding on the Clouds -- Starts & Finishes: The Usual -- @pos -163 -8 13 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:getGil() == 0 and trade:getItemCount() == 1) then if(trade:hasItemQty(4530,1) and player:getVar("CidsSecret_Event") == 1 and player:hasKeyItem(UNFINISHED_LETTER) == false) then -- Trade Rollanberry player:startEvent(0x0085); elseif(trade:hasItemQty(4386,1) and player:getQuestStatus(BASTOK,THE_USUAL) == QUEST_ACCEPTED) then -- Trade King Truffle player:startEvent(0x0087); end end if(player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 5) then if(trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_2",0); player:tradeComplete(); player:addKeyItem(SMILING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatBastok = player:getVar("WildcatBastok"); if(player:getCurrentMission(BASTOK) == ON_MY_WAY) and (player:getVar("MissionStatus") == 1) then player:startEvent(0x00ff); elseif (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,3) == false) then player:startEvent(0x0164); elseif(player:getQuestStatus(BASTOK,THE_USUAL) ~= QUEST_COMPLETED) then if(player:getQuestStatus(BASTOK,CID_S_SECRET) == QUEST_ACCEPTED) then player:startEvent(0x0084); if(player:getVar("CidsSecret_Event") ~= 1) then player:setVar("CidsSecret_Event",1); end elseif(player:getFameLevel(BASTOK) >= 5 and player:getQuestStatus(BASTOK,CID_S_SECRET) == QUEST_COMPLETED) then if(player:getVar("TheUsual_Event") == 1) then player:startEvent(0x0088); elseif(player:getQuestStatus(BASTOK,THE_USUAL) == QUEST_ACCEPTED) then player:startEvent(0x0031); --Hilda thanks the player for all the help; there is no reminder dialogue for this quest else player:startEvent(0x0086); end else player:startEvent(0x0030); --Standard dialogue if fame isn't high enough to start The Usual and Cid's Secret is not active end elseif(player:getQuestStatus(BASTOK,THE_USUAL) == QUEST_COMPLETED and player:getQuestStatus(BASTOK,CID_S_SECRET) == QUEST_COMPLETED) then player:startEvent(0x0031); --Hilda thanks the player for all the help else player:startEvent(0x0030); --Standard dialogue if no quests are active or available 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 == 0x0085) then player:tradeComplete(); player:addKeyItem(UNFINISHED_LETTER); player:messageSpecial(KEYITEM_OBTAINED,UNFINISHED_LETTER); elseif(csid == 0x0086 and option == 0) then if(player:getQuestStatus(BASTOK,THE_USUAL) == QUEST_AVAILABLE) then player:addQuest(BASTOK,THE_USUAL); end elseif(csid == 0x0087) then player:tradeComplete(); player:addKeyItem(STEAMING_SHEEP_INVITATION); player:messageSpecial(KEYITEM_OBTAINED,STEAMING_SHEEP_INVITATION); elseif(csid == 0x0088) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17170); else player:addTitle(STEAMING_SHEEP_REGULAR); player:delKeyItem(STEAMING_SHEEP_INVITATION); player:setVar("TheUsual_Event",0); player:addItem(17170); player:messageSpecial(ITEM_OBTAINED,17170); -- Speed Bow player:addFame(BASTOK,BAS_FAME*30); player:completeQuest(BASTOK,THE_USUAL); end elseif(csid == 0x00ff) then player:setVar("MissionStatus",2); elseif (csid == 0x0164) then player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",3,true); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Uleguerand_Range/Zone.lua
28
1983
----------------------------------- -- -- Zone: Uleguerand_Range (5) -- ----------------------------------- package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/Uleguerand_Range/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) -- Jormungand SetRespawnTime(16797969, 86400, 259200); 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(363.025,16,-60,12); end if (player:getCurrentMission(COP) == DAWN and player:getVar("COP_louverance_story")== 1 ) then cs=0x0011; 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); if (csid == 0x0011) then player:setVar("COP_louverance_story",2); end end;
gpl-3.0