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
lichtl/darkstar
scripts/zones/Maze_of_Shakhrami/npcs/Rockwell.lua
13
2288
----------------------------------- -- Area: Maze of Shakhrami -- Quest: Your Crystal Ball -- @pos -18 -13 181 198 ----------------------------------- package.loaded["scripts/zones/Maze_of_Shakhrami/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Maze_of_Shakhrami/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,YOUR_CRYSTAL_BALL) == QUEST_ACCEPTED and trade:hasItemQty(557,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then --no cs i think player:setVar("QuestYourCrystalBall_date", os.date("%j")); -- %M for next minute, %j for next day player:setVar("QuestYourCrystalBall_prog", 1); player:tradeComplete(trade); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day local starttime = player:getVar("QuestYourCrystalBall_date"); if (player:getQuestStatus(JEUNO,YOUR_CRYSTAL_BALL) == QUEST_ACCEPTED and player:getVar("QuestYourCrystalBall_prog") == 1 and starttime ~= realday) then player:startEvent(0x0034); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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 == 0x0034) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,556); else player:addItem(556); player:messageSpecial(ITEM_OBTAINED,556); player:setVar("QuestYourCrystalBall_date", 0); player:setVar("QuestYourCrystalBall_prog", 0); end end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Lower_Jeuno/TextIDs.lua
7
5193
-- 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 = 6384; -- Obtained: <item>. GIL_OBTAINED = 6385; -- Obtained <number> gil. KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>. NOT_HAVE_ENOUGH_GIL = 6391; -- You do not have enough gil. HOMEPOINT_SET = 6513; -- Home point set! FISHING_MESSAGE_OFFSET = 6915; -- You can't fish here. INVENTORY_INCREASED = 7773; -- Your inventory capacity has increased. ITS_LOCKED = 7578; -- It's locked. -- Other Texts ITEM_DELIVERY_DIALOG = 7774; -- Now offering quick and easy delivery of packages to residences everywhere! GUIDE_STONE = 7131; -- Up: Upper Jeuno (Selection Dialogfacing San d'Oria) Down: Port Jeuno (Selection Dialogfacing Windurst) STREETLAMP_EXAMINE = 7245; -- You examine the lamp. It seems that it must be lit manually. PARIKE_PORANKE_DIALOG = 8945; -- All these people running back and forth... There have to be a few that have munched down more mithkabobs than they can manage. WAYPOINT_EXAMINE = 10336; -- An enigmatic contrivance hovers in silence... NO_KEY = 9897; -- You do not have a usable key in your possession. ALDO_DIALOG = 7136; -- Hi. I'm Aldo, head of Tenshodo. We deal in things you can't buy anywhere else. Take your time and have a look around. CHOCOBO_DIALOG = 7310; -- Hmph. PARIKE_PORANKE_1 = 8946; -- Hey you! Belly bursting? Intestines inflating? Bladder bulging? I can tell by the notch on your belt that you've been overindulging yourself in culinary delights. PARIKE_PORANKE_2 = 8949; -- I mean, this is a new era. If somebody wants to go around with their flabby-flubber hanging out of their cloaks, they should have every right to do so. If someone wants to walk around town with breath reeking of Kazham pines and roasted sleepshrooms, who am I to stop them PARIKE_PORANKE_3 = 8950; -- What? You want me to tend to your tummy trouble? No problem! And don't worry, this won't hurt at all! I'm only going to be flushing your bowels with thousands of tiny lightning bolts. It's all perfectly safe! PARIKE_PORANKE_4 = 8951; -- Now stand still! You wouldn't want your pelvis to implode, would you? (Let's see... What were those magic words again...?) PARIKE_PORANKE_5 = 8952; -- Ready? No? Well, too bad! PARIKE_PORANKE_6 = 8960; -- digestive magic skill rises 0.1 points. PARIKE_PORANKE_7 = 8961; -- digestive magic skill rises one level. PARIKE_PORANKE_8 = 8962; -- Heh heh! I think I'm starting to get the hang of this spellcasting. PARIKE_PORANKE_9 = 8963; -- Consider this a petite present from your pal Parike-Poranke! PARIKE_PORANKE_10 = 8967; -- Wait a minute... Don't tell me you came to Parike-Poranke on an empty stomach! This is terrible! The minister will have my head! PARIKE_PORANKE_12 = 8969; -- Phew! That was close... What were you thinking, crazy adventurer! PARIKE_PORANKE_13 = 8972; -- Speaker Name's ll in the name of scienceskill rises 0.1 points. PARIKE_PORANKE_14 = 8973; -- Speaker Name's ll in the name of scienceskill rises one level. PARIKE_PORANKE_15 = 8974; -- You know, I've learned a lot from my mist--er, I mean, less-than-successful attempts at weight-loss consulting. PARIKE_PORANKE_16 = 8975; -- To show you my gratitude, let me try out this new spell I thought up yesterday while I was taking a nap! MERTAIRE_DIALOG = 7416; -- Who are you? Leave me alone! -- Conquest system CONQUEST = 8047; -- You've earned conquest points! -- Shop Texts CREEPSTIX_SHOP_DIALOG = 7122; -- Hey, how ya doin'? We got the best junk in town. STINKNIX_SHOP_DIALOG = 7122; -- Hey, how ya doin'? We got the best junk in town. HASIM_SHOP_DIALOG = 7123; -- Welcome to Waag-Deeg's Magic Shop. TAZA_SHOP_DIALOG = 7123; -- Welcome to Waag-Deeg's Magic Shop. SUSU_SHOP_DIALOG = 7123; -- Welcome to Waag-Deeg's Magic Shop. CHETAK_SHOP_DIALOG = 7124; -- Welcome to Othon's Garments. CHENOKIH_SHOP_DIALOG = 7124; -- Welcome to Othon's Garments. YOSKOLO_SHOP_DIALOG = 7125; -- Welcome to the Merry Minstrel's Meadhouse. What'll it be? ADELFLETE_SHOP_DIALOG = 7126; -- Here at Gems by Kshama, we aim to please. MOREFIE_SHOP_DIALOG = 7126; -- Here at Gems by Kshama, we aim to please. MATOAKA_SHOP_DIALOG = 7126; -- Here at Gems by Kshama, we aim to please. RHIMONNE_SHOP_DIALOG = 7129; -- Howdy! Thanks for visiting the Chocobo Shop! PAWKRIX_SHOP_DIALOG = 7626; -- Hey, we're fixin' up some stew. Gobbie food's good food! AMALASANDA_SHOP_DIALOG = 7674; -- Welcome to the Tenshodo. You want something, we got it. We got all kinds of special merchandise you won't find anywhere else! AKAMAFULA_SHOP_DIALOG = 7675; -- We ain't cheap, but you get what you pay for! Take your time, have a look around, see if there's somethin' you like. -- conquest Base CONQUEST_BASE = 6538; -- Tallying conquest results... -- Porter Moogle RETRIEVE_DIALOG_ID = 10177; -- You retrieve$ from the porter moogle's care.
gpl-3.0
lichtl/darkstar
scripts/zones/Windurst_Waters/npcs/Maysoon.lua
25
2162
----------------------------------- -- Area: Windurst Waters -- NPC: Maysoon -- Starts and Finishes Quest: Hoist the Jelly, Roger -- Involved in Quests: Cook's Pride -- @zone 238 -- @pos -105 -2 69 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(WINDURST,HOIST_THE_JELLY_ROGER) == QUEST_ACCEPTED) then if (trade:hasItemQty(4508,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(0x2711); -- Finish quest "Hoist the Jelly, Roger" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) CooksPride = player:getQuestStatus(JEUNO,COOK_S_PRIDE); HoistTheJelly = player:getQuestStatus(WINDURST,HOIST_THE_JELLY_ROGER); if (CooksPride == QUEST_ACCEPTED and HoistTheJelly == QUEST_AVAILABLE) then player:startEvent(0x2710); -- Start quest "Hoist the Jelly, Roger" else player:startEvent(0x010a); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x2710) then player:addQuest(WINDURST,HOIST_THE_JELLY_ROGER); elseif (csid == 0x2711) then player:completeQuest(WINDURST,HOIST_THE_JELLY_ROGER); player:addKeyItem(SUPER_SOUP_POT); player:messageSpecial(KEYITEM_OBTAINED,SUPER_SOUP_POT); player:addFame(WINDURST,30); player:tradeComplete(); end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/mobskills/tail_swing.lua
11
1029
--------------------------------------------- -- Tail Swing -- -- Description: Deals damage to a single target. Additional effect: Bind -- Type: Physical -- Utsusemi/Blink absorb: 1 shadow -- Range: Melee -- Notes: --------------------------------------------- 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.4 local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,info.hitslanded) local typeEffect = dsp.effect.BIND MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 30) target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING) return dmg end
gpl-3.0
OctoEnigma/shiny-octo-system
gamemodes/terrortown/entities/weapons/weapon_ttt_defuser.lua
2
2406
AddCSLuaFile() SWEP.HoldType = "slam" if CLIENT then SWEP.PrintName = "defuser_name" SWEP.Slot = 7 SWEP.DrawCrosshair = false SWEP.ViewModelFOV = 10 SWEP.EquipMenuData = { type = "item_weapon", desc = "defuser_desc" }; SWEP.Icon = "vgui/ttt/icon_defuser" end SWEP.Base = "weapon_tttbase" SWEP.ViewModel = "models/weapons/v_crowbar.mdl" SWEP.WorldModel = "models/weapons/w_defuser.mdl" SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = -1 SWEP.Primary.Automatic = true SWEP.Primary.Delay = 1 SWEP.Primary.Ammo = "none" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = true SWEP.Secondary.Ammo = "none" SWEP.Secondary.Delay = 2 SWEP.Kind = WEAPON_EQUIP2 SWEP.CanBuy = {ROLE_DETECTIVE} -- only detectives can buy SWEP.WeaponID = AMMO_DEFUSER --SWEP.AllowDrop = false local defuse = Sound("c4.disarmfinish") function SWEP:PrimaryAttack() self:SetNextPrimaryFire( CurTime() + self.Primary.Delay ) local spos = self.Owner:GetShootPos() local sdest = spos + (self.Owner:GetAimVector() * 80) local tr = util.TraceLine({start=spos, endpos=sdest, filter=self.Owner, mask=MASK_SHOT}) if IsValid(tr.Entity) and tr.Entity.Defusable then local bomb = tr.Entity if bomb.Defusable==true or bomb:Defusable() then if SERVER and bomb.Disarm then bomb:Disarm(self.Owner) sound.Play(defuse, bomb:GetPos()) end self:SetNextPrimaryFire( CurTime() + (self.Primary.Delay * 2) ) end end end function SWEP:SecondaryAttack() self:SetNextPrimaryFire( CurTime() + self.Primary.Delay ) self:SetNextSecondaryFire( CurTime() + 0.1 ) end if CLIENT then function SWEP:Initialize() self:AddHUDHelp("defuser_help", nil, true) return self.BaseClass.Initialize(self) end function SWEP:DrawWorldModel() if not IsValid(self.Owner) then self:DrawModel() end end end function SWEP:Reload() return false end function SWEP:Deploy() if SERVER and IsValid(self.Owner) then self.Owner:DrawViewModel(false) end return true end function SWEP:OnDrop() end
mit
lichtl/darkstar
scripts/zones/Lower_Delkfutts_Tower/npcs/_540.lua
14
2241
----------------------------------- -- Area: Lower Delkfutt's Tower -- NPC: Cermet Door -- Cermet Door for Windy Ambassador -- Windurst Mission 3.3 "A New Journey" -- @pos 636 16 59 184 ----------------------------------- package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Lower_Delkfutts_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getCurrentMission(WINDURST) == A_NEW_JOURNEY and player:getVar("MissionStatus") == 2) then if (trade:hasItemQty(549,1) and trade:getItemCount() == 1) then -- Trade Delkfutt Key player:startEvent(0x0002); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentMission = player:getCurrentMission(WINDURST); if (currentMission == A_NEW_JOURNEY and player:getVar("MissionStatus") == 2 and player:hasKeyItem(DELKFUTT_KEY) == false) then player:messageSpecial(THE_DOOR_IS_FIRMLY_SHUT_OPEN_KEY); elseif (currentMission == A_NEW_JOURNEY and player:getVar("MissionStatus") == 2 and player:hasKeyItem(DELKFUTT_KEY)) then player:startEvent(0x0002); else player:messageSpecial(DOOR_FIRMLY_SHUT); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); if (csid == 0x0002) then if (player:hasKeyItem(DELKFUTT_KEY) == false) then player:tradeComplete(); player:addKeyItem(DELKFUTT_KEY); player:messageSpecial(KEYITEM_OBTAINED,DELKFUTT_KEY); end player:setVar("MissionStatus",3); end end;
gpl-3.0
PrimaStudios/ProjectPrima
src/libs/SUIT-master/imagebutton.lua
8
1338
-- This file is part of SUIT, copyright (c) 2016 Matthias Richter local BASE = (...):match('(.-)[^%.]+$') return function(core, normal, ...) local opt, x,y = core.getOptionsAndSize(...) opt.normal = normal or opt.normal or opt[1] opt.hovered = opt.hovered or opt[2] or opt.normal opt.active = opt.active or opt[3] or opt.hovered assert(opt.normal, "Need at least `normal' state image") opt.id = opt.id or opt.normal opt.state = core:registerMouseHit(opt.id, x,y, function(u,v) local id = opt.normal:getData() assert(id:typeOf("ImageData"), "Can only use uncompressed images") u, v = math.floor(u+.5), math.floor(v+.5) if u < 0 or u >= opt.normal:getWidth() or v < 0 or v >= opt.normal:getHeight() then return false end local _,_,_,a = id:getPixel(u,v) return a > 0 end) local img = opt.normal if core:isActive(opt.id) then img = opt.active elseif core:isHovered(opt.id) then img = opt.hovered end core:registerDraw(opt.draw or function(img,x,y, r,g,b,a) love.graphics.setColor(r,g,b,a) love.graphics.draw(img,x,y) end, img, x,y, love.graphics.getColor()) return { id = opt.id, hit = core:mouseReleasedOn(opt.id), hovered = core:isHovered(opt.id), entered = core:isHovered(opt.id) and not core:wasHovered(opt.id), left = not core:isHovered(opt.id) and core:wasHovered(opt.id) } end
apache-2.0
stanxii/indexRiver
lua/bbs_main.lua
1
2501
local ickey_passwd="C=299792.458" --我方密钥 local ip=ngx.var.remote_addr --客户端IP local real_ip = ngx.req.get_headers()["x_forwarded_for"] if real_ip ~= nil then for astr in string.gfind(real_ip, "%d+%.%d+%.%d+%.%d+") do if string.find(astr,"10%.")==nil then --10 if string.find(astr,"172%.16")==nil then --172.16 if string.find(astr,"192%.168")==nil then --192.168 real_ip = astr break end end end end end if real_ip == nil then real_ip = ngx.req.get_headers()["http_cdn_src_ip"] end if real_ip == nil then real_ip = ngx.req.get_headers()["http_client_ip"] end if real_ip ~= nil then ip = real_ip end local bbscheck_time = ngx.var.cookie_seach --COOKIE值:客户端校验出错次数 if(bbscheck_time == nil) then bbscheck_time = 0 else bbscheck_time=tonumber(bbscheck_time) or 0 end local bbrnd = ngx.var.cookie_bbrnd --COOKIE值:客户端随机数 if(bbrnd == nil) then bbrnd = os.time() .. "_".. os.clock() --客户端随机数=当前时间int值_2位小数的秒值 end local user_mark = ip .. "|" .. bbrnd .. "|" .. ickey_passwd --客户端唯一标识明文 local token = ngx.md5(user_mark) --客户端唯一标识实时计算值 local bbut= ngx.var.cookie_bbut --COOKIE值:客户端唯一标识MD5加密值 local need_redirect=0 if(bbut == nil) then --没有客户端唯一标识MD5加密值 need_redirect=1 else if (bbut~= token) then --客户端唯一标识MD5加密值 与 实时计算值 不一样 bbscheck_time = bbscheck_time+1 need_redirect=1 end end local req_args="" if(ngx.var.args ~= nil) then req_args=ngx.var.args end if(need_redirect == 1) then --写入cookie ngx.header["Set-Cookie"] = {"bbut=" .. token .. ";domain=.ickey.cn;path=/;expires=31 Dec 2099 23:55:55 GMT;", "bbrnd=" .. bbrnd .. ";domain=.ickey.cn;path=/;expires=31 Dec 2099 23:55:55 GMT;", "bbtime=" .. bbscheck_time .. ";domain=.ickey.cn;path=/;expires=31 Dec 2099 23:55:55 GMT;"} local final_url=ngx.var.scheme .. "://" .. ngx.var.host .. ngx.var.uri .. "?" .. req_args .. "&__tm=" .. bbrnd return ngx.redirect(final_url) else --ngx.say("bbrnd=" .. bbrnd .. " ip=" .. ip .. " bbut=" .. bbut .. " token=" .. token .. " ngx.var.uri=" ..ngx.var.uri) ngx.req.set_uri_args(req_args .. "&ip=" .. ip .. "&user_mark=" .. user_mark) end
apache-2.0
lichtl/darkstar
scripts/zones/La_Theine_Plateau/npcs/Laurisse.lua
14
1795
----------------------------------- -- Area: La Theine Plateau -- NPC: Laurisse -- Involved in Mission: The Rescue Drill -- @pos -292 28 143 102 ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/La_Theine_Plateau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(SANDORIA) == THE_RESCUE_DRILL) then local MissionStatus = player:getVar("MissionStatus"); if (MissionStatus == 5) then player:startEvent(0x006a); elseif (MissionStatus >= 6 and MissionStatus <= 7) then player:startEvent(0x006d); elseif (MissionStatus == 8) then player:showText(npc, RESCUE_DRILL + 21); elseif (MissionStatus >= 9) then player:showText(npc, RESCUE_DRILL + 26); else player:showText(npc, RESCUE_DRILL); end else player:showText(npc, RESCUE_DRILL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x006a) then player:setVar("MissionStatus",6); end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Sacrarium/npcs/qm7.lua
9
1607
----------------------------------- -- Area: Sacrarium -- NPC: qm7 (???) -- Notes: Used to spawn Old Prof. Mariselle -- !pos 22.669 -3.111 -127.318 28 ----------------------------------- local ID = require("scripts/zones/Sacrarium/IDs"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); function onTrade(player,npc,trade) end; function onTrigger(player,npc) local cop = player:getCurrentMission(COP); local copStat = player:getCharVar("PromathiaStatus"); local prof = GetMobByID(ID.mob.OLD_PROFESSOR_MARISELLE); local profLoc = GetServerVariable("Old_Prof_Spawn_Location"); if (cop == dsp.mission.id.cop.THE_SECRETS_OF_WORSHIP and copStat == 3 and not player:hasKeyItem(dsp.ki.RELIQUIARIUM_KEY) and not prof:isSpawned() and profLoc == 7) then player:messageSpecial(ID.text.EVIL_PRESENCE); SpawnMob(ID.mob.OLD_PROFESSOR_MARISELLE):updateClaim(player); prof:setPos(npc:getXPos()+1, npc:getYPos(), npc:getZPos()+1); -- Set Prof. spawn x and z pos. +1 from NPC elseif (cop == dsp.mission.id.cop.THE_SECRETS_OF_WORSHIP and copStat == 4 and not player:hasKeyItem(dsp.ki.RELIQUIARIUM_KEY)) then player:addKeyItem(dsp.ki.RELIQUIARIUM_KEY); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.RELIQUIARIUM_KEY); elseif (profLoc == 7) then player:messageSpecial(ID.text.DRAWER_SHUT); else player:messageSpecial(ID.text.DRAWER_OPEN); player:messageSpecial(ID.text.DRAWER_EMPTY); end end; function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end;
gpl-3.0
lichtl/darkstar
scripts/zones/Beadeaux/npcs/Haggleblix.lua
14
7234
----------------------------------- -- Area: Beadeaux -- NPC: Haggleblix -- Type: Dynamis NPC -- @pos -255.847 0.595 106.485 147 ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/dynamis"); require("scripts/zones/Beadeaux/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); local buying = false; local exchange; local gil = trade:getGil(); if (player:hasKeyItem(VIAL_OF_SHROUDED_SAND)) then if (count == 1 and gil == TIMELESS_HOURGLASS_COST) then -- Hourglass purchase player:startEvent(134); elseif (gil == 0) then if (count == 1 and trade:hasItemQty(4236,1)) then -- Bringing back a Timeless Hourglass player:startEvent(153); -- Currency Exchanges elseif (count == CURRENCY_EXCHANGE_RATE and trade:hasItemQty(1455,CURRENCY_EXCHANGE_RATE)) then -- Single -> Hundred player:startEvent(135,CURRENCY_EXCHANGE_RATE); elseif (count == CURRENCY_EXCHANGE_RATE and trade:hasItemQty(1456,CURRENCY_EXCHANGE_RATE)) then -- Hundred -> Ten thousand player:startEvent(136,CURRENCY_EXCHANGE_RATE); elseif (count == 1 and trade:hasItemQty(1457,1)) then -- Ten thousand -> 100 Hundreds player:startEvent(138,1457,1456,CURRENCY_EXCHANGE_RATE); -- Currency Shop elseif (count == 12 and trade:hasItemQty(1456,12)) then -- Cantarella (4246) buying = true; exchange = {12, 4246}; elseif (count == 33 and trade:hasItemQty(1456,33)) then -- Koh-I-Noor (1460) buying = true; exchange = {33,1460}; elseif (count == 20 and trade:hasItemQty(1456,20)) then -- Marksman's Oil (1468) buying = true; exchange = {20, 1468}; elseif (count == 7 and trade:hasItemQty(1456,7)) then -- Siren's Hair (1313) buying = true; exchange = {7, 1313}; elseif (count == 8 and trade:hasItemQty(1456,8)) then -- Slime Juice (1521) buying = true; exchange = {8,1521}; elseif (count == 25 and trade:hasItemQty(1456,25)) then -- Wootz Ingot (1461) buying = true; exchange = {25, 1461}; elseif (count == 9 and trade:hasItemQty(1456,9)) then -- Wootz Ore (1469) buying = true; exchange = {9, 1469}; end end end -- Handle the shop trades. -- Item obtained dialog appears before CS. Could be fixed with a non-local variable and onEventFinish, but meh. if (buying == true) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,exchange[2]); else player:startEvent(137,1456,exchange[1],exchange[2]); player:tradeComplete(); player:addItem(exchange[2]); player:messageSpecial(ITEM_OBTAINED,exchange[2]); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(VIAL_OF_SHROUDED_SAND) == true) then player:startEvent(133, 1455, CURRENCY_EXCHANGE_RATE, 1456, CURRENCY_EXCHANGE_RATE, 1457, TIMELESS_HOURGLASS_COST, 4236, TIMELESS_HOURGLASS_COST); else player:startEvent(130); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 133) then if (option == 11) then -- Main menu, and many others. Param1 = map bitmask, param2 = player's gil player:updateEvent(getDynamisMapList(player), player:getGil()); elseif (option == 10) then -- Final line of the ancient currency explanation. "I'll trade you param3 param2s for a param1." player:updateEvent(1457, 1456, CURRENCY_EXCHANGE_RATE); -- Map sales handling. elseif (option >= MAP_OF_DYNAMIS_SANDORIA and option <= MAP_OF_DYNAMIS_TAVNAZIA) then -- The returned option is actually the keyitem ID, making this much easier. -- The prices are set in the menu's dialog, so they cannot be (visibly) changed. if (option == MAP_OF_DYNAMIS_BEAUCEDINE) then -- 15k gil player:delGil(15000); elseif (option == MAP_OF_DYNAMIS_XARCABARD or option == MAP_OF_DYNAMIS_TAVNAZIA) then -- 20k gil player:delGil(20000); else -- All others 10k player:delGil(10000); end player:addKeyItem(option); player:updateEvent(getDynamisMapList(player),player:getGil()); -- Ancient Currency shop menu elseif (option == 2) then -- Hundreds sales menu Page 1 (price1 item1 price2 item2 price3 item3 price4 item4) player:updateEvent(12,4246,33,1460,20,1468,7,1313); elseif (option == 3) then -- Hundreds sales menu Page 2 (price1 item1 price2 item2 price3 item3) player:updateEvent(8,1521,25,1461,9,1469); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 134) then -- Buying an Hourglass if (player:getFreeSlotsCount() == 0 or player:hasItem(4236) == true) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4236); else player:tradeComplete(); player:addItem(4236); player:messageSpecial(ITEM_OBTAINED,4236); end elseif (csid == 153) then -- Bringing back an hourglass for gil. player:tradeComplete(); player:addGil(TIMELESS_HOURGLASS_COST); player:messageSpecial(GIL_OBTAINED,TIMELESS_HOURGLASS_COST); elseif (csid == 135) then -- Trading Singles for a Hundred if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1456); else player:tradeComplete(); player:addItem(1456); player:messageSpecial(ITEM_OBTAINED,1456); end elseif (csid == 136) then -- Trading 100 Hundreds for Ten thousand if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1457); else player:tradeComplete(); player:addItem(1457); player:messageSpecial(ITEM_OBTAINED,1457); end elseif (csid == 138) then -- Trading Ten thousand for 100 Hundreds if (player:getFreeSlotsCount() <= 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1456); else player:tradeComplete(); player:addItem(1456,CURRENCY_EXCHANGE_RATE); if (CURRENCY_EXCHANGE_RATE >= 100) then -- Turns out addItem cannot add > stackSize, so we need to addItem twice for quantities > 99. player:addItem(1456,CURRENCY_EXCHANGE_RATE - 99); end player:messageSpecial(ITEMS_OBTAINED,1456,CURRENCY_EXCHANGE_RATE); end end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Porter_Moogle.lua
14
1546
----------------------------------- -- Area: Tavnazian_Safehold -- NPC: Porter Moogle -- Type: Storage Moogle -- @zone 26 -- @pos TODO ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Tavnazian_Safehold/TextIDs"); require("scripts/globals/porter_moogle_util"); local e = { TALK_EVENT_ID = 619, STORE_EVENT_ID = 620, RETRIEVE_EVENT_ID = 621, ALREADY_STORED_ID = 622, MAGIAN_TRIAL_ID = 623 }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) porterMoogleTrade(player, trade, e); end ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- No idea what the params are, other than event ID and gil. player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8); end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED); end ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL); end
gpl-3.0
OctoEnigma/shiny-octo-system
gamemodes/darkrp/gamemode/modules/base/sh_interface.lua
7
40603
DarkRP.registerDarkRPVar = DarkRP.stub{ name = "registerDarkRPVar", description = "Register a DarkRPVar by name. You should definitely register DarkRPVars. Registering DarkRPVars will make networking much more efficient.", parameters = { { name = "name", description = "The name of the DarkRPVar.", type = "string", optional = false }, { name = "writeFn", description = "The function that writes a value for this DarkRPVar. Examples: net.WriteString, function(val) net.WriteUInt(val, 8) end.", type = "function", optional = false }, { name = "readFn", description = "The function that reads and returns a value for this DarkRPVar. Examples: net.ReadString, function() return net.ReadUInt(8) end.", type = "function", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.writeNetDarkRPVar = DarkRP.stub{ name = "writeNetDarkRPVar", description = "Internal function. You probably shouldn't need this. DarkRP calls this function when sending DarkRPVar net messages. This function writes the net data for a specific DarkRPVar.", parameters = { { name = "name", description = "The name of the DarkRPVar.", type = "string", optional = false }, { name = "value", description = "The value of the DarkRPVar.", type = "any", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.writeNetDarkRPVarRemoval = DarkRP.stub{ name = "writeNetDarkRPVarRemoval", description = "Internal function. You probably shouldn't need this. DarkRP calls this function when sending DarkRPVar net messages. This function sets a DarkRPVar to nil.", parameters = { { name = "name", description = "The name of the DarkRPVar.", type = "string", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.readNetDarkRPVar = DarkRP.stub{ name = "readNetDarkRPVar", description = "Internal function. You probably shouldn't need this. DarkRP calls this function when reading DarkRPVar net messages. This function reads the net data for a specific DarkRPVar.", parameters = { }, returns = { { name = "name", description = "The name of the DarkRPVar.", type = "string" }, { name = "value", description = "The value of the DarkRPVar.", type = "any" } }, metatable = DarkRP } DarkRP.readNetDarkRPVarRemoval = DarkRP.stub{ name = "readNetDarkRPVarRemoval", description = "Internal function. You probably shouldn't need this. DarkRP calls this function when reading DarkRPVar net messages. This function the removal of a DarkRPVar.", parameters = { }, returns = { { name = "name", description = "The name of the DarkRPVar.", type = "string" } }, metatable = DarkRP } DarkRP.findPlayer = DarkRP.stub{ name = "findPlayer", description = "Find a single player based on vague information.", parameters = { { name = "info", description = "The information of the player (UserID, SteamID, name).", type = "string", optional = false } }, returns = { { name = "found", description = "The player that matches the description.", type = "Player" } }, metatable = DarkRP } DarkRP.findPlayers = DarkRP.stub{ name = "findPlayers", description = "Find a list of players based on vague information.", parameters = { { name = "info", description = "The information of the player (UserID, SteamID, name).", type = "string", optional = false } }, returns = { { name = "found", description = "Table of players that match the description.", type = "table" } }, metatable = DarkRP } DarkRP.nickSortedPlayers = DarkRP.stub{ name = "nickSortedPlayers", description = "A table of players sorted by RP name.", parameters = {}, returns = { { name = "players", description = "The list of players sorted by RP name.", type = "table" } }, metatable = DarkRP } DarkRP.explodeArg = DarkRP.stub{ name = "explodeArg", description = "String arguments exploded into a table. It accounts for substrings in quotes, which makes it more intelligent than string.Explode", parameters = { { name = "arg", description = "The full string of the argument", type = "string", optional = false }, }, returns = { { name = "args", description = "The table of arguments", type = "table" } }, metatable = DarkRP } DarkRP.formatMoney = DarkRP.stub{ name = "formatMoney", description = "Format a number as a money value. Includes currency symbol.", parameters = { { name = "amount", description = "The money to format, e.g. 100000.", type = "number", optional = false } }, returns = { { name = "money", description = "The money as a nice string, e.g. \"$100,000\".", type = "string" } }, metatable = DarkRP } DarkRP.getJobByCommand = DarkRP.stub{ name = "getJobByCommand", description = "Get the job table and number from the command of the job.", parameters = { { name = "command", description = "The command of the job, without preceding slash (e.g. 'medic' for medic)", type = "string", optional = false } }, returns = { { name = "tbl", description = "A table containing all information about the job.", type = "table" }, { name = "jobindex", description = "The index of the job (for 'medic' it's the value of TEAM_MEDIC).", type = "number" } }, metatable = DarkRP } DarkRP.simplerrRun = DarkRP.stub{ name = "simplerrRun", description = "Run a function with the given parameters and send any runtime errors to admins.", parameters = { { name = "f", description = "The function to be called.", type = "function", optional = false }, { name = "args", description = "The arguments to be given to f.", type = "vararg", optional = true }, }, returns = { { name = "retVals", description = "The return values of f.", type = "vararg" } }, metatable = DarkRP } DarkRP.error = DarkRP.stub{ name = "error", description = "Throw a simplerr formatted error. Also halts the stack, which means that statements after calling this function will not execute.", parameters = { { name = "message", description = "The message of the error.", type = "string", optional = false }, { name = "stack", description = "From which point in the function call stack to report the error. 1 to include the function that called DarkRP.error, 2 to exclude it, etc. The default value is 1.", type = "number", optional = true }, { name = "hints", description = "Table containing hint strings. Use these hints to explain the error, describe possible causes or provide help to solve the problem.", type = "table", optional = true }, { name = "path", description = "Override the path of the error. Will be shown in the error message. By default this is determined by the stack level.", type = "string", optional = true }, { name = "line", description = "Override the line number of the error. By default this is determined by the stack level.", type = "number", optional = true }, }, returns = { { name = "succeed", description = "Simplerr return value: whether the calculation succeeded. Always false. This return value will never be reached.", type = "boolean" }, { name = "msg", description = "Simplerr return value: nicely formatted error message. This return value will never be reached.", type = "string" } }, metatable = DarkRP } DarkRP.errorNoHalt = DarkRP.stub{ name = "errorNoHalt", description = "Throw a simplerr formatted error. Unlike DarkRP.error, this does not halt the stack. This means that statements after calling this function will be executed like normal.", parameters = { { name = "message", description = "The message of the error.", type = "string", optional = false }, { name = "stack", description = "From which point in the function call stack to report the error. 1 to include the function that called DarkRP.error, 2 to exclude it, etc. The default value is 1.", type = "number", optional = true }, { name = "hints", description = "Table containing hint strings. Use these hints to explain the error, describe possible causes or provide help to solve the problem.", type = "table", optional = true }, { name = "path", description = "Override the path of the error. Will be shown in the error message. By default this is determined by the stack level.", type = "string", optional = true }, { name = "line", description = "Override the line number of the error. By default this is determined by the stack level.", type = "number", optional = true }, }, returns = { { name = "succeed", description = "Simplerr return value: whether the calculation succeeded. Always false.", type = "boolean" }, { name = "msg", description = "Simplerr return value: nicely formatted error message.", type = "string" } }, metatable = DarkRP } -- This function is one of the few that's already defined before the stub is created DarkRP.stub{ name = "SteamName", description = "Retrieve a player's real (steam) name.", parameters = { }, returns = { { name = "name", description = "The player's steam name.", type = "string" } }, metatable = DarkRP.PLAYER } DarkRP.PLAYER.getJobTable = DarkRP.stub{ name = "getJobTable", description = "Get the job table of a player.", parameters = { }, returns = { { name = "job", description = "Table with the job information.", type = "table" } }, metatable = DarkRP.PLAYER } DarkRP.PLAYER.getDarkRPVar = DarkRP.stub{ name = "getDarkRPVar", description = "Get the value of a DarkRPVar, which is shared between server and client.", parameters = { { name = "var", description = "The name of the variable.", type = "string", optional = false } }, returns = { { name = "value", description = "The value of the DarkRP var.", type = "any" } }, metatable = DarkRP.PLAYER } DarkRP.PLAYER.getAgenda = DarkRP.stub{ name = "getAgenda", description = "Get the agenda a player manages.", deprecated = "Use ply:getAgendaTable() instead.", parameters = { }, returns = { { name = "agenda", description = "The agenda.", type = "table" } }, metatable = DarkRP.PLAYER } DarkRP.PLAYER.getAgendaTable = DarkRP.stub{ name = "getAgendaTable", description = "Get the agenda a player can see. Note: when a player is not the manager of an agenda, it returns the agenda of the manager.", parameters = { }, returns = { { name = "agenda", description = "The agenda.", type = "table" } }, metatable = DarkRP.PLAYER } DarkRP.PLAYER.hasDarkRPPrivilege = DarkRP.stub{ name = "hasDarkRPPrivilege", description = "Whether the player has a certain privilege.", parameters = { { name = "priv", description = "The name of the privilege.", type = "string", optional = false } }, returns = { { name = "answer", description = "Whether the player has the privilege.", type = "boolean" } }, metatable = DarkRP.PLAYER } DarkRP.PLAYER.getEyeSightHitEntity = DarkRP.stub{ name = "getEyeSightHitEntity", description = "Get the entity that is closest to a player's line of sight and its distance.", parameters = { { name = "searchDistance", description = "How far to look. You usually don't want this function to return an entity millions of units away. The default is 100 units.", type = "number", optional = true }, { name = "hitDistance", description = "The maximum distance between the player's line of sight and the object. Basically how far the player can be 'looking away' from the object. The default is 15 units.", type = "number", optional = true }, { name = "filter", description = "The filter for which entities to look for. By default it only looks for players.", type = "function", optional = true } }, returns = { { name = "closestEnt", description = "The entity that is closest to the player's line of sight. Returns nil when not found.", type = "Entity" }, { name = "distance", description = "The (minimum) distance between the player's line of sight and the object.", type = "number" } }, metatable = DarkRP.PLAYER } DarkRP.VECTOR.isInSight = DarkRP.stub{ name = "isInSight", description = "Decides whether the vector could be seen by the player if they were to look at it.", parameters = { { name = "filter", description = "Trace filter that decides what the player can see through.", type = "table", optional = false }, { name = "ply", description = "The player for whom the vector may or may not be visible.", type = "Player", optional = false } }, returns = { { name = "answer", description = "Whether the player can see the position.", type = "boolean" }, { name = "HitPos", description = "The position of the thing that blocks the player's sight.", type = "Vector" } }, metatable = DarkRP.VECTOR } DarkRP.hookStub{ name = "UpdatePlayerSpeed", description = "Change a player's walking and running speed.", deprecated = "Use GMod's SetupMove and Move hooks instead.", parameters = { { name = "ply", description = "The player for whom the speed changes.", type = "Player" } }, returns = { } } --[[--------------------------------------------------------------------------- Creating custom items ---------------------------------------------------------------------------]] DarkRP.createJob = DarkRP.stub{ name = "createJob", description = "Create a job for DarkRP.", parameters = { { name = "name", description = "The name of the job.", type = "string", optional = false }, { name = "tbl", description = "Table containing the information for the job.", type = "table", optional = false } }, returns = { { name = "team", description = "The team number of the job you've created.", type = "number" } }, metatable = DarkRP } AddExtraTeam = DarkRP.createJob DarkRP.removeJob = DarkRP.stub{ name = "removeJob", description = "Remove a job from DarkRP.", parameters = { { name = "i", description = "The TEAM_ number of the job. Also the index of the job in RPExtraTeams.", type = "number", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.removeShipment = DarkRP.stub{ name = "removeShipment", description = "Remove a shipment from DarkRP. NOTE: Must be called from BOTH server AND client to properly get it removed!", parameters = { { name = "i", description = "The index of the item.", type = "number", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.removeVehicle = DarkRP.stub{ name = "removeVehicle", description = "Remove a vehicle from DarkRP. NOTE: Must be called from BOTH server AND client to properly get it removed!", parameters = { { name = "i", description = "The index of the item.", type = "number", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.removeEntity = DarkRP.stub{ name = "removeEntity", description = "Remove an entity from DarkRP. NOTE: Must be called from BOTH server AND client to properly get it removed!", parameters = { { name = "i", description = "The index of the item.", type = "number", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.removeGroupChat = DarkRP.stub{ name = "removeGroupChat", description = "Remove a groupchat from DarkRP. NOTE: Must be called from BOTH server AND client to properly get it removed!", parameters = { { name = "i", description = "The index of the item.", type = "number", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.removeAmmoType = DarkRP.stub{ name = "removeAmmoType", description = "Remove an ammotype from DarkRP. NOTE: Must be called from BOTH server AND client to properly get it removed!", parameters = { { name = "i", description = "The index of the item.", type = "number", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.removeEntityGroup = DarkRP.stub{ name = "removeEntityGroup", description = "Remove an entitygroup from DarkRP. NOTE: Must be called from BOTH server AND client to properly get it removed!", parameters = { { name = "name", description = "The name of the item.", type = "string", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.removeAgenda = DarkRP.stub{ name = "removeAgenda", description = "Remove a agenda from DarkRP. NOTE: Must be called from BOTH server AND client to properly get it removed!", parameters = { { name = "name", description = "The name of the item.", type = "string", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.removeDemoteGroup = DarkRP.stub{ name = "removeDemoteGroup", description = "Remove an demotegroup from DarkRP. NOTE: Must be called from BOTH server AND client to properly get it removed!", parameters = { { name = "name", description = "The name of the item.", type = "string", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.createEntityGroup = DarkRP.stub{ name = "createEntityGroup", description = "Create a entity group for DarkRP.", parameters = { { name = "name", description = "The name of the entity group.", type = "string", optional = false }, { name = "teamNrs", description = "Vararg team numbers.", type = "number", optional = false } }, returns = { }, metatable = DarkRP } AddDoorGroup = DarkRP.createEntityGroup DarkRP.createShipment = DarkRP.stub{ name = "createShipment", description = "Create a shipment for DarkRP.", parameters = { { name = "name", description = "The name of the shipment.", type = "string", optional = false }, { name = "tbl", description = "Table containing the information for the shipment.", type = "table", optional = false } }, returns = { }, metatable = DarkRP } AddCustomShipment = DarkRP.createShipment DarkRP.createVehicle = DarkRP.stub{ name = "createVehicle", description = "Create a vehicle for DarkRP.", parameters = { { name = "name", description = "The name of the vehicle.", type = "string", optional = false }, { name = "tbl", description = "Table containing the information for the vehicle.", type = "table", optional = false } }, returns = { }, metatable = DarkRP } AddCustomVehicle = DarkRP.createVehicle DarkRP.createEntity = DarkRP.stub{ name = "createEntity", description = "Create a entity for DarkRP.", parameters = { { name = "name", description = "The name of the entity.", type = "string", optional = false }, { name = "tbl", description = "Table containing the information for the entity.", type = "table", optional = false } }, returns = { }, metatable = DarkRP } AddCustomVehicle = DarkRP.createEntity DarkRP.createAgenda = DarkRP.stub{ name = "createAgenda", description = "Create an agenda for groups of jobs to communicate.", parameters = { { name = "title", description = "The name of the agenda.", type = "string", optional = false }, { name = "manager", description = "The team numer of the manager of the agenda (the one who can set the agenda).", type = "number", optional = false }, { name = "listeners", description = "The jobs that can see this agenda.", type = "table", optional = false } }, returns = { }, metatable = DarkRP } AddAgenda = DarkRP.createAgenda DarkRP.getAgendas = DarkRP.stub{ name = "getAgendas", description = "Get all agendas. Note: teams that share an agenda use the exact same agenda table. E.g. when you change the agenda of the CP, the agenda of the Chief will automatically be updated as well. Make sure this property is maintained when modifying the agenda table. Not maintaining that property will lead to players not seeing the right agenda text.", parameters = { }, returns = { { name = "agendas", description = "Table in which the keys are team numbers and the values agendas.", type = "table" } }, metatable = DarkRP } DarkRP.createGroupChat = DarkRP.stub{ name = "createGroupChat", description = "Create a group chat.", parameters = { { name = "functionOrJob", description = "A function that returns whether the person can see the group chat, or a team number.", type = "any", optional = false }, { name = "teamNr", description = "VarArg team number.", type = "number", optional = true } }, returns = { }, metatable = DarkRP } GM.AddGroupChat = DarkRP.createGroupChat DarkRP.createAmmoType = DarkRP.stub{ name = "createAmmoType", description = "Create an ammo type.", parameters = { { name = "name", description = "The name of the ammo.", type = "string", optional = false }, { name = "tbl", description = "Table containing the information for the ammo.", type = "table", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.createDemoteGroup = DarkRP.stub{ name = "createDemoteGroup", description = "Create a demote group. When you get banned (demoted) from one of the jobs in this group, you will be banned from every job in this group.", parameters = { { name = "name", description = "The name of the demote group.", type = "string", optional = false }, { name = "tbl", description = "Table consisting of a list of job.", type = "table", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.getDemoteGroup = DarkRP.stub{ name = "getDemoteGroup", description = "Get the demote group of a team. Every team in the same group will return the same object.", parameters = { { name = "teamNr", description = "Table consisting of a list of job.", type = "number", optional = false } }, returns = { { name = "set", description = "The demote group identifier.", type = "Disjoint-Set" } }, metatable = DarkRP } DarkRP.getGroupChats = DarkRP.stub{ name = "getGroupChats", description = "Get all group chats.", parameters = { }, returns = { { name = "set", description = "Table with functions that decide who can hear who.", type = "table" } }, metatable = DarkRP } DarkRP.getDemoteGroups = DarkRP.stub{ name = "getDemoteGroups", description = "Get all demote groups Every team in the same group will return the same object.", parameters = { }, returns = { { name = "set", description = "Table in which the keys are team numbers and the values Disjoint-Set.", type = "table" } }, metatable = DarkRP } DarkRP.createCategory = DarkRP.stub{ name = "createCategory", description = "Create a category for the F4 menu.", parameters = { { name = "tbl", description = "Table describing the category.", type = "table", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.addToCategory = DarkRP.stub{ name = "addToCategory", description = "Create a category for the F4 menu.", parameters = { { name = "item", description = "Table of the custom entity/job/etc.", type = "table", optional = false }, { name = "kind", description = "The kind of the category (e.g. 'jobs' for job stuff).", type = "string", optional = false }, { name = "cat", description = "The name of the category. Note that the category must exist. Defaults to 'Other'.", type = "string", optional = true } }, returns = { }, metatable = DarkRP } DarkRP.removeFromCategory = DarkRP.stub{ name = "removeFromCategory", description = "Create a category for the F4 menu.", parameters = { { name = "item", description = "Table of the custom entity/job/etc.", type = "table", optional = false }, { name = "kind", description = "The kind of the category (e.g. 'jobs' for job stuff).", type = "string", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.getCategories = DarkRP.stub{ name = "getCategories", description = "Get all categories for all F4 menu tabs.", parameters = { }, returns = { { name = "tbl", description = "all categories.", type = "table" } }, metatable = DarkRP } DarkRP.hookStub{ name = "DarkRPVarChanged", description = "Called when a DarkRPVar was changed.", parameters = { { name = "ply", description = "The player for whom the DarkRPVar changed.", type = "Player" }, { name = "varname", description = "The name of the variable that has changed.", type = "string" }, { name = "oldValue", description = "The old value of the DarkRPVar.", type = "any" }, { name = "newvalue", description = "The new value of the DarkRPVar.", type = "any" } }, returns = { } } DarkRP.hookStub{ name = "canBuyPistol", description = "Whether a player can buy a pistol.", parameters = { { name = "ply", description = "The player.", type = "Player" }, { name = "shipmentTable", description = "The table, as defined in the shipments file.", type = "table" } }, returns = { { name = "canBuy", description = "Whether it can be bought.", type = "boolean" }, { name = "suppressMessage", description = "Suppress the notification message when it cannot be bought.", type = "boolean" }, { name = "message", description = "A replacement for the message that shows if it cannot be bought.", type = "string" }, { name = "price", description = "An optional override for the price.", type = "number" } } } DarkRP.hookStub{ name = "canBuyShipment", description = "Whether a player can buy a shipment.", parameters = { { name = "ply", description = "The player.", type = "Player" }, { name = "shipmentTable", description = "The table, as defined in the shipments file.", type = "table" } }, returns = { { name = "canBuy", description = "Whether it can be bought.", type = "boolean" }, { name = "suppressMessage", description = "Suppress the notification message when it cannot be bought.", type = "boolean" }, { name = "message", description = "A replacement for the message that shows if it cannot be bought.", type = "string" }, { name = "price", description = "An optional override for the price.", type = "number" } } } DarkRP.hookStub{ name = "canBuyVehicle", description = "Whether a player can buy a vehicle.", parameters = { { name = "ply", description = "The player.", type = "Player" }, { name = "vehicleTable", description = "The table, as defined in the vehicles file.", type = "table" } }, returns = { { name = "canBuy", description = "Whether it can be bought.", type = "boolean" }, { name = "suppressMessage", description = "Suppress the notification message when it cannot be bought.", type = "boolean" }, { name = "message", description = "A replacement for the message that shows if it cannot be bought.", type = "string" }, { name = "price", description = "An optional override for the price.", type = "number" } } } DarkRP.hookStub{ name = "canBuyAmmo", description = "Whether a player can buy ammo.", parameters = { { name = "ply", description = "The player.", type = "Player" }, { name = "ammoTable", description = "The table, as defined in the a ammo file.", type = "table" } }, returns = { { name = "canBuy", description = "Whether it can be bought.", type = "boolean" }, { name = "suppressMessage", description = "Suppress the notification message when it cannot be bought.", type = "boolean" }, { name = "message", description = "A replacement for the message that shows if it cannot be bought.", type = "string" }, { name = "price", description = "An optional override for the price.", type = "number" } } } DarkRP.hookStub{ name = "canBuyCustomEntity", description = "Whether a player can a certain custom entity.", parameters = { { name = "ply", description = "The player.", type = "Player" }, { name = "entTable", description = "The table, as defined by the user.", type = "table" } }, returns = { { name = "canBuy", description = "Whether it can be bought.", type = "boolean" }, { name = "suppressMessage", description = "Suppress the notification message when it cannot be bought.", type = "boolean" }, { name = "message", description = "A replacement for the message that shows if it cannot be bought.", type = "string" }, { name = "price", description = "An optional override for the price.", type = "number" } } } DarkRP.hookStub{ name = "onJobRemoved", description = "Called when a job was removed.", parameters = { { name = "num", description = "The TEAM_ number of the job.", type = "number" }, { name = "jobbtable", description = "The table containing all the job info.", type = "table" } }, returns = { } } DarkRP.hookStub{ name = "onShipmentRemoved", description = "Called when a shipment was removed.", parameters = { { name = "num", description = "The index of this item.", type = "number" }, { name = "itemTable", description = "The table containing all the info about this item.", type = "table" } }, returns = { } } DarkRP.hookStub{ name = "onVehicleRemoved", description = "Called when a vehicle was removed.", parameters = { { name = "num", description = "The index of this item.", type = "number" }, { name = "itemTable", description = "The table containing all the info about this item.", type = "table" } }, returns = { } } DarkRP.hookStub{ name = "onEntityRemoved", description = "Called when a buyable entity was removed.", parameters = { { name = "num", description = "The index of this item.", type = "number" }, { name = "itemTable", description = "The table containing all the info about this item.", type = "table" } }, returns = { } } DarkRP.hookStub{ name = "onGroupChatRemoved", description = "Called when a groupchat was removed.", parameters = { { name = "num", description = "The index of this item.", type = "number" }, { name = "itemTable", description = "The table containing all the info about this item.", type = "table" } }, returns = { } } DarkRP.hookStub{ name = "onAmmoTypeRemoved", description = "Called when a ammotype was removed.", parameters = { { name = "num", description = "The index of this item.", type = "number" }, { name = "itemTable", description = "The table containing all the info about this item.", type = "table" } }, returns = { } } DarkRP.hookStub{ name = "onEntityGroupRemoved", description = "Called when an entity group was removed.", parameters = { { name = "name", description = "The name of this item.", type = "string" }, { name = "itemTable", description = "The table containing all the info about this item.", type = "table" } }, returns = { } } DarkRP.hookStub{ name = "onAgendaRemoved", description = "Called when an agenda was removed.", parameters = { { name = "name", description = "The name of this item.", type = "string" }, { name = "itemTable", description = "The table containing all the info about this item.", type = "table" } }, returns = { } } DarkRP.hookStub{ name = "onDemoteGroupRemoved", description = "Called when a job was demotegroup.", parameters = { { name = "name", description = "The name of this item.", type = "string" }, { name = "itemTable", description = "The table containing all the info about this item.", type = "table" } }, returns = { } } DarkRP.hookStub{ name = "loadCustomDarkRPItems", description = "Runs right after the scripts from the DarkRPMod are run. You can add custom jobs, entities, shipments and whatever in this hook.", parameters = { }, returns = { } } DarkRP.hookStub{ name = "DarkRPStartedLoading", description = "Runs at the very start of loading DarkRP. Not even sandbox has loaded here yet.", parameters = { }, returns = { } } DarkRP.hookStub{ name = "DarkRPFinishedLoading", description = "Runs right after DarkRP itself has loaded. All DarkRPMod stuff (except for disabled_defaults) is loaded during this hook. NOTE! NO CUSTOM STUFF WILL BE AVAILABLE DURING THIS HOOK. USE `loadCustomDarkRPItems` INSTEAD IF YOU WANT THAT!", parameters = { }, returns = { } }
mit
lichtl/darkstar
scripts/globals/spells/bluemagic/queasyshroom.lua
31
1990
----------------------------------------- -- Spell: Queasyshroom -- Additional effect: Poison. Duration of effect varies with TP -- Spell cost: 20 MP -- Monster Type: Plantoids -- Spell Type: Physical (Piercing) -- Blue Magic Points: 2 -- Stat Bonus: HP-5, MP+5 -- Level: 8 -- Casting Time: 2 seconds -- Recast Time: 15 seconds -- Skillchain Element(s): Dark (can open Transfixion or Detonation; can close Compression or Gravitation) -- Combos: None ----------------------------------------- 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 params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_PIERCE; params.scattr = SC_DARK; params.numhits = 1; params.multiplier = 1.25; params.tp150 = 1.25; params.tp300 = 1.25; params.azuretp = 1.25; params.duppercap = 8; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.20; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local chance = math.random(); if (damage > 0 and chance > 10) then local typeEffect = EFFECT_POISON; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,3,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
lichtl/darkstar
scripts/zones/Bastok_Mines/npcs/Gawful.lua
14
1103
----------------------------------- -- Area: Bastok Mines -- NPC: Gawful -- Type: Item Deliverer -- @zone 234 -- @pos -22.416 -3.999 -56.076 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); 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
Mudlet-cn/mudlet
src/mudlet-lua/lua/DebugTools.lua
7
6517
---------------------------------------------------------------------------------- --- Mudlet Debug Tools ---------------------------------------------------------------------------------- --- Function colorizes all matched regex capture groups on the screen. --- This is very handy if you make complex regex and want to see what really matches in the text. --- --- @see matches function showCaptureGroups() for k, v in pairs ( matches ) do selectCaptureGroup( tonumber(k) ) setFgColor( math.random(0,255), math.random(0,255), math.random(0,255) ) setBgColor( math.random(0,255), math.random(0,255), math.random(0,255) ) end end --- Prints the content of the table multimatches[n][m] to the screen. This is meant --- as a tool to help write multiline trigger scripts. This helps you to easily see --- what your multiline trigger actually captured in all regex. You can use these values --- directly in your script by referring to it with multimatches[regex-number][capturegroup]. --- --- @usage Just call this s function from your trigger to show the info. --- <pre> --- showMultimatches() --- </pre> --- --- @see multimatches function showMultimatches() echo("\n-------------------------------------------------------"); echo("\nThe table multimatches[n][m] contains:"); echo("\n-------------------------------------------------------"); for k,v in ipairs(multimatches) do echo("\nregex " .. k .. " captured: (multimatches["..k .."][1-n])"); for k2,v2 in ipairs(v) do echo("\n key="..k2.." value="..v2); end end echo("\n-------------------------------------------------------\n"); end --- get the Lua keywords as a set-like table. -- So <code>res["and"]</code> etc would be <code>true</code>. -- @return a table local function get_keywords () if not lua_keyword then lua_keyword = { ["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true, ["until"] = true, ["while"] = true } end return lua_keyword end local function quote_if_necessary (v) if not v then return '' else if v:find ' ' then v = '"'..v..'"' end end return v end local keywords local function is_identifier (s) return type(s) == 'string' and s:find('^[%a_][%w_]*$') and not keywords[s] end local function quote (s) if type(s) == 'table' then return prettywrite(s,'') else return ('%q'):format(tostring(s)) end end local function index (numkey,key) if not numkey then key = quote(key) end return '['..key..']' end --- Create a string representation of a Lua table. (From Steve Donovans Penlight library) -- This function never fails, but may complain by returning an -- extra value. Normally puts out one item per line, using -- the provided indent; set the second parameter to '' if -- you want output on one line. -- @param tbl {table} Table to serialize to a string. -- @param space {string} (optional) The indent to use. -- Defaults to two spaces; make it the empty string for no indentation -- @param not_clever {bool} (optional) Use for plain output, e.g {['key']=1}. -- Defaults to false. -- @return a string -- @return a possible error message local append = table.insert function prettywrite (tbl,space,not_clever) if type(tbl) ~= 'table' then if type(tbl) == "string" then return string.format("\"%s\"\n", tostring(tbl)) else return string.format("%s\n", tostring(tbl)) end end -- return a nice {} instead of {\n} on blanks if not next(tbl) then return '{}' end if not keywords then keywords = get_keywords() end local set = ' = ' if space == '' then set = '=' end space = space or ' ' local lines = {} local line = '' local tables = {} local function put(s) if #s > 0 then line = line..s end end local function putln (s) if #line > 0 then line = line..s append(lines,line) line = '' else append(lines,s) end end local function eat_last_comma () local n,lastch = #lines local lastch = lines[n]:sub(-1,-1) if lastch == ',' then lines[n] = lines[n]:sub(1,-2) end end local writeit writeit = function (t,oldindent,indent) local tp = type(t) if tp ~= 'string' and tp ~= 'table' then putln(quote_if_necessary(tostring(t))..',') elseif tp == 'string' then if t:find('\n') then putln('[[\n'..t..']],') else putln(quote(t)..',') end elseif tp == 'table' then if tables[t] then putln('<cycle>,') return end tables[t] = true local newindent = indent..space putln('{') local used = {} if not not_clever then for i,val in ipairs(t) do put(indent) writeit(val,indent,newindent) used[i] = true end end for key,val in pairs(t) do local numkey = type(key) == 'number' if not_clever then key = tostring(key) put(indent..index(numkey,key)..set) writeit(val,indent,newindent) else if not numkey or not used[key] then -- non-array indices if numkey or not is_identifier(key) then key = index(numkey,key) end put(indent..key..set) writeit(val,indent,newindent) end end end tables[t] = nil eat_last_comma() putln(oldindent..'},') else putln(tostring(t)..',') end end writeit(tbl,'',space) eat_last_comma() return table.concat(lines,#space > 0 and '\n' or '') end function display(what) echo((prettywrite(what, ' ') or 'nil')..'\n') end
gpl-2.0
lichtl/darkstar
scripts/zones/Port_Jeuno/npcs/Zedduva.lua
14
1401
----------------------------------- -- Area: Port Jeuno -- NPC: Zedduva -- @zone 246 -- @pos -61 7 -54 ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(AIRSHIP_PASS) == true and player:getGil() >= 200) then player:startEvent(0x0024); else player:startEvent(0x002c); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0024) then Z = player:getZPos(); if (Z >= -61 and Z <= -58) then player:delGil(200); end end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/spells/kaustra.lua
12
1382
-------------------------------------- -- Spell: Kaustra -- Consumes 20% of your maximum MP. Relentless -- dark damage slowly devours an enemy. -------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/magic") -------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local skill = caster:getSkillLevel(dsp.skill.DARK_MAGIC) local dINT = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT) if (skill > 500) then skill = 500 end if (dINT > 300) then dINT = 300 end local duration = 3 * (1 + (skill / 11)) local base = math.floor((math.floor(0.67 * caster:getMainLvl())/10)*(37 + math.floor(0.67*dINT))) local params = {} params.diff = nil params.attribute = dsp.mod.INT params.skillType = dsp.skill.DARK_MAGIC params.bonus = 0 params.effect = nil local resist = applyResistance(caster, target, spell, params) local dmg = base * resist duration = duration * resist dmg = addBonuses(caster, spell, target, dmg) dmg = adjustForTarget(target,dmg,spell:getElement()) dmg = finalMagicAdjustments(caster,target,spell,dmg) target:addStatusEffect(dsp.effect.KAUSTRA,math.floor(dmg/3),3,duration) return dmg end
gpl-3.0
punisherbot/he
plugins/google.lua
722
1037
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searches Google and send results", usage = "!google [terms]: Searches Google and send results", patterns = { "^!google (.*)$", "^%.[g|G]oogle (.*)$" }, run = run }
gpl-2.0
RunAwayDSP/darkstar
scripts/globals/ephemeral.lua
6
6004
---------------------------------------------- -- Global functionality for Ephemeral Moogles ---------------------------------------------- require("scripts/globals/npc_util") ---------------------------------------------- dsp = dsp or {} dsp.ephemeral = {} -- Cap per crystal type that can be stored. Retail/Default is 5000 local CrystalCap = 5000 -- Information for currency storage and event params local crystalData = { { crystal = 4096, cluster = 4104, tradeparam = 1, eventparam = 1, offset = 0, name = "fire_crystals" }, -- Fire Crystal { crystal = 4097, cluster = 4105, tradeparam = 2, eventparam = 1, offset = 16, name = "ice_crystals" }, -- Ice Crystal { crystal = 4098, cluster = 4106, tradeparam = 3, eventparam = 2, offset = 0, name = "wind_crystals" }, -- Wind Crystal { crystal = 4099, cluster = 4107, tradeparam = 4, eventparam = 2, offset = 16, name = "earth_crystals" }, -- Earth Crystal { crystal = 4100, cluster = 4108, tradeparam = 5, eventparam = 3, offset = 0, name = "lightning_crystals" }, -- Lightning Crystal { crystal = 4101, cluster = 4109, tradeparam = 6, eventparam = 3, offset = 16, name = "water_crystals" }, -- Water Crystal { crystal = 4102, cluster = 4110, tradeparam = 7, eventparam = 4, offset = 0, name = "light_crystals" }, -- Light Crystal { crystal = 4103, cluster = 4111, tradeparam = 8, eventparam = 4, offset = 16, name = "dark_crystals" }, -- Dark Crystal } -- Helper function for getting crystal counts as params local getCrystalTotals = function(player) local params = { 0, 0, 0, 0 } for _, v in pairs(crystalData) do params[v.eventparam] = bit.bor(params[v.eventparam], bit.lshift(player:getCurrency(v.name), v.offset)) end return params end dsp.ephemeral.onTrade = function(player, trade, successEvent, failEvent) local params = { 0, 0, 0, 0, 0, 0, 0, 0 } local success = false for _, v in pairs(crystalData) do if npcUtil.tradeHas(trade, v.crystal) or npcUtil.tradeHas(trade, v.cluster) then -- Check how far from crystal cap we are local currentCount = math.min(player:getCurrency(v.name), CrystalCap) -- In case there is a db discrepancy local diff = CrystalCap - currentCount -- Count clusters and subtract any that won't fit local hqQty = trade:getItemQty(v.cluster) local hqToCrystal = math.min(hqQty * 12, math.floor(diff / 12)) hqQty = math.floor(hqToCrystal / 12) diff = math.max(diff - hqQty * 12, 0) -- Confirm the clusters in the trade if hqQty > 0 then trade:confirmItem(v.cluster, hqQty) end -- Count normal crystals and and subtract any that won't fit local qty = math.min(trade:getItemQty(v.crystal), diff) -- Confirm the crystals in the trade if qty > 0 then trade:confirmItem(v.crystal, qty) end -- Calculate the params params[v.tradeparam] = bit.bor(hqQty, bit.lshift(qty, 16)) -- Calculate total and add to player local total = qty + hqQty * 12 player:addCurrency(v.name, total) -- Make sure we flag success if any of the crystals can be traded if (qty > 0) or (hqQty > 0) then success = true end end end if success then player:startEvent(successEvent, unpack(params)) else player:startEvent(failEvent) end end dsp.ephemeral.onTrigger = function(player, event) player:startEvent(event, unpack(getCrystalTotals(player))) end dsp.ephemeral.onEventUpdate = function(player) player:updateEvent(unpack(getCrystalTotals(player))) end dsp.ephemeral.onEventFinish = function(player, option, wasTrade) -- Early out if the player cancelled the menu if not wasTrade and bit.band(option, 0xF) == 0 then return end if wasTrade then -- Confirm trade player:confirmTrade() else -- Grab the crystal type and quantities local index = bit.band(bit.rshift(option, 16), 0xFF) local quantity = bit.band(option, 0xFFFF) local crystals = quantity % 12 local clusters = math.floor(quantity / 12) -- Player selected "as many as can fit" if (option > 0x80000000) then -- Recalculate the quantity according to open inventory slots local freeSlots = player:getFreeSlotsCount() if freeSlots > 0 then -- If we don't have any free slots, don't bother. Just fail later. local clusterStacks = math.ceil(clusters / 12) -- If we don't have room for everything, drop the extra crystals first if (clusterStacks + math.ceil(crystals / 12)) > freeSlots then crystals = 0 end -- Pick the the smaller of the cluster stacks and free slots clusterStacks = math.min(clusterStacks, freeSlots) -- Original number of clusters could have an incomplete stack clusters = math.min(clusters, clusterStacks * 12) end end local totalToRemove = 0 -- Clusters first if clusters > 0 then if npcUtil.giveItem(player, { { crystalData[index].cluster, clusters } }) then totalToRemove = clusters * 12 end end -- Then Crystals if crystals > 0 then if npcUtil.giveItem(player, { { crystalData[index].crystal, crystals } }) then totalToRemove = totalToRemove + crystals end end -- Crystals were added. Remove them from char_points if totalToRemove > 0 then player:delCurrency(crystalData[index].name, totalToRemove) end end end
gpl-3.0
MightyPirates/OC-LuaJ
luaj-test/src/test/resources/lua5.2.1-tests/all.lua
1
5647
#!../lua local version = "Lua 5.2" if _VERSION ~= version then io.stderr:write("\nThis test suite is for ", version, ", not for ", _VERSION, "\nExiting tests\n") return end -- next variables control the execution of some tests -- true means no test (so an undefined variable does not skip a test) -- defaults are for Linux; test everything _soft = false -- true to avoid long or memory consuming tests _port = false -- true to avoid non-portable tests _no32 = false -- true to avoid tests that assume 32 bits _nomsg = false -- true to avoid messages about tests not performed _noposix = false -- false assumes LUA_USE_POSIX _nolonglong = false -- false assumes LUA_USE_LONGLONG _noformatA = false -- false assumes LUA_USE_AFORMAT local usertests = rawget(_G, "_U") if usertests then -- tests for sissies ;) Avoid problems _soft = true _port = true _no32 = true _nomsg = true _noposix = true _nolonglong = true _noformatA = true; end -- no "internal" tests for user tests if usertests then T = nil end T = rawget(_G, "T") -- avoid problems with 'strict' module package.path = "?;./?.lua" .. package.path math.randomseed(0) collectgarbage("setstepmul", 200) collectgarbage("setpause", 200) --[=[ example of a long [comment], [[spanning several [lines]]] ]=] print("current path:\n****" .. package.path .. "****\n") local c = os.clock() local collectgarbage = collectgarbage do -- track messages for tests not performed local msgs = {} function Message (m) if not _nomsg then print(m) msgs[#msgs+1] = string.sub(m, 3, -3) end end assert(os.setlocale"C") local T,print,format,write,assert,type,unpack,floor = T,print,string.format,io.write,assert,type,table.unpack,math.floor -- use K for 1000 and M for 1000000 (not 2^10 -- 2^20) local function F (m) local function round (m) m = m + 0.04999 return m - (m % 0.1) -- keep one decimal digit end if m < 1000 then return m else m = m / 1000 if m < 1000 then return round(m).."K" else return round(m/1000).."M" end end end local showmem if not T then local max = 0 showmem = function () local m = collectgarbage("count") * 1024 max = (m > max) and m or max print(format(" ---- total memory: %s, max memory: %s ----\n", F(m), F(max))) end else showmem = function () T.checkmemory() local total, numblocks, maxmem = T.totalmem() local count = collectgarbage("count") print(format( "\n ---- total memory: %s (%.0fK), max use: %s, blocks: %d\n", F(total), count, F(maxmem), numblocks)) print(format("\t(strings: %d, tables: %d, functions: %d, ".. "\n\tudata: %d, threads: %d)", T.totalmem"string", T.totalmem"table", T.totalmem"function", T.totalmem"userdata", T.totalmem"thread")) end end -- -- redefine dofile to run files through dump/undump -- local function report (n) print("\n***** FILE '"..n.."'*****") end local olddofile = dofile dofile = function (n) showmem() report(n) local f = assert(loadfile(n)) local b = string.dump(f) f = assert(load(b)) return f() end dofile('main.lua') do local eph = setmetatable({}, {__mode = "k"}) -- create an ephemeron table local next, setmetatable, stderr = next, setmetatable, io.stderr local mt = {} -- each time a table is collected, create a new one to be -- collected next cycle mt.__gc = function (o) stderr:write'.' -- mark progress -- assert(eph[o]() == o and next(eph) == o and next(eph, o) == nil) local n = setmetatable({}, mt) -- replicate object eph[n] = function () return n end o = nil local a,b,c,d,e = nil -- erase 'o' from the stack end local n = setmetatable({}, mt) -- replicate object eph[n] = function () return n end end report"gc.lua" local f = assert(loadfile('gc.lua')) f() collectgarbage("generational") dofile('db.lua') assert(dofile('calls.lua') == deep and deep) olddofile('strings.lua') olddofile('literals.lua') assert(dofile('attrib.lua') == 27) collectgarbage("incremental") -- redo some tests in incremental mode olddofile('strings.lua') olddofile('literals.lua') dofile('constructs.lua') dofile('api.lua') collectgarbage("generational") -- back to generational mode collectgarbage("setpause", 200) collectgarbage("setmajorinc", 500) assert(dofile('locals.lua') == 5) dofile('constructs.lua') dofile('code.lua') if not _G._soft then report('big.lua') local f = coroutine.wrap(assert(loadfile('big.lua'))) assert(f() == 'b') assert(f() == 'a') end dofile('nextvar.lua') dofile('pm.lua') dofile('api.lua') assert(dofile('events.lua') == 12) dofile('vararg.lua') dofile('closure.lua') dofile('coroutine.lua') dofile('goto.lua') dofile('errors.lua') dofile('math.lua') dofile('sort.lua') dofile('bitwise.lua') assert(dofile('verybig.lua') == 10); collectgarbage() dofile('files.lua') if #msgs > 0 then print("\ntests not performed:") for i=1,#msgs do print(msgs[i]) end print() end print("final OK !!!") local debug = require "debug" debug.sethook(function (a) assert(type(a) == 'string') end, "cr") -- to survive outside block _G.showmem = showmem end local _G, showmem, print, format, clock = _G, showmem, print, string.format, os.clock -- erase (almost) all globals print('cleaning all!!!!') for n in pairs(_G) do if not ({___Glob = 1, tostring = 1})[n] then _G[n] = nil end end collectgarbage() collectgarbage() collectgarbage() collectgarbage() collectgarbage() collectgarbage();showmem() print(format("\n\ntotal time: %.2f\n", clock()-c))
mit
lichtl/darkstar
scripts/globals/mobskills/Chains_of_Rage.lua
18
1157
--------------------------------------------- -- Chains of Apathy -- --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/keyitems"); require("scripts/zones/Empyreal_Paradox/TextIDs"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local targets = mob:getEnmityList(); for i,v in pairs(targets) do if (v:isPC()) then local race = v:getRace() if (race == 8) and not v:hasKeyItem(LIGHT_OF_ALTAIEU) then mob:showText(mob, PROMATHIA_TEXT + 4); return 0; end end end return 1; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_TERROR; local power = 30; local duration = 30; if target:isPC() and ((target:getRace() == 8) and not target:hasKeyItem(LIGHT_OF_ALTAIEU)) then skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, power, 0, duration)); else skill:setMsg(MSG_NO_EFFECT); end return typeEffect; end;
gpl-3.0
lichtl/darkstar
scripts/zones/Northern_San_dOria/npcs/Bertenont.lua
14
1763
----------------------------------- -- Area: Northern San d'Oria -- NPC: Bertenont -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- @pos -165 0.1 226 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,9) == false) then player:startEvent(0x0329); else player:showText(npc,BERTENONT_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0329) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",9,true); end end;
gpl-3.0
OctoEnigma/shiny-octo-system
addons/ulx/lua/ulx/xgui/server/sv_bans.lua
1
9548
--sv_bans -- by Stickly Man! --Server-side code related to the bans menu. local bans={} function bans.init() ULib.ucl.registerAccess( "xgui_managebans", "superadmin", "Allows addition, removal, and viewing of bans in XGUI.", "XGUI" ) xgui.addDataType( "bans", function() return { count=table.Count( ULib.bans ) } end, "xgui_managebans", 30, 20 ) --Chat commands local function xgui_banWindowChat( ply, func, args, doFreeze ) if doFreeze ~= true then doFreeze = false end if args[1] and args[1] ~= "" then local target = ULib.getUser( args[1] ) if target then ULib.clientRPC( ply, "xgui.ShowBanWindow", target, target:SteamID(), doFreeze ) end else ULib.clientRPC( ply, "xgui.ShowBanWindow" ) end end ULib.addSayCommand( "!xban", xgui_banWindowChat, "ulx ban" ) local function xgui_banWindowChatFreeze( ply, func, args ) xgui_banWindowChat( ply, func, args, true ) end ULib.addSayCommand( "!fban", xgui_banWindowChatFreeze, "ulx ban" ) --XGUI commands function bans.updateBan( ply, args ) local access, accessTag = ULib.ucl.query( ply, "ulx ban" ) if not access then ULib.tsayError( ply, "Error editing ban: You must have access to ulx ban, " .. ply:Nick() .. "!", true ) return end local steamID = args[1] local bantime = tonumber( args[2] ) local reason = args[3] local name = args[4] -- Check restrictions local cmd = ULib.cmds.translatedCmds[ "ulx ban" ] local accessPieces = {} if accessTag then accessPieces = ULib.splitArgs( accessTag, "<", ">" ) end -- Ban length local argInfo = cmd.args[3] local success, err = argInfo.type:parseAndValidate( ply, bantime, argInfo, accessPieces[2] ) if not success then ULib.tsayError( ply, "Error editing ban: " .. err, true ) return end -- Reason local argInfo = cmd.args[4] local success, err = argInfo.type:parseAndValidate( ply, reason, argInfo, accessPieces[3] ) if not success then ULib.tsayError( ply, "Error editing ban: You did not specify a valid reason, " .. ply:Nick() .. "!", true ) return end if not ULib.bans[steamID] then ULib.addBan( steamID, bantime, reason, name, ply ) return end if name == "" then name = nil ULib.bans[steamID].name = nil end if bantime ~= 0 then if (ULib.bans[steamID].time + bantime*60) <= os.time() then --New ban time makes the ban expired ULib.unban( steamID, ply ) return end bantime = bantime - (os.time() - ULib.bans[steamID].time)/60 end ULib.addBan( steamID, bantime, reason, name, ply ) end xgui.addCmd( "updateBan", bans.updateBan ) --Misc functions function bans.processBans() bans.clearSortCache() xgui.sendDataTable( {}, "bans" ) --Only sends the ban count, and triggers the client to clear their cache. end function bans.clearSortCache() xgui.bansbyid = {} xgui.bansbyname = {} xgui.bansbyadmin = {} xgui.bansbyreason = {} xgui.bansbydate = {} xgui.bansbyunban = {} xgui.bansbybanlength = {} end function bans.getSortTable( sortType ) -- Retrieve the sorted table of bans. If type hasn't been sorted, then sort and cache. if sortType == 1 then -- Bans by Name if next( xgui.bansbyname ) == nil then for k, v in pairs( ULib.bans ) do table.insert( xgui.bansbyname, { k, v.name and string.upper( v.name ) or nil } ) end table.sort( xgui.bansbyname, function( a, b ) return (a[2] or "\255" .. a[1]) < (b[2] or "\255" .. b[1]) end ) end return xgui.bansbyname elseif sortType == 2 then -- Bans by SteamID if next( xgui.bansbyid ) == nil then for k, v in pairs( ULib.bans ) do table.insert( xgui.bansbyid, { k } ) end table.sort( xgui.bansbyid, function( a, b ) return a[1] < b[1] end ) end return xgui.bansbyid elseif sortType == 3 then -- Bans by Admin if next( xgui.bansbyadmin ) == nil then for k, v in pairs( ULib.bans ) do table.insert( xgui.bansbyadmin, { k, v.admin or "" } ) end table.sort( xgui.bansbyadmin, function( a, b ) return a[2] < b[2] end ) end return xgui.bansbyadmin elseif sortType == 4 then -- Bans by Reason if next( xgui.bansbyreason ) == nil then for k, v in pairs( ULib.bans ) do table.insert( xgui.bansbyreason, { k, v.reason or "" } ) end table.sort( xgui.bansbyreason, function( a, b ) return a[2] < b[2] end ) end return xgui.bansbyreason elseif sortType == 5 then -- Bans by Unban Date if next( xgui.bansbyunban ) == nil then for k, v in pairs( ULib.bans ) do table.insert( xgui.bansbyunban, { k, tonumber(v.unban) or 0 } ) end table.sort( xgui.bansbyunban, function( a, b ) return a[2] < b[2] end ) end return xgui.bansbyunban elseif sortType == 6 then -- Bans by Ban Length if next( xgui.bansbybanlength ) == nil then for k, v in pairs( ULib.bans ) do table.insert( xgui.bansbybanlength, { k, (tonumber(v.unban) ~= 0) and (v.unban - v.time) or nil } ) end table.sort( xgui.bansbybanlength, function( a, b ) return (a[2] or math.huge) < (b[2] or math.huge) end ) end return xgui.bansbybanlength else if next( xgui.bansbydate ) == nil then for k, v in pairs( ULib.bans ) do table.insert( xgui.bansbydate, { k, v.time or 0 } ) end table.sort( xgui.bansbydate, function( a, b ) return tonumber( a[2] ) > tonumber( b[2] ) end ) end return xgui.bansbydate end end function bans.sendBansToUser( ply, args ) if not ply then return end if not ULib.ucl.query( ply, "xgui_managebans" ) then return end --local perfTimer = os.clock() --Debug -- Default params sortType = tonumber( args[1] ) or 0 filterString = args[2] ~= "" and string.lower( args[2] ) or nil filterPermaBan = args[3] and tonumber( args[3] ) or 0 filterIncomplete = args[4] and tonumber( args[4] ) or 0 page = tonumber( args[5] ) or 1 ascending = tonumber( args[6] ) == 1 or false -- Get cached sort table to use to reference the real data. sortTable = bans.getSortTable( sortType ) local bansToSend = {} -- Handle ascending or descending local startValue = ascending and #sortTable or 1 local endValue = ascending and 1 or #sortTable local firstEntry = (page - 1) * 17 local currentEntry = 0 local noFilter = ( filterPermaBan == 0 and filterIncomplete == 0 and filterString == nil ) for i = startValue, endValue, ascending and -1 or 1 do local steamID = sortTable[i][1] local bandata = ULib.bans[steamID] -- Handle filters. This is confusing, but essentially 0 means skip check, 1 means restrict if condition IS true, 2+ means restrict if condition IS NOT true. if not ( filterPermaBan > 0 and ( ( tonumber( bandata.unban ) == 0 ) == ( filterPermaBan == 1 ) ) ) then if not ( filterIncomplete > 0 and ( ( bandata.time == nil ) == ( filterIncomplete == 1 ) ) ) then -- Handle string filter if not ( filterString and not ( steamID and string.find( string.lower( steamID ), filterString ) or bandata.name and string.find( string.lower( bandata.name ), filterString ) or bandata.reason and string.find( string.lower( bandata.reason ), filterString ) or bandata.admin and string.find( string.lower( bandata.admin ), filterString ) or bandata.modified_admin and string.find( string.lower( bandata.modified_admin ), filterString ) )) then --We found a valid one! .. Now for the pagination. if #bansToSend < 17 and currentEntry >= firstEntry then table.insert( bansToSend, bandata ) bansToSend[#bansToSend].steamID = steamID if noFilter and #bansToSend >= 17 then break end -- If there is a filter, then don't stop the loop so we can get a "result" count. end currentEntry = currentEntry + 1 end end end end if not noFilter then bansToSend.count = currentEntry end --print( "XGUI: Ban request took " .. os.clock() - perfTimer ) --Debug -- Send bans to client via custom handling. xgui.sendDataEvent( ply, 7, "bans", bansToSend ) end xgui.addCmd( "getbans", bans.sendBansToUser ) --Hijack the addBan function to update XGUI's ban info. local banfunc = ULib.addBan ULib.addBan = function( steamid, time, reason, name, admin ) banfunc( steamid, time, reason, name, admin ) bans.processBans() bans.unbanTimer() end --Hijack the unBan function to update XGUI's ban info. local unbanfunc = ULib.unban ULib.unban = function( steamid, admin ) unbanfunc( steamid, admin ) bans.processBans() if timer.Exists( "xgui_unban" .. steamid ) then timer.Remove( "xgui_unban" .. steamid ) end end --Create timers that will automatically perform an unban when a users ban runs out. Polls hourly. function bans.unbanTimer() timer.Create( "xgui_unbanTimer", 3600, 0, bans.unbanTimer ) for ID, data in pairs( ULib.bans ) do if tonumber( data.unban ) ~= 0 then if tonumber( data.unban ) - os.time() <= 3600 then timer.Remove( "xgui_unban" .. ID ) timer.Create( "xgui_unban" .. ID, tonumber( data.unban ) - os.time(), 1, function() ULib.unban( ID ) end ) end end end end ulx.addToHelpManually( "Menus", "xgui fban", "<player> - Opens the add ban window, freezes the specified player, and fills out the Name/SteamID automatically. (say: !fban)" ) ulx.addToHelpManually( "Menus", "xgui xban", "<player> - Opens the add ban window and fills out Name/SteamID automatically if a player was specified. (say: !xban)" ) end function bans.postinit() bans.processBans() bans.unbanTimer() end xgui.addSVModule( "bans", bans.init, bans.postinit )
mit
lichtl/darkstar
scripts/zones/Periqia/instances/seagull_grounded.lua
29
4665
----------------------------------- -- -- Assault: Seagull Grounded -- ----------------------------------- require("scripts/zones/Periqia/IDs"); ----------------------------------- -- afterInstanceRegister ----------------------------------- function afterInstanceRegister(player) local instance = player:getInstance(); player:messageSpecial(Periqia.text.ASSAULT_31_START, 1); player:messageSpecial(Periqia.text.TIME_TO_COMPLETE, instance:getTimeLimit()); end; ----------------------------------- -- onInstanceCreated ----------------------------------- function onInstanceCreated(instance) for i,v in pairs(Periqia.mobs[31]) do SpawnMob(v, instance); end local rune = instance:getEntity(bit.band(Periqia.npcs.RUNE_OF_RELEASE, 0xFFF), TYPE_NPC); local box = instance:getEntity(bit.band(Periqia.npcs.ANCIENT_LOCKBOX, 0xFFF), TYPE_NPC); rune:setPos(-495,-9.899,-72,0); box:setPos(-495,-9.695,-75,0); instance:getEntity(bit.band(Periqia.npcs.EXCALIACE, 0xFFF), TYPE_NPC):setStatus(1); instance:getEntity(bit.band(Periqia.npcs._1K6, 0xFFF), TYPE_NPC):setAnimation(8); instance:getEntity(bit.band(Periqia.npcs._1KX, 0xFFF), TYPE_NPC):setAnimation(8); instance:getEntity(bit.band(Periqia.npcs._1KZ, 0xFFF), TYPE_NPC):setAnimation(8); instance:getEntity(bit.band(Periqia.npcs._JK1, 0xFFF), TYPE_NPC):setAnimation(8); instance:getEntity(bit.band(Periqia.npcs._JK3, 0xFFF), TYPE_NPC):setAnimation(8); end; ----------------------------------- -- onInstanceTimeUpdate ----------------------------------- function onInstanceTimeUpdate(instance, elapsed) local players = instance:getChars(); local lastTimeUpdate = instance:getLastTimeUpdate(); local remainingTimeLimit = (instance:getTimeLimit()) * 60 - (elapsed / 1000); local wipeTime = instance:getWipeTime(); local message = 0; if (remainingTimeLimit < 0) then instance:fail(); return; end if (wipeTime == 0) then local wipe = true; for i,v in pairs(players) do if v:getHP() ~= 0 then wipe = false; break; end end if (wipe) then for i,v in pairs(players) do v:messageSpecial(Periqia.text.PARTY_FALLEN, 3); end instance:setWipeTime(elapsed); end else if (elapsed - wipeTime) / 1000 > 180 then instance:fail(); return; else for i,v in pairs(players) do if v:getHP() ~= 0 then instance:setWipeTime(0); break; end end end end if (lastTimeUpdate == 0 and elapsed > 20 * 60000) then message = 600; elseif (lastTimeUpdate == 600 and remainingTimeLimit < 300) then message = 300; elseif (lastTimeUpdate == 300 and remainingTimeLimit < 60) then message = 60; elseif (lastTimeUpdate == 60 and remainingTimeLimit < 30) then message = 30; elseif (lastTimeUpdate == 30 and remainingTimeLimit < 10) then message = 10; end if (message ~= 0) then for i,v in pairs(players) do if (remainingTimeLimit >= 60) then v:messageSpecial(Periqia.text.TIME_REMAINING_MINUTES, remainingTimeLimit / 60); else v:messageSpecial(Periqia.text.TIME_REMAINING_SECONDS, remainingTimeLimit); end end instance:setLastTimeUpdate(message); end end; ----------------------------------- -- onInstanceFailure ----------------------------------- function onInstanceFailure(instance) local chars = instance:getChars(); for i,v in pairs(chars) do v:messageSpecial(Periqia.text.MISSION_FAILED,10,10); v:startEvent(0x66); end end; ----------------------------------- -- onInstanceProgressUpdate ----------------------------------- function onInstanceProgressUpdate(instance, progress) if (progress > 0) then instance:complete(); end end; ----------------------------------- -- onInstanceComplete ----------------------------------- function onInstanceComplete(instance) local chars = instance:getChars(); for i,v in pairs(chars) do v:messageSpecial(Periqia.text.RUNE_UNLOCKED_POS, 8, 8); end local rune = instance:getEntity(bit.band(Periqia.npcs.RUNE_OF_RELEASE, 0xFFF), TYPE_NPC); local box = instance:getEntity(bit.band(Periqia.npcs.ANCIENT_LOCKBOX, 0xFFF), TYPE_NPC); rune:setStatus(STATUS_NORMAL); box:setStatus(STATUS_NORMAL); end;
gpl-3.0
lichtl/darkstar
scripts/zones/Bastok_Mines/npcs/Tami.lua
17
2878
----------------------------------- -- Area: Bastok Mines -- NPC: Tami -- Starts & Finishes Repeatable Quest: Groceries -- Note: Repeatable until proper completion ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) ViewedNote = player:getVar("GroceriesViewedNote"); if (ViewedNote == 1) then count = trade:getItemCount(); MeatJerky = trade:hasItemQty(4376,1); if (MeatJerky == true and count == 1) then player:startEvent(0x0071); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Groceries = player:getQuestStatus(BASTOK,GROCERIES); GroceriesVar = player:getVar("Groceries"); if (Groceries == QUEST_COMPLETED) then player:startEvent(0x0073); elseif (Groceries == QUEST_AVAILABLE or GroceriesVar == 0) then player:startEvent(0x006e); elseif (GroceriesVar == 1) then player:showText(npc,10510); elseif (GroceriesVar == 2) then player:startEvent(0x0070); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x006e) then Groceries = player:getQuestStatus(BASTOK,GROCERIES); if (Groceries == QUEST_AVAILABLE) then player:addQuest(BASTOK,GROCERIES); end player:addKeyItem(0x98); player:messageSpecial(KEYITEM_OBTAINED,0x98); player:setVar("Groceries",1); elseif (csid == 0x0070) then player:addFame(BASTOK,8); player:setVar("Groceries",0); player:addGil(GIL_RATE*10); player:messageSpecial(GIL_OBTAINED,GIL_RATE*10); elseif (csid == 0x0071) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:tradeComplete(); player:setVar("Groceries",0); player:setVar("GroceriesViewedNote",0); player:completeQuest(BASTOK,GROCERIES); player:addFame(BASTOK,75); player:addItem(13594); player:messageSpecial(ITEM_OBTAINED,13594); else player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,13594); end end end;
gpl-3.0
OctoEnigma/shiny-octo-system
gamemodes/sandbox/entities/weapons/gmod_tool/stool.lua
1
4834
ToolObj = {} include( "ghostentity.lua" ) include( "object.lua" ) if ( CLIENT ) then include( "stool_cl.lua" ) end function ToolObj:Create() local o = {} setmetatable( o, self ) self.__index = self o.Mode = nil o.SWEP = nil o.Owner = nil o.ClientConVar = {} o.ServerConVar = {} o.Objects = {} o.Stage = 0 o.Message = "start" o.LastMessage = 0 o.AllowedCVar = 0 return o end function ToolObj:CreateConVars() local mode = self:GetMode() if ( CLIENT ) then for cvar, default in pairs( self.ClientConVar ) do CreateClientConVar( mode .. "_" .. cvar, default, true, true ) end return end -- Note: I changed this from replicated because replicated convars don't work -- when they're created via Lua. if ( SERVER ) then self.AllowedCVar = CreateConVar( "toolmode_allow_" .. mode, 1, FCVAR_NOTIFY ) end end function ToolObj:GetServerInfo( property ) local mode = self:GetMode() return GetConVarString( mode .. "_" .. property ) end function ToolObj:BuildConVarList() local mode = self:GetMode() local convars = {} for k, v in pairs( self.ClientConVar ) do convars[ mode .. "_" .. k ] = v end return convars end function ToolObj:GetClientInfo( property ) return self:GetOwner():GetInfo( self:GetMode() .. "_" .. property ) end function ToolObj:GetClientNumber( property, default ) return self:GetOwner():GetInfoNum( self:GetMode() .. "_" .. property, tonumber( default ) or 0 ) end function ToolObj:Allowed() if ( CLIENT ) then return true end return self.AllowedCVar:GetBool() end -- Now for all the ToolObj redirects function ToolObj:Init() end function ToolObj:GetMode() return self.Mode end function ToolObj:GetSWEP() return self.SWEP end function ToolObj:GetOwner() return self:GetSWEP().Owner or self.Owner end function ToolObj:GetWeapon() return self:GetSWEP().Weapon or self.Weapon end function ToolObj:LeftClick() return false end function ToolObj:RightClick() return false end function ToolObj:Reload() self:ClearObjects() end function ToolObj:Deploy() self:ReleaseGhostEntity() return end function ToolObj:Holster() self:ReleaseGhostEntity() return end function ToolObj:Think() self:ReleaseGhostEntity() end --[[--------------------------------------------------------- Checks the objects before any action is taken This is to make sure that the entities haven't been removed -----------------------------------------------------------]] function ToolObj:CheckObjects() for k, v in pairs( self.Objects ) do if ( !v.Ent:IsWorld() && !v.Ent:IsValid() ) then self:ClearObjects() end end end local toolmodes = file.Find( SWEP.Folder .. "/stools/*.lua", "LUA" ) for key, val in pairs( toolmodes ) do local char1, char2, toolmode = string.find( val, "([%w_]*).lua" ) TOOL = ToolObj:Create() TOOL.Mode = toolmode AddCSLuaFile( "stools/" .. val ) include( "stools/" .. val ) TOOL:CreateConVars() SWEP.Tool[ toolmode ] = TOOL TOOL = nil end ToolObj = nil if ( CLIENT ) then -- Keep the tool list handy local TOOLS_LIST = SWEP.Tool -- Add the STOOLS to the tool menu hook.Add( "PopulateToolMenu", "AddSToolsToMenu", function() for ToolName, TOOL in pairs( TOOLS_LIST ) do if ( TOOL.AddToMenu != false ) then spawnmenu.AddToolMenuOption( TOOL.Tab or "Main", TOOL.Category or "New Category", ToolName, TOOL.Name or "#" .. ToolName, TOOL.Command or "gmod_tool " .. ToolName, TOOL.ConfigName or ToolName, TOOL.BuildCPanel ) end end end ) -- -- Search -- search.AddProvider( function( str ) str = str:PatternSafe() local list = {} for k, v in pairs( TOOLS_LIST ) do if ( !k:find( str ) ) then continue end local entry = { text = v.Name or "#" .. k, icon = spawnmenu.CreateContentIcon( "tool", nil, { spawnname = k, nicename = v.Name or "#" .. k } ), words = { k } } table.insert( list, entry ) if ( #list >= 32 ) then break end end return list end ) -- -- Tool spawnmenu icon -- spawnmenu.AddContentType( "tool", function( container, obj ) if ( !obj.spawnname ) then return end local icon = vgui.Create( "ContentIcon", container ) icon:SetContentType( "tool" ) icon:SetSpawnName( obj.spawnname ) icon:SetName( obj.nicename or "#tool." .. obj.spawnname .. ".name" ) icon:SetMaterial( "gui/tool.png" ) icon.DoClick = function() spawnmenu.ActivateTool( obj.spawnname ) surface.PlaySound( "ui/buttonclickrelease.wav" ) end icon.OpenMenu = function( icon ) local menu = DermaMenu() menu:AddOption( "Delete", function() icon:Remove() hook.Run( "SpawnlistContentChanged", icon ) end ) menu:Open() end if ( IsValid( container ) ) then container:Add( icon ) end return icon end ) end
mit
lichtl/darkstar
scripts/zones/Port_San_dOria/npcs/Ilgusin.lua
14
1051
----------------------------------- -- Area: Port San d'Oria -- NPC: Ilgusin -- Type: Standard NPC -- @zone 232 -- @pos -68.313 -6.5 -36.985 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x024f); 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
taiha/luci
protocols/luci-proto-relay/luasrc/model/cbi/admin_network/proto_relay.lua
70
1945
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ipaddr, network local forward_bcast, forward_dhcp, gateway, expiry, retry, table ipaddr = section:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Address to access local relay bridge")) ipaddr.datatype = "ip4addr" network = s:taboption("general", DynamicList, "network", translate("Relay between networks")) network.widget = "checkbox" network.exclude = arg[1] network.template = "cbi/network_netlist" network.nocreate = true network.nobridges = true network.novirtual = true network:depends("proto", "relay") forward_bcast = section:taboption("advanced", Flag, "forward_bcast", translate("Forward broadcast traffic")) forward_bcast.default = forward_bcast.enabled forward_dhcp = section:taboption("advanced", Flag, "forward_dhcp", translate("Forward DHCP traffic")) forward_dhcp.default = forward_dhcp.enabled gateway = section:taboption("advanced", Value, "gateway", translate("Use DHCP gateway"), translate("Override the gateway in DHCP responses")) gateway.datatype = "ip4addr" gateway:depends("forward_dhcp", forward_dhcp.enabled) expiry = section:taboption("advanced", Value, "expiry", translate("Host expiry timeout"), translate("Specifies the maximum amount of seconds after which hosts are presumed to be dead")) expiry.placeholder = "30" expiry.datatype = "min(1)" retry = section:taboption("advanced", Value, "retry", translate("ARP retry threshold"), translate("Specifies the maximum amount of failed ARP requests until hosts are presumed to be dead")) retry.placeholder = "5" retry.datatype = "min(1)" table = section:taboption("advanced", Value, "table", translate("Use routing table"), translate("Override the table used for internal routes")) table.placeholder = "16800" table.datatype = "range(0,65535)"
apache-2.0
ld-test/loop
lua/loop/compiler/Conditional.lua
12
1934
-------------------------------------------------------------------------------- ---------------------- ## ##### ##### ###### ----------------------- ---------------------- ## ## ## ## ## ## ## ----------------------- ---------------------- ## ## ## ## ## ###### ----------------------- ---------------------- ## ## ## ## ## ## ----------------------- ---------------------- ###### ##### ##### ## ----------------------- ---------------------- ----------------------- ----------------------- Lua Object-Oriented Programming ------------------------ -------------------------------------------------------------------------------- -- Project: LOOP Class Library -- -- Release: 2.3 beta -- -- Title : Conditional Compiler for Code Generation -- -- Author : Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- local type = type local assert = assert local ipairs = ipairs local setfenv = setfenv local loadstring = loadstring local table = require "table" local oo = require "loop.base" module("loop.compiler.Conditional", oo.class) function source(self, includes) local func = {} for line, strip in ipairs(self) do local cond = strip[2] if cond then cond = assert(loadstring("return "..cond, "compiler condition "..line..":")) setfenv(cond, includes) cond = cond() else cond = true end if cond then assert(type(strip[1]) == "string", "code string is not a string") func[#func+1] = strip[1] end end return table.concat(func, "\n") end function execute(self, includes, ...) return assert(loadstring(self:source(includes), self.name))(...) end
mit
RunAwayDSP/darkstar
scripts/globals/weaponskills/combo.lua
10
1459
----------------------------------- -- Combo -- Hand-to-Hand weapon skill -- Skill level: 5 -- Delivers a threefold attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Thunder Gorget. -- Aligned with the Thunder 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, tp, primary, action, taChar) local params = {} params.numHits = 3 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.atk100 = 1; params.atk200 = 1; params.atk300 = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 1 params.ftp200 = 3.75 params.ftp300 = 5.5 params.str_wsc = 0.3 params.dex_wsc = 0.3 end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar) return tpHits, extraHits, criticalHit, damage end
gpl-3.0
OctoEnigma/shiny-octo-system
gamemodes/sandbox/entities/weapons/gmod_tool/stools/motor.lua
1
4943
TOOL.Category = "Constraints" TOOL.Name = "#tool.motor.name" TOOL.ClientConVar[ "torque" ] = "500" TOOL.ClientConVar[ "friction" ] = "1" TOOL.ClientConVar[ "nocollide" ] = "1" TOOL.ClientConVar[ "forcetime" ] = "0" TOOL.ClientConVar[ "fwd" ] = "45" TOOL.ClientConVar[ "bwd" ] = "42" TOOL.ClientConVar[ "toggle" ] = "0" TOOL.ClientConVar[ "forcelimit" ] = "0" TOOL.Information = { { name = "left", stage = 0 }, { name = "left_1", stage = 1 }, { name = "reload"} } function TOOL:LeftClick( trace ) if ( IsValid( trace.Entity ) && trace.Entity:IsPlayer() ) then return end -- If there's no physics object then we can't constraint it! if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end local iNum = self:NumObjects() local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone ) -- Don't allow us to choose the world as the first object if ( iNum == 0 && !IsValid( trace.Entity ) ) then return end -- Don't allow us to choose the same object if ( iNum == 1 && trace.Entity == self:GetEnt( 1 ) ) then return end self:SetObject( iNum + 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal ) if ( iNum > 0 ) then if ( CLIENT ) then self:ClearObjects() self:ReleaseGhostEntity() return true end -- Get client's CVars local torque = self:GetClientNumber( "torque" ) local friction = self:GetClientNumber( "friction" ) local nocollide = self:GetClientNumber( "nocollide" ) local time = self:GetClientNumber( "forcetime" ) local forekey = self:GetClientNumber( "fwd" ) local backkey = self:GetClientNumber( "bwd" ) local toggle = self:GetClientNumber( "toggle" ) local limit = self:GetClientNumber( "forcelimit" ) local Ent1, Ent2 = self:GetEnt( 1 ), self:GetEnt( 2 ) local Bone1, Bone2 = self:GetBone( 1 ), self:GetBone( 2 ) local LPos1, LPos2 = self:GetLocalPos( 1 ), self:GetLocalPos( 2 ) local Norm1, Norm2 = self:GetNormal( 1 ), self:GetNormal( 2 ) local Phys1 = self:GetPhys( 1 ) local WPos2 = self:GetPos( 2 ) -- Note: To keep stuff ragdoll friendly try to treat things as physics objects rather than entities local Ang1, Ang2 = Norm1:Angle(), ( -Norm2 ):Angle() local TargetAngle = Phys1:AlignAngles( Ang1, Ang2 ) Phys1:SetAngles( TargetAngle ) -- Move the object so that the hitpos on our object is at the second hitpos local TargetPos = WPos2 + ( Phys1:GetPos() - self:GetPos( 1 ) ) + ( Norm2 * 0.2 ) -- Set the position Phys1:SetPos( TargetPos ) -- Wake up the physics object so that the entity updates Phys1:Wake() -- Set the hinge Axis perpendicular to the trace hit surface LPos1 = Phys1:WorldToLocal( WPos2 + Norm2 * 64 ) local constraint, axis = constraint.Motor( Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, friction, torque, time, nocollide, toggle, self:GetOwner(), limit, forekey, backkey, 1 ) undo.Create( "Motor" ) undo.AddEntity( axis ) undo.AddEntity( constraint ) undo.SetPlayer( self:GetOwner() ) undo.Finish() self:GetOwner():AddCleanup( "constraints", axis ) self:GetOwner():AddCleanup( "constraints", constraint ) -- Clear the objects so we're ready to go again self:ClearObjects() self:ReleaseGhostEntity() else self:StartGhostEntity( trace.Entity ) self:SetStage( iNum + 1 ) end return true end function TOOL:Reload( trace ) if ( !IsValid( trace.Entity ) || trace.Entity:IsPlayer() ) then return false end if ( CLIENT ) then return true end return constraint.RemoveConstraints( trace.Entity, "Motor" ) end function TOOL:Think() if ( self:NumObjects() != 1 ) then return end self:UpdateGhostEntity() end function TOOL:Holster() self:ClearObjects() end local ConVarsDefault = TOOL:BuildConVarList() function TOOL.BuildCPanel( CPanel ) CPanel:AddControl( "Header", { Description = "#tool.motor.help" } ) CPanel:AddControl( "ComboBox", { MenuButton = 1, Folder = "motor", Options = { [ "#preset.default" ] = ConVarsDefault }, CVars = table.GetKeys( ConVarsDefault ) } ) CPanel:AddControl( "Numpad", { Label = "#tool.motor.numpad1", Command = "motor_fwd", Label2 = "#tool.motor.numpad2", Command2 = "motor_bwd" } ) CPanel:AddControl( "Slider", { Label = "#tool.motor.torque", Command = "motor_torque", Type = "Float", Min = 0, Max = 10000 } ) CPanel:AddControl( "Slider", { Label = "#tool.forcelimit", Command = "motor_forcelimit", Type = "Float", Min = 0, Max = 50000, Help = true } ) CPanel:AddControl( "Slider", { Label = "#tool.hingefriction", Command = "motor_friction", Type = "Float", Min = 0, Max = 100, Help = true } ) CPanel:AddControl( "Slider", { Label = "#tool.motor.forcetime", Command = "motor_forcetime", Type = "Float", Min = 0, Max = 120, Help = true } ) CPanel:AddControl( "CheckBox", { Label = "#tool.nocollide", Command = "motor_nocollide", Help = true } ) CPanel:AddControl( "CheckBox", { Label = "#tool.toggle", Command = "motor_toggle", Help = true } ) end
mit
zegotinha/LiveShift
vlclib/windows/lua/modules/simplexml.lua
4
3833
--[==========================================================================[ simplexml.lua: Lua simple xml parser wrapper --[==========================================================================[ Copyright (C) 2010 Antoine Cellerier $Id$ Authors: Antoine Cellerier <dionoea at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]==========================================================================] module("simplexml",package.seeall) --[[ Returns the xml tree structure -- Each node is of one of the following types: -- { name (string), attributes (key->value map), children (node array) } -- text content (string) --]] local function parsexml(stream, errormsg) if not stream then return nil, errormsg end local xml = vlc.xml() local reader = xml:create_reader(stream) local tree local parents = {} while reader:read() > 0 do local nodetype = reader:node_type() --print(nodetype, reader:name()) if nodetype == 'startelem' then local name = reader:name() local node = { name= '', attributes= {}, children= {} } node.name = name while reader:next_attr() == 0 do node.attributes[reader:name()] = reader:value() end if tree then table.insert(tree.children, node) table.insert(parents, tree) end tree = node elseif nodetype == 'endelem' then if #parents > 0 then local name = reader:name() local tmp = {} --print(name, tree.name, #parents) while name ~= tree.name do if #parents == 0 then error("XML parser error/faulty logic") end local child = tree tree = parents[#parents] table.remove(parents) table.remove(tree.children) table.insert(tmp, 1, child) for i, node in pairs(child.children) do table.insert(tmp, i+1, node) end child.children = {} end for _, node in pairs(tmp) do table.insert(tree.children, node) end tree = parents[#parents] table.remove(parents) end elseif nodetype == 'text' then table.insert(tree.children, reader:value()) end end if #parents > 0 then error("XML parser error/Missing closing tags") end return tree end function parse_url(url) return parsexml(vlc.stream(url)) end function parse_string(str) return parsexml(vlc.memory_stream(str)) end function add_name_maps(tree) tree.children_map = {} for _, node in pairs(tree.children) do if type(node) == "table" then if not tree.children_map[node.name] then tree.children_map[node.name] = {} end table.insert(tree.children_map[node.name], node) add_name_maps(node) end end end
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/spells/bluemagic/light_of_penance.lua
12
2380
----------------------------------------- -- Spell: Light of Penance -- Reduces an enemy's TP. Additional effect: Blindness and "Bind" -- Spell cost: 53 MP -- Monster Type: Beastmen -- Spell Type: Magical (Light) -- Blue Magic Points: 5 -- Stat Bonus: CHR+1, HP+15 -- Level: 58 -- Casting Time: 3 seconds -- Recast Time: 60 seconds -- Magic Bursts on: Transfixion, Fusion, and Light -- Combos: Auto Refresh ----------------------------------------- require("scripts/globals/bluemagic") require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local typeEffectOne = dsp.effect.BLINDNESS local typeEffectTwo = dsp.effect.BIND local params = {} params.diff = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT) params.attribute = dsp.mod.INT params.skillType = dsp.skill.BLUE_MAGIC params.bonus = 1.0 local resist = applyResistance(caster, target, spell, params) local duration = 30 * resist local power = 100 * resist local returnEffect = typeEffectOne if (resist >= 0.5) then if (target:isFacing(caster)) then if (target:hasStatusEffect(typeEffectOne) and target:hasStatusEffect(typeEffectTwo) and target:getTP() == 0) then spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) -- no effect elseif (target:hasStatusEffect(typeEffectOne) and target:hasStatusEffect(typeEffectTwo)) then target:delTP(power) spell:setMsg(dsp.msg.basic.MAGIC_TP_REDUCE) elseif (target:hasStatusEffect(typeEffectOne)) then target:addStatusEffect(typeEffectTwo,1,0,duration) target:delTP(power) returnEffect = typeEffectTwo -- make it return bind message if blind can't be inflicted spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS) else target:addStatusEffect(typeEffectOne,50,0,duration) target:addStatusEffect(typeEffectTwo,1,0,duration) target:delTP(power) spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS) end else spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end end return returnEffect end
gpl-3.0
lichtl/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/qm7.lua
57
2181
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: qm7 (??? - Ancient Papyrus Shreds) -- Involved in Quest: In Defiant Challenge -- @pos 105.275 -32 92.551 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(ANCIENT_PAPYRUS_SHRED1); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED1); end if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1088, 1); player:messageSpecial(ITEM_OBTAINED, 1088); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088); end end if (player:hasItem(1088)) then player:delKeyItem(ANCIENT_PAPYRUS_SHRED1); player:delKeyItem(ANCIENT_PAPYRUS_SHRED2); player:delKeyItem(ANCIENT_PAPYRUS_SHRED3); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
lichtl/darkstar
scripts/globals/mobskills/Tourbillion.lua
31
1404
--------------------------------------------- -- Tourbillion -- -- Description: Delivers an area attack. Additional effect duration varies with TP. Additional effect: Weakens defense. -- Type: Physical -- Shadow per hit -- Range: Unknown range --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1805) then return 0; else return 1; end end --[[TODO: Khimaira should only use this when its wings are up, which is animationsub() == 0. There's no system to put them "down" yet, so it's not really fair to leave it active. Tyger's fair game, though. :)]] return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 3; local accmod = 1; local dmgmod = 1.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local duration = 20 * (skill:getTP() / 1000); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_DEFENSE_DOWN, 20, 0, duration); target:delHP(dmg); return dmg; end;
gpl-3.0
lichtl/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Despachiaire.lua
14
2761
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Despachiaire -- @pos 108 -40 -83 26 ----------------------------------- require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentCOPMission = player:getCurrentMission(COP); local LouverancePathStatut = player:getVar("COP_Louverance_s_Path"); if (currentCOPMission == THE_LOST_CITY and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0066); elseif (currentCOPMission == SHELTERING_DOUBT and player:getVar("PromathiaStatus") == 1) then player:startEvent(0x006C); elseif (currentCOPMission == THE_ENDURING_TUMULT_OF_WAR and player:getVar("COP_optional_CS_Despachaire") == 0) then player:startEvent(0x0075); --117 elseif (currentCOPMission == THREE_PATHS and LouverancePathStatut == 0) then player:startEvent(0x0076); elseif (currentCOPMission == THREE_PATHS and LouverancePathStatut == 1 ) then player:startEvent(0x0086); else player:startEvent(0x006A); end end; --Despachiaire 102 ++ --Despachiaire 104 ++ --Despachiaire 106 ++ --Despachiaire 107 ++ --Despachiaire 108 ++ --Despachiaire 110 ++ --Despachiaire 112 ++ --Despachiaire 117 ++ --Despachiaire 118 ++ --Despachiaire 132 --Despachiaire 133 --Despachiaire 134 ?? --Despachiaire 139 --Despachiaire 144 chat --Despachiaire 149 XX --Despachiaire 315 chat --Despachiaire 317 chat --Despachiaire 318 chat --Despachiaire 505 CS --Despachiaire 517 CS (despachiaire's wife) --Despachiaire 518 CS (ulmia mother) --Despachiaire 576 CS --Despachiaire 577 chat --Despachiaire 578 chat --Despachiaire 579 chat --Despachiaire 617 XX --Despachiaire 618 XX ----------------------------------- -- 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 == 0x0066 or csid == 0x006C) then player:setVar("PromathiaStatus",2); elseif (csid == 0x0075) then player:setVar("COP_optional_CS_Despachaire",1); elseif (csid == 0x0076) then player:setVar("COP_Louverance_s_Path",1); end end;
gpl-3.0
lichtl/darkstar
scripts/globals/spells/bluemagic/tail_slap.lua
21
2101
----------------------------------------- -- Spell: Tail Slap -- Delivers an area attack. Additional effect: "Stun." Damage varies with TP -- Spell cost: 77 MP -- Monster Type: Beastmen -- Spell Type: Physical (Blunt) -- Blue Magic Points: 4 -- Stat Bonus: MND+2 -- Level: 69 -- Casting Time: 1 seconds -- Recast Time: 28.5 seconds -- Skillchain Element: Water (can open Impaction and Induration; can close Reverberation and Fragmentation) -- Combos: Store TP ----------------------------------------- require("scripts/globals/bluemagic"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local resist = applyResistanceEffect(caster,spell,target,dINT,SKILL_BLU,0,EFFECT_STUN) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ATTACK; params.dmgtype = DMGTYPE_H2H; params.scattr = SC_REVERBERATION; params.numhits = 1; params.multiplier = 1.625; params.tp150 = 1.625; params.tp300 = 1.625; params.azuretp = 1.625; params.duppercap = 75; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; local damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if (resist > 0.5) then -- This line may need adjusting for retail accuracy. target:addStatusEffect(EFFECT_STUN, 1, 0, 5 * resist); -- pre-resist duration needs confirmed/adjusted end return damage; end;
gpl-3.0
lichtl/darkstar
scripts/commands/exec.lua
54
1121
--------------------------------------------------------------------------------------------------- -- func: exec -- desc: Allows you to execute a Lua string directly from chat. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 4, parameters = "s" }; function onTrigger(player, str) -- Ensure a command was given.. if (str == nil or string.len(str) == 0) then player:PrintToPlayer("You must enter a string to execute."); return; end -- For safety measures we will nuke the os table.. local old_os = os; os = nil; -- Ensure the command compiles / is valid.. local scriptObj, err = loadstring(str); if (scriptObj == nil) then player:PrintToPlayer("Failed to load the given string."); player:PrintToPlayer(err); os = old_os; return; end -- Execute the string.. local status, err = pcall(scriptObj); if (status == false) then player:PrintToPlayer(err); end -- Restore the os table.. os = old_os; end
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/RuLude_Gardens/npcs/_6r8.lua
9
1986
----------------------------------- -- Area: Ru'Lud Gardens -- Door: Windurstian Ambassador -- Windurst Missions 3.3 "A New Journey" and 4.1 "Magicite" -- !pos 31 9 -22 243 ----------------------------------- local ID = require("scripts/zones/RuLude_Gardens/IDs") require("scripts/globals/keyitems") require("scripts/globals/missions") ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) local pNation = player:getNation() if pNation == dsp.nation.WINDURST then local currentMission = player:getCurrentMission(pNation) local MissionStatus = player:getCharVar("MissionStatus") if currentMission == dsp.mission.id.windurst.A_NEW_JOURNEY and MissionStatus == 4 then player:startEvent(40) elseif player:getRank() == 4 and currentMission == dsp.mission.id.windurst.NONE and getMissionRankPoints(player,13) == 1 then if player:hasKeyItem(dsp.ki.ARCHDUCAL_AUDIENCE_PERMIT) then player:startEvent(131,1) else player:startEvent(131) end elseif player:getRank() >= 4 then player:messageSpecial(ID.text.RESTRICTED) else player:messageSpecial(ID.text.RESTRICTED+1) -- you have no letter of introduction end else player:messageSpecial(ID.text.RESTRICTED+1) -- you have no letter of introduction end return 1 end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if csid == 40 then finishMissionTimeline(player,1,csid,option) elseif csid == 131 and option == 1 then player:setCharVar("MissionStatus",1) if not player:hasKeyItem(dsp.ki.ARCHDUCAL_AUDIENCE_PERMIT) then player:addKeyItem(dsp.ki.ARCHDUCAL_AUDIENCE_PERMIT) player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.ARCHDUCAL_AUDIENCE_PERMIT) end end end
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/abilities/ice_maneuver.lua
9
1877
----------------------------------- -- Ability: Ice Maneuver -- Enhances the effect of ice attachments. Must have animator equipped. -- Obtained: Puppetmaster level 1 -- Recast Time: 10 seconds (shared with all maneuvers) -- Duration: 1 minute ----------------------------------- require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/utils") ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getWeaponSubSkillType(dsp.slot.RANGED) == 10 and not player:hasStatusEffect(dsp.effect.OVERLOAD) and player:getPet()) then return 0,0 else return 71,0 end end function onUseAbility(player,target,ability) local burden = 15 if (target:getStat(dsp.mod.INT) < target:getPet():getStat(dsp.mod.INT)) then burden = 20 end local overload = target:addBurden(dsp.magic.ele.ICE-1, burden) if (overload ~= 0 and (player:getMod(dsp.mod.PREVENT_OVERLOAD) > 0 or player:getPet():getMod(dsp.mod.PREVENT_OVERLOAD) > 0) and player:delStatusEffectSilent(dsp.effect.WATER_MANEUVER)) then overload = 0 end if (overload ~= 0) then target:removeAllManeuvers() target:addStatusEffect(dsp.effect.OVERLOAD, 0, 0, overload) else local level if (target:getMainJob() == dsp.job.PUP) then level = target:getMainLvl() else level = target:getSubLvl() end local bonus = 1 + (level/15) + target:getMod(dsp.mod.MANEUVER_BONUS) if (target:getActiveManeuvers() == 3) then target:removeOldestManeuver() end local dur = player:getPet():getLocalVar("MANEUVER_DURATION") target:addStatusEffect(dsp.effect.ICE_MANEUVER, bonus, 0, utils.clamp(dur,60,300)) end return dsp.effect.ICE_MANEUVER end
gpl-3.0
lichtl/darkstar
scripts/zones/Port_Bastok/npcs/Raifa.lua
14
1039
----------------------------------- -- Area: Port Bastok -- NPC: Raifa -- Type: Quest Giver -- @zone 236 -- @pos -166.416 -8.48 7.153 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0116); 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
sjznxd/lc-20130222
applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua
80
1397
--[[ Luci configuration model for statistics - collectd ping plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("Ping Plugin Configuration"), translate( "The ping plugin will send icmp echo replies to selected " .. "hosts and measure the roundtrip time for each host." )) -- collectd_ping config section s = m:section( NamedSection, "collectd_ping", "luci_statistics" ) -- collectd_ping.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_ping.hosts (Host) hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space.")) hosts.default = "127.0.0.1" hosts:depends( "enable", 1 ) -- collectd_ping.ttl (TTL) ttl = s:option( Value, "TTL", translate("TTL for ping packets") ) ttl.isinteger = true ttl.default = 128 ttl:depends( "enable", 1 ) -- collectd_ping.interval (Interval) interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") ) interval.isinteger = true interval.default = 30 interval:depends( "enable", 1 ) return m
apache-2.0
sdkbox/sdkbox-facebook-sample-v2
samples/Lua/TestLua/Resources/luaScript/ParticleTest/ParticleTest.lua
7
43201
local SceneIdx = -1 local MAX_LAYER = 42 local emitter = nil local background = nil local labelAtlas = nil local titleLabel = nil local subtitleLabel = nil local baseLayer_entry = nil local s = CCDirector:sharedDirector():getWinSize() local function backAction() SceneIdx = SceneIdx - 1 if SceneIdx < 0 then SceneIdx = SceneIdx + MAX_LAYER end return CreateParticleLayer() end local function restartAction() return CreateParticleLayer() end local function nextAction() SceneIdx = SceneIdx + 1 SceneIdx = math.mod(SceneIdx, MAX_LAYER) return CreateParticleLayer() end local function backCallback(sender) local scene = CCScene:create() scene:addChild(backAction()) scene:addChild(CreateBackMenuItem()) CCDirector:sharedDirector():replaceScene(scene) end local function restartCallback(sender) local scene = CCScene:create() scene:addChild(restartAction()) scene:addChild(CreateBackMenuItem()) CCDirector:sharedDirector():replaceScene(scene) end local function nextCallback(sender) local scene = CCScene:create() scene:addChild(nextAction()) scene:addChild(CreateBackMenuItem()) CCDirector:sharedDirector():replaceScene(scene) end local function toggleCallback(sender) if emitter ~= nil then if emitter:getPositionType() == kCCPositionTypeGrouped then emitter:setPositionType(kCCPositionTypeFree) elseif emitter:getPositionType() == kCCPositionTypeFree then emitter:setPositionType(kCCPositionTypeRelative) elseif emitter:getPositionType() == kCCPositionTypeRelative then emitter:setPositionType(kCCPositionTypeGrouped) end end end local function setEmitterPosition() if emitter ~= nil then emitter:setPosition(s.width / 2, s.height / 2) end end local function update(dt) if emitter ~= nil then local str = "" .. emitter:getParticleCount() -- labelAtlas:setString("" .. str) end end local function baseLayer_onEnterOrExit(tag) local scheduler = CCDirector:sharedDirector():getScheduler() if tag == "enter" then baseLayer_entry = scheduler:scheduleScriptFunc(update, 0, false) elseif tag == "exit" then scheduler:unscheduleScriptEntry(baseLayer_entry) end end local function getBaseLayer() local layer = CCLayerColor:create(ccc4(127,127,127,255)) emitter = nil titleLabel = CCLabelTTF:create("", "Arial", 28) layer:addChild(titleLabel, 100, 1000) titleLabel:setPosition(s.width / 2, s.height - 50) subtitleLabel = CCLabelTTF:create("", "Arial", 16) layer:addChild(subtitleLabel, 100) subtitleLabel:setPosition(s.width / 2, s.height - 80) local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2) local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2) local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2) local item4 = CCMenuItemToggle:create(CCMenuItemFont:create("Free Movement")) item4:addSubItem(CCMenuItemFont:create("Relative Movement")) item4:addSubItem(CCMenuItemFont:create("Grouped Movement")) item1:registerScriptTapHandler(backCallback) item2:registerScriptTapHandler(restartCallback) item3:registerScriptTapHandler(nextCallback) item4:registerScriptTapHandler(toggleCallback) local menu = CCMenu:create() menu:addChild(item1) menu:addChild(item2) menu:addChild(item3) menu:addChild(item4) menu:setPosition(CCPointMake(0, 0)) item1:setPosition(CCPointMake(s.width/2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2)) item2:setPosition(CCPointMake(s.width/2, item2:getContentSize().height / 2)) item3:setPosition(CCPointMake(s.width/2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2)) item4:setPosition(ccp(0, 100)) item4:setAnchorPoint(ccp(0, 0)) layer:addChild(menu, 100) labelAtlas = CCLabelAtlas:create("0000", "fps_images.png", 12, 32, string.byte('.')) layer:addChild(labelAtlas, 100) labelAtlas:setPosition(ccp(s.width - 66, 50)) -- moving background background = CCSprite:create(s_back3) layer:addChild(background, 5) background:setPosition(ccp(s.width / 2, s.height - 180)) local move = CCMoveBy:create(4, ccp(300, 0)) local move_back = move:reverse() local seq = CCSequence:createWithTwoActions(move, move_back) background:runAction(CCRepeatForever:create(seq)) local function onTouchEnded(x, y) local pos = CCPointMake(0, 0) if background ~= nil then pos = background:convertToWorldSpace(CCPointMake(0, 0)) end if emitter ~= nil then local newPos = ccpSub(CCPointMake(x, y), pos) emitter:setPosition(newPos.x, newPos.y) end end local function onTouch(eventType, x, y) if eventType == "began" then return true else return onTouchEnded(x, y) end end layer:setTouchEnabled(true) layer:registerScriptTouchHandler(onTouch) layer:registerScriptHandler(baseLayer_onEnterOrExit) return layer end --------------------------------- -- ParticleReorder --------------------------------- local ParticleReorder_Order = nil local ParticleReorder_entry = nil local ParticleReorder_layer = nil local function reorderParticles(dt) update(dt) for i = 0, 1 do local parent = ParticleReorder_layer:getChildByTag(1000 + i) local child1 = parent:getChildByTag(1) local child2 = parent:getChildByTag(2) local child3 = parent:getChildByTag(3) if math.mod(ParticleReorder_Order, 3) == 0 then parent:reorderChild(child1, 1) parent:reorderChild(child2, 2) parent:reorderChild(child3, 3) elseif math.mod(ParticleReorder_Order, 3) == 1 then parent:reorderChild(child1, 3) parent:reorderChild(child2, 1) parent:reorderChild(child3, 2) elseif math.mod(ParticleReorder_Order, 3) == 2 then parent:reorderChild(child1, 2) parent:reorderChild(child2, 3) parent:reorderChild(child3, 1) end end ParticleReorder_Order = ParticleReorder_Order + 1 end local function ParticleReorder_onEnterOrExit(tag) local scheduler = CCDirector:sharedDirector():getScheduler() if tag == "enter" then ParticleReorder_entry = scheduler:scheduleScriptFunc(reorderParticles, 1.0, false) elseif tag == "exit" then scheduler:unscheduleScriptEntry(ParticleReorder_entry) end end local function ParticleReorder() ParticleReorder_layer = getBaseLayer() ParticleReorder_Order = 0 ParticleReorder_layer:setColor(ccc3(0, 0, 0)) ParticleReorder_layer:removeChild(background, true) background = nil local ignore = CCParticleSystemQuad:create("Particles/SmallSun.plist") local parent1 = CCNode:create() local parent2 = CCParticleBatchNode:createWithTexture(ignore:getTexture()) ignore:unscheduleUpdate() for i = 0, 1 do local parent = nil if i == 0 then parent = parent1 else parent = parent2 end local emitter1 = CCParticleSystemQuad:create("Particles/SmallSun.plist") emitter1:setStartColor(ccc4f(1,0,0,1)) emitter1:setBlendAdditive(false) local emitter2 = CCParticleSystemQuad:create("Particles/SmallSun.plist") emitter2:setStartColor(ccc4f(0,1,0,1)) emitter2:setBlendAdditive(false) local emitter3 = CCParticleSystemQuad:create("Particles/SmallSun.plist") emitter3:setStartColor(ccc4f(0,0,1,1)) emitter3:setBlendAdditive(false) local neg = nil if i == 0 then neg = 1 else neg = -1 end emitter1:setPosition(ccp( s.width / 2 - 30, s.height / 2 + 60 * neg)) emitter2:setPosition(ccp( s.width / 2, s.height / 2 + 60 * neg)) emitter3:setPosition(ccp( s.width / 2 + 30, s.height / 2 + 60 * neg)) parent:addChild(emitter1, 0, 1) parent:addChild(emitter2, 0, 2) parent:addChild(emitter3, 0, 3) ParticleReorder_layer:addChild(parent, 10, 1000 + i) end ParticleReorder_layer:registerScriptHandler(ParticleReorder_onEnterOrExit) titleLabel:setString("Reordering particles") subtitleLabel:setString("Reordering particles with and without batches batches") return ParticleReorder_layer end --------------------------------- -- ParticleBatchHybrid --------------------------------- local ParticleBatchHybrid_entry = nil local ParticleBatchHybrid_parent1 = nil local ParticleBatchHybrid_parent2 = nil local function switchRender(dt) update(dt) local cond = (emitter:getBatchNode() ~= nil) emitter:removeFromParentAndCleanup(false) local str = "Particle: Using new parent: " local newParent = nil if cond == true then newParent = ParticleBatchHybrid_parent2 str = str .. "CCNode" else newParent = ParticleBatchHybrid_parent1 str = str .. "CCParticleBatchNode" end newParent:addChild(emitter) cclog(str) end local function ParticleBatchHybrid_onEnterOrExit(tag) local scheduler = CCDirector:sharedDirector():getScheduler() if tag == "enter" then ParticleBatchHybrid_entry = scheduler:scheduleScriptFunc(switchRender, 2.0, false) elseif tag == "exit" then scheduler:unscheduleScriptEntry(ParticleBatchHybrid_entry) --emitter:release() end end local function ParticleBatchHybrid() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background, true) background = nil emitter = CCParticleSystemQuad:create("Particles/LavaFlow.plist") ---- emitter:retain() local batch = CCParticleBatchNode:createWithTexture(emitter:getTexture()) batch:addChild(emitter) layer:addChild(batch, 10) local node = CCNode:create() layer:addChild(node) ParticleBatchHybrid_parent1 = batch ParticleBatchHybrid_parent2 = node layer:registerScriptHandler(ParticleBatchHybrid_onEnterOrExit) titleLabel:setString("Paticle Batch") subtitleLabel:setString("Hybrid: batched and non batched every 2 seconds") return layer end --------------------------------- -- ParticleBatchMultipleEmitters --------------------------------- local function ParticleBatchMultipleEmitters() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background, true) background = nil local emitter1 = CCParticleSystemQuad:create("Particles/LavaFlow.plist") emitter1:setStartColor(ccc4f(1,0,0,1)) local emitter2 = CCParticleSystemQuad:create("Particles/LavaFlow.plist") emitter2:setStartColor(ccc4f(0,1,0,1)) local emitter3 = CCParticleSystemQuad:create("Particles/LavaFlow.plist") emitter3:setStartColor(ccc4f(0,0,1,1)) emitter1:setPosition(ccp(s.width / 1.25, s.height / 1.25)) emitter2:setPosition(ccp(s.width / 2, s.height / 2)) emitter3:setPosition(ccp(s.width / 4, s.height / 4)) local batch = CCParticleBatchNode:createWithTexture(emitter1:getTexture()) batch:addChild(emitter1, 0) batch:addChild(emitter2, 0) batch:addChild(emitter3, 0) layer:addChild(batch, 10) titleLabel:setString("Paticle Batch") subtitleLabel:setString("Multiple emitters. One Batch") return layer end --------------------------------- -- DemoFlower --------------------------------- local function DemoFlower() local layer = getBaseLayer() emitter = CCParticleFlower:create() -- emitter:retain() background:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_stars1)) setEmitterPosition() titleLabel:setString("ParticleFlower") return layer end --------------------------------- -- DemoGalaxy --------------------------------- local function DemoGalaxy() local layer = getBaseLayer() emitter = CCParticleGalaxy:create() -- emitter:retain() background:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire)) setEmitterPosition() titleLabel:setString("ParticleGalaxy") return layer end --------------------------------- -- DemoFirework --------------------------------- local function DemoFirework() local layer = getBaseLayer() emitter = CCParticleFireworks:create() -- emitter:retain() background:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_stars1)) setEmitterPosition() titleLabel:setString("ParticleFireworks") return layer end --------------------------------- -- DemoSpiral --------------------------------- local function DemoSpiral() local layer = getBaseLayer() emitter = CCParticleSpiral:create() -- emitter:retain() background:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire)) setEmitterPosition() titleLabel:setString("ParticleSpiral") return layer end --------------------------------- -- DemoSun --------------------------------- local function DemoSun() local layer = getBaseLayer() emitter = CCParticleSun:create() -- emitter:retain() background:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire)) setEmitterPosition() titleLabel:setString("ParticleSun") return layer end --------------------------------- -- DemoMeteor --------------------------------- local function DemoMeteor() local layer = getBaseLayer() emitter = CCParticleMeteor:create() -- emitter:retain() background:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire)) setEmitterPosition() titleLabel:setString("ParticleMeteor") return layer end --------------------------------- -- DemoFire --------------------------------- local function DemoFire() local layer = getBaseLayer() emitter = CCParticleFire:create() -- emitter:retain() background:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire)) local pos_x, pos_y = emitter:getPosition() emitter:setPosition(pos_x, 100) titleLabel:setString("ParticleFire") return layer end --------------------------------- -- DemoSmoke --------------------------------- local function DemoSmoke() local layer = getBaseLayer() emitter = CCParticleSmoke:create() -- emitter:retain() background:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire)) local pos_x, pos_y = emitter:getPosition() emitter:setPosition(pos_x, 100) setEmitterPosition() titleLabel:setString("ParticleSmoke") return layer end --------------------------------- -- DemoExplosion --------------------------------- local function DemoExplosion() local layer = getBaseLayer() emitter = CCParticleExplosion:create() -- emitter:retain() background:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_stars1)) emitter:setAutoRemoveOnFinish(true) setEmitterPosition() titleLabel:setString("ParticleExplosion") return layer end --------------------------------- -- DemoSnow --------------------------------- local function DemoSnow() local layer = getBaseLayer() emitter = CCParticleSnow:create() -- emitter:retain() background:addChild(emitter, 10) local pos_x, pos_y = emitter:getPosition() emitter:setPosition(pos_x, pos_y - 110) emitter:setLife(3) emitter:setLifeVar(1) -- gravity emitter:setGravity(CCPointMake(0, -10)) -- speed of particles emitter:setSpeed(130) emitter:setSpeedVar(30) local startColor = emitter:getStartColor() startColor.r = 0.9 startColor.g = 0.9 startColor.b = 0.9 emitter:setStartColor(startColor) local startColorVar = emitter:getStartColorVar() startColorVar.b = 0.1 emitter:setStartColorVar(startColorVar) emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife()) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_snow)) setEmitterPosition() titleLabel:setString("ParticleSnow") return layer end --------------------------------- -- DemoRain --------------------------------- local function DemoRain() local layer = getBaseLayer() emitter = CCParticleRain:create() -- emitter:retain() background:addChild(emitter, 10) local pos_x, pos_y = emitter:getPosition() emitter:setPosition(pos_x, pos_y - 100) emitter:setLife(4) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire)) setEmitterPosition() titleLabel:setString("ParticleRain") return layer end --------------------------------- -- DemoBigFlower --------------------------------- local function DemoBigFlower() local layer = getBaseLayer() emitter = CCParticleSystemQuad:new() emitter:initWithTotalParticles(50) emitter:autorelease() background:addChild(emitter, 10) ----emitter:release() -- win32 : use this line or remove this line and use autorelease() emitter:setTexture( CCTextureCache:sharedTextureCache():addImage(s_stars1) ) emitter:setDuration(-1) -- gravity emitter:setGravity(CCPointMake(0, 0)) -- angle emitter:setAngle(90) emitter:setAngleVar(360) -- speed of particles emitter:setSpeed(160) emitter:setSpeedVar(20) -- radial emitter:setRadialAccel(-120) emitter:setRadialAccelVar(0) -- tagential emitter:setTangentialAccel(30) emitter:setTangentialAccelVar(0) -- emitter position emitter:setPosition(160, 240) emitter:setPosVar(ccp(0, 0)) -- life of particles emitter:setLife(4) emitter:setLifeVar(1) -- spin of particles emitter:setStartSpin(0) emitter:setStartSizeVar(0) emitter:setEndSpin(0) emitter:setEndSpinVar(0) -- color of particles emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2)) emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2)) -- size, in pixels emitter:setStartSize(80.0) emitter:setStartSizeVar(40.0) emitter:setEndSize(kParticleStartSizeEqualToEndSize) -- emits per second emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife()) -- additive emitter:setBlendAdditive(true) setEmitterPosition() titleLabel:setString("ParticleBigFlower") return layer end --------------------------------- -- DemoRotFlower --------------------------------- local function DemoRotFlower() local layer = getBaseLayer() emitter = CCParticleSystemQuad:new() emitter:initWithTotalParticles(300) emitter:autorelease() background:addChild(emitter, 10) ----emitter:release() -- win32 : Remove this line emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_stars2)) -- duration emitter:setDuration(-1) -- gravity emitter:setGravity(ccp(0, 0)) -- angle emitter:setAngle(90) emitter:setAngleVar(360) -- speed of particles emitter:setSpeed(160) emitter:setSpeedVar(20) -- radial emitter:setRadialAccel(-120) emitter:setRadialAccelVar(0) -- tagential emitter:setTangentialAccel(30) emitter:setTangentialAccelVar(0) -- emitter position emitter:setPosition(160, 240) emitter:setPosVar(ccp(0, 0)) -- life of particles emitter:setLife(3) emitter:setLifeVar(1) -- spin of particles emitter:setStartSpin(0) emitter:setStartSpinVar(0) emitter:setEndSpin(0) emitter:setEndSpinVar(2000) -- color of particles emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2)) emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2)) -- size, in pixels emitter:setStartSize(30.0) emitter:setStartSizeVar(0) emitter:setEndSize(kParticleStartSizeEqualToEndSize) -- emits per second emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife()) -- additive emitter:setBlendAdditive(false) setEmitterPosition() titleLabel:setString("ParticleRotFlower") return layer end --------------------------------- -- DemoModernArt --------------------------------- local function DemoModernArt() local layer = getBaseLayer() emitter = CCParticleSystemQuad:new() emitter:initWithTotalParticles(1000) emitter:autorelease() background:addChild(emitter, 10) ----emitter:release() -- duration emitter:setDuration(-1) -- gravity emitter:setGravity(CCPointMake(0,0)) -- angle emitter:setAngle(0) emitter:setAngleVar(360) -- radial emitter:setRadialAccel(70) emitter:setRadialAccelVar(10) -- tagential emitter:setTangentialAccel(80) emitter:setTangentialAccelVar(0) -- speed of particles emitter:setSpeed(50) emitter:setSpeedVar(10) -- emitter position emitter:setPosition(s.width / 2, s.height / 2) emitter:setPosVar(ccp(0, 0)) -- life of particles emitter:setLife(2.0) emitter:setLifeVar(0.3) -- emits per frame emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife()) -- color of particles emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2)) emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2)) -- size, in pixels emitter:setStartSize(1.0) emitter:setStartSizeVar(1.0) emitter:setEndSize(32.0) emitter:setEndSizeVar(8.0) -- texture emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire)) -- additive emitter:setBlendAdditive(false) setEmitterPosition() titleLabel:setString("Varying size") return layer end --------------------------------- -- DemoRing --------------------------------- local function DemoRing() local layer = getBaseLayer() emitter = CCParticleFlower:create() -- emitter:retain() background:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_stars1)) emitter:setLifeVar(0) emitter:setLife(10) emitter:setSpeed(100) emitter:setSpeedVar(0) emitter:setEmissionRate(10000) setEmitterPosition() titleLabel:setString("Ring Demo") return layer end --------------------------------- -- ParallaxParticle --------------------------------- local function ParallaxParticle() local layer = getBaseLayer() background:getParent():removeChild(background, true) background = nil local p = CCParallaxNode:create() layer:addChild(p, 5) local p1 = CCSprite:create(s_back3) local p2 = CCSprite:create(s_back3) p:addChild(p1, 1, CCPointMake(0.5, 1), CCPointMake(0, 250)) p:addChild(p2, 2, CCPointMake(1.5, 1), CCPointMake(0, 50)) emitter = CCParticleFlower:create() -- emitter:retain() emitter:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire)) p1:addChild(emitter, 10) emitter:setPosition(250, 200) local par = CCParticleSun:create() p2:addChild(par, 10) par:setTexture(CCTextureCache:sharedTextureCache():addImage(s_fire)) local move = CCMoveBy:create(4, CCPointMake(300,0)) local move_back = move:reverse() local seq = CCSequence:createWithTwoActions(move, move_back) p:runAction(CCRepeatForever:create(seq)) titleLabel:setString("Parallax + Particles") return layer end --------------------------------- -- DemoParticleFromFile --------------------------------- local function DemoParticleFromFile(name) local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background, true) background = nil emitter = CCParticleSystemQuad:new() emitter:autorelease() local filename = "Particles/" .. name .. ".plist" emitter:initWithFile(filename) layer:addChild(emitter, 10) setEmitterPosition() titleLabel:setString(name) return layer end --------------------------------- -- RadiusMode1 --------------------------------- local function RadiusMode1() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background, true) background = nil emitter = CCParticleSystemQuad:new() emitter:initWithTotalParticles(200) layer:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage("Images/stars-grayscale.png")) -- duration emitter:setDuration(kCCParticleDurationInfinity) -- radius mode emitter:setEmitterMode(kCCParticleModeRadius) -- radius mode: start and end radius in pixels emitter:setStartRadius(0) emitter:setStartRadiusVar(0) emitter:setEndRadius(160) emitter:setEndRadiusVar(0) -- radius mode: degrees per second emitter:setRotatePerSecond(180) emitter:setRotatePerSecondVar(0) -- angle emitter:setAngle(90) emitter:setAngleVar(0) -- emitter position emitter:setPosition(s.width / 2, s.height / 2) emitter:setPosVar(ccp(0, 0)) -- life of particles emitter:setLife(5) emitter:setLifeVar(0) -- spin of particles emitter:setStartSpin(0) emitter:setStartSpinVar(0) emitter:setEndSpin(0) emitter:setEndSpinVar(0) -- color of particles emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2)) emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2)) -- size, in pixels emitter:setStartSize(32) emitter:setStartSizeVar(0) emitter:setEndSize(kCCParticleStartSizeEqualToEndSize) -- emits per second emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife()) -- additive emitter:setBlendAdditive(false) titleLabel:setString("Radius Mode: Spiral") return layer end --------------------------------- -- RadiusMode2 --------------------------------- local function RadiusMode2() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background, true) background = nil emitter = CCParticleSystemQuad:new() emitter:initWithTotalParticles(200) layer:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage("Images/stars-grayscale.png")) -- duration emitter:setDuration(kCCParticleDurationInfinity) -- radius mode emitter:setEmitterMode(kCCParticleModeRadius) -- radius mode: start and end radius in pixels emitter:setStartRadius(100) emitter:setStartRadiusVar(0) emitter:setEndRadius(kCCParticleStartRadiusEqualToEndRadius) emitter:setEndRadiusVar(0) -- radius mode: degrees per second emitter:setRotatePerSecond(45) emitter:setRotatePerSecondVar(0) -- angle emitter:setAngle(90) emitter:setAngleVar(0) -- emitter position emitter:setPosition(s.width / 2, s.height / 2) emitter:setPosVar(ccp(0, 0)) -- life of particles emitter:setLife(4) emitter:setLifeVar(0) -- spin of particles emitter:setStartSpin(0) emitter:setStartSpinVar(0) emitter:setEndSpin(0) emitter:setEndSpinVar(0) -- color of particles emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2)) emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2)) -- size, in pixels emitter:setStartSize(32) emitter:setStartSizeVar(0) emitter:setEndSize(kCCParticleStartSizeEqualToEndSize) -- emits per second emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife()) -- additive emitter:setBlendAdditive(false) titleLabel:setString("Radius Mode: Semi Circle") return layer end --------------------------------- -- Issue704 --------------------------------- local function Issue704() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background, true) background = nil emitter = CCParticleSystemQuad:new() emitter:initWithTotalParticles(100) layer:addChild(emitter, 10) emitter:setTexture(CCTextureCache:sharedTextureCache():addImage("Images/fire.png")) -- duration emitter:setDuration(kCCParticleDurationInfinity) -- radius mode emitter:setEmitterMode(kCCParticleModeRadius) -- radius mode: start and end radius in pixels emitter:setStartRadius(50) emitter:setStartRadiusVar(0) emitter:setEndRadius(kCCParticleStartRadiusEqualToEndRadius) emitter:setEndRadiusVar(0) -- radius mode: degrees per second emitter:setRotatePerSecond(0) emitter:setRotatePerSecondVar(0) -- angle emitter:setAngle(90) emitter:setAngleVar(0) -- emitter position emitter:setPosition(s.width / 2, s.height / 2) emitter:setPosVar(ccp(0, 0)) -- life of particles emitter:setLife(5) emitter:setLifeVar(0) -- spin of particles emitter:setStartSpin(0) emitter:setStartSpinVar(0) emitter:setEndSpin(0) emitter:setEndSpinVar(0) -- color of particles emitter:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setStartColorVar(ccc4f(0.5, 0.5, 0.5, 1.0)) emitter:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2)) emitter:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2)) -- size, in pixels emitter:setStartSize(16) emitter:setStartSizeVar(0) emitter:setEndSize(kCCParticleStartSizeEqualToEndSize) -- emits per second emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife()) -- additive emitter:setBlendAdditive(false) local rot = CCRotateBy:create(16, 360) emitter:runAction(CCRepeatForever:create(rot)) titleLabel:setString("Issue 704. Free + Rot") subtitleLabel:setString("Emitted particles should not rotate") return layer end --------------------------------- -- Issue870 --------------------------------- local Issue870_index = nil local Issue870_entry = nil local function updateQuads(dt) update(dt) Issue870_index = math.mod(Issue870_index + 1, 4) local rect = CCRectMake(Issue870_index * 32, 0, 32, 32) emitter:setTextureWithRect(emitter:getTexture(), rect) end local function Issue870_onEnterOrExit(tag) local scheduler = CCDirector:sharedDirector():getScheduler() if tag == "enter" then Issue870_entry = scheduler:scheduleScriptFunc(updateQuads, 2.0, false) elseif tag == "exit" then scheduler:unscheduleScriptEntry(Issue870_entry) end end local function Issue870() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background, true) background = nil local system = CCParticleSystemQuad:new() system:initWithFile("Particles/SpinningPeas.plist") system:setTextureWithRect(CCTextureCache:sharedTextureCache():addImage("Images/particles.png"), CCRectMake(0,0,32,32)) layer:addChild(system, 10) emitter = system Issue870_index = 0 layer:registerScriptHandler(Issue870_onEnterOrExit) titleLabel:setString("Issue 870. SubRect") subtitleLabel:setString("Every 2 seconds the particle should change") return layer end --------------------------------- -- MultipleParticleSystems --------------------------------- local function MultipleParticleSystems() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background, true) background = nil CCTextureCache:sharedTextureCache():addImage("Images/particles.png") for i = 0, 4 do local particleSystem = CCParticleSystemQuad:create("Particles/SpinningPeas.plist") particleSystem:setPosition(i * 50, i * 50) particleSystem:setPositionType(kCCPositionTypeGrouped) layer:addChild(particleSystem) end emitter = nil titleLabel:setString("Multiple particle systems") subtitleLabel:setString("v1.1 test: FPS should be lower than next test") return layer end --------------------------------- -- MultipleParticleSystemsBatched --------------------------------- local function MultipleParticleSystemsBatched() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background, true) background = nil local batchNode = CCParticleBatchNode:createWithTexture(nil, 3000) layer:addChild(batchNode, 1, 2) for i = 0, 4 do local particleSystem = CCParticleSystemQuad:create("Particles/SpinningPeas.plist") particleSystem:setPositionType(kCCPositionTypeGrouped) particleSystem:setPosition(i * 50, i * 50) batchNode:setTexture(particleSystem:getTexture()) batchNode:addChild(particleSystem) end emitter = nil titleLabel:setString("Multiple particle systems batched") subtitleLabel:setString("v1.1 test: should perform better than previous test") return layer end --------------------------------- -- AddAndDeleteParticleSystems --------------------------------- local AddAndDeleteParticleSystems_entry = nil local AddAndDeleteParticleSystems_batchNode = nil local function removeSystem(dt) update(dt) local ChildrenCount = AddAndDeleteParticleSystems_batchNode:getChildren():count() if ChildrenCount > 0 then cclog("remove random system") local rand = math.mod(math.random(1, 999999), ChildrenCount - 1) AddAndDeleteParticleSystems_batchNode:removeChild(AddAndDeleteParticleSystems_batchNode:getChildren():objectAtIndex(rand), true) --add new local particleSystem = CCParticleSystemQuad:create("Particles/Spiral.plist") particleSystem:setPositionType(kCCPositionTypeGrouped) particleSystem:setTotalParticles(200) particleSystem:setPosition(math.mod(math.random(1, 999999), 300) ,math.mod(math.random(1, 999999), 400)) cclog("add a new system") local randZ = math.floor(math.random() * 100) AddAndDeleteParticleSystems_batchNode:addChild(particleSystem, randZ, -1) end end local function AddAndDeleteParticleSystems_onEnterOrExit(tag) local scheduler = CCDirector:sharedDirector():getScheduler() if tag == "enter" then AddAndDeleteParticleSystems_entry = scheduler:scheduleScriptFunc(removeSystem, 2.0, false) elseif tag == "exit" then scheduler:unscheduleScriptEntry(AddAndDeleteParticleSystems_entry) end end local function AddAndDeleteParticleSystems() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background, true) background = nil --adds the texture inside the plist to the texture cache AddAndDeleteParticleSystems_batchNode = CCParticleBatchNode:createWithTexture(nil, 16000) layer:addChild(AddAndDeleteParticleSystems_batchNode, 1, 2) for i = 0, 5 do local particleSystem = CCParticleSystemQuad:create("Particles/Spiral.plist") AddAndDeleteParticleSystems_batchNode:setTexture(particleSystem:getTexture()) particleSystem:setPositionType(kCCPositionTypeGrouped) particleSystem:setTotalParticles(200) particleSystem:setPosition(i * 15 + 100, i * 15 + 100) local randZ = math.floor(math.random() * 100) AddAndDeleteParticleSystems_batchNode:addChild(particleSystem, randZ, -1) end layer:registerScriptHandler(AddAndDeleteParticleSystems_onEnterOrExit) emitter = nil titleLabel:setString("Add and remove Particle System") subtitleLabel:setString("v1.1 test: every 2 sec 1 system disappear, 1 appears") return layer end --------------------------------- -- ReorderParticleSystems * -- problem --------------------------------- local ReorderParticleSystems_entry = nil local ReorderParticleSystems_batchNode = nil local function reorderSystem(dt) update(dt) local child = ReorderParticleSystems_batchNode:getChildren():randomObject() -- problem: there's no getZOrder() for CCObject -- ReorderParticleSystems_batchNode:reorderChild(child, child:getZOrder() - 1) ReorderParticleSystems_batchNode:reorderChild(child, math.random(0, 99999)) end local function ReorderParticleSystems_onEnterOrExit(tag) local scheduler = CCDirector:sharedDirector():getScheduler() if tag == "enter" then ReorderParticleSystems_entry = scheduler:scheduleScriptFunc(reorderSystem, 2.0, false) elseif tag == "exit" then scheduler:unscheduleScriptEntry(ReorderParticleSystems_entry) end end local function ReorderParticleSystems() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background ,true) background = nil ReorderParticleSystems_batchNode = CCParticleBatchNode:create("Images/stars-grayscale.png", 3000) layer:addChild(ReorderParticleSystems_batchNode, 1, 2) for i = 0, 2 do local particleSystem = CCParticleSystemQuad:new() particleSystem:initWithTotalParticles(200) particleSystem:setTexture(ReorderParticleSystems_batchNode:getTexture()) -- duration particleSystem:setDuration(kCCParticleDurationInfinity) -- radius mode particleSystem:setEmitterMode(kCCParticleModeRadius) -- radius mode: 100 pixels from center particleSystem:setStartRadius(100) particleSystem:setStartRadiusVar(0) particleSystem:setEndRadius(kCCParticleStartRadiusEqualToEndRadius) particleSystem:setEndRadiusVar(0) -- not used when start == end -- radius mode: degrees per second -- 45 * 4 seconds of life = 180 degrees particleSystem:setRotatePerSecond(45) particleSystem:setRotatePerSecondVar(0) -- angle particleSystem:setAngle(90) particleSystem:setAngleVar(0) -- emitter position particleSystem:setPosVar(ccp(0, 0)) -- life of particles particleSystem:setLife(4) particleSystem:setLifeVar(0) -- spin of particles particleSystem:setStartSpin(0) particleSystem:setStartSpinVar(0) particleSystem:setEndSpin(0) particleSystem:setEndSpinVar(0) -- color of particles local startColor = ccColor4F:new() startColor.r = 0 startColor.g = 0 startColor.b = 0 startColor.a = 1 if i == 0 then startColor.r = 1 elseif i == 1 then startColor.g = 1 elseif i == 2 then startColor.b = 1 end particleSystem:setStartColor(startColor) particleSystem:setStartColorVar(ccc4f(0, 0, 0, 0)) local endColor = startColor particleSystem:setEndColor(endColor) particleSystem:setEndColorVar(ccc4f(0, 0, 0, 0)) -- size, in pixels particleSystem:setStartSize(32) particleSystem:setStartSizeVar(0) particleSystem:setEndSize(kCCParticleStartSizeEqualToEndSize) -- emits per second particleSystem:setEmissionRate(particleSystem:getTotalParticles() / particleSystem:getLife()) -- additive particleSystem:setPosition(i * 10 + 120, 200) ReorderParticleSystems_batchNode:addChild(particleSystem) particleSystem:setPositionType(kCCPositionTypeFree) particleSystem:release() end layer:registerScriptHandler(ReorderParticleSystems_onEnterOrExit) emitter = nil titleLabel:setString("reorder systems") subtitleLabel:setString("changes every 2 seconds") return layer end --------------------------------- -- PremultipliedAlphaTest --------------------------------- local function PremultipliedAlphaTest() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 255)) layer:removeChild(background, true) background = nil emitter = CCParticleSystemQuad:create("Particles/BoilingFoam.plist") local tBlendFunc = ccBlendFunc:new() tBlendFunc.src = 1 --GL_ONE tBlendFunc.dst = 0x0303 --GL_ONE_MINUS_SRC_ALPHA emitter:setBlendFunc(tBlendFunc) --assert(emitter:getOpacityModifyRGB(), "Particle texture does not have premultiplied alpha, test is useless") emitter:setStartColor(ccc4f(1, 1, 1, 1)) emitter:setEndColor(ccc4f(1, 1, 1, 0)) emitter:setStartColorVar(ccc4f(0, 0, 0, 0)) emitter:setEndColorVar(ccc4f(0, 0, 0, 0)) layer:addChild(emitter, 10) titleLabel:setString("premultiplied alpha") subtitleLabel:setString("no black halo, particles should fade out") return layer end --------------------------------- -- PremultipliedAlphaTest2 --------------------------------- local function PremultipliedAlphaTest2() local layer = getBaseLayer() layer:setColor(ccc3(0, 0, 0)) layer:removeChild(background, true) background = nil emitter = CCParticleSystemQuad:create("Particles/TestPremultipliedAlpha.plist") layer:addChild(emitter ,10) titleLabel:setString("premultiplied alpha 2") subtitleLabel:setString("Arrows should be faded") return layer end --------------------------------- -- Particle Test --------------------------------- function CreateParticleLayer() if SceneIdx == 0 then return ParticleReorder() elseif SceneIdx == 1 then return ParticleBatchHybrid() elseif SceneIdx == 2 then return ParticleBatchMultipleEmitters() elseif SceneIdx == 3 then return DemoFlower() elseif SceneIdx == 4 then return DemoGalaxy() elseif SceneIdx == 5 then return DemoFirework() elseif SceneIdx == 6 then return DemoSpiral() elseif SceneIdx == 7 then return DemoSun() elseif SceneIdx == 8 then return DemoMeteor() elseif SceneIdx == 9 then return DemoFire() elseif SceneIdx == 10 then return DemoSmoke() elseif SceneIdx == 11 then return DemoExplosion() elseif SceneIdx == 12 then return DemoSnow() elseif SceneIdx == 13 then return DemoRain() elseif SceneIdx == 14 then return DemoBigFlower() elseif SceneIdx == 15 then return DemoRotFlower() elseif SceneIdx == 16 then return DemoModernArt() elseif SceneIdx == 17 then return DemoRing() elseif SceneIdx == 18 then return ParallaxParticle() elseif SceneIdx == 19 then return DemoParticleFromFile("BoilingFoam") elseif SceneIdx == 20 then return DemoParticleFromFile("BurstPipe") elseif SceneIdx == 21 then return DemoParticleFromFile("Comet") elseif SceneIdx == 22 then return DemoParticleFromFile("debian") elseif SceneIdx == 23 then return DemoParticleFromFile("ExplodingRing") elseif SceneIdx == 24 then return DemoParticleFromFile("LavaFlow") elseif SceneIdx == 25 then return DemoParticleFromFile("SpinningPeas") elseif SceneIdx == 26 then return DemoParticleFromFile("SpookyPeas") elseif SceneIdx == 27 then return DemoParticleFromFile("Upsidedown") elseif SceneIdx == 28 then return DemoParticleFromFile("Flower") elseif SceneIdx == 29 then return DemoParticleFromFile("Spiral") elseif SceneIdx == 30 then return DemoParticleFromFile("Galaxy") elseif SceneIdx == 31 then return DemoParticleFromFile("Phoenix") elseif SceneIdx == 32 then return DemoParticleFromFile("lines") elseif SceneIdx == 33 then return RadiusMode1() elseif SceneIdx == 34 then return RadiusMode2() elseif SceneIdx == 35 then return Issue704() elseif SceneIdx == 36 then return Issue870() --elseif SceneIdx == 36 then return Issue1201() -- v1.1 tests elseif SceneIdx == 37 then return MultipleParticleSystems() elseif SceneIdx == 38 then return MultipleParticleSystemsBatched() elseif SceneIdx == 39 then return AddAndDeleteParticleSystems() elseif SceneIdx == 40 then return ReorderParticleSystems() elseif SceneIdx == 41 then return PremultipliedAlphaTest() elseif SceneIdx == 42 then return PremultipliedAlphaTest2() end end function ParticleTest() cclog("ParticleTest") local scene = CCScene:create() SceneIdx = -1 scene:addChild(nextAction()) scene:addChild(CreateBackMenuItem()) return scene end
mit
lichtl/darkstar
scripts/globals/spells/aisha_ichi.lua
27
1608
----------------------------------------- -- Spell: Aisha: Ichi ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_ATTACK_DOWN; -- Base Stats local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Duration Calculation local resist = applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); --Base power is 15 and is not affected by resistaces. local power = 15; --Calculates Resist Chance if (resist >= 0.125) then local duration = 120 * resist; if (duration >= 50) then -- Erases a weaker attack down and applies the stronger one local attackdown = target:getStatusEffect(effect); if (attackdown ~= nil) then if (attackdown:getPower() < power) then target:delStatusEffect(effect); target:addStatusEffect(effect,power,0,duration); spell:setMsg(237); else -- no effect spell:setMsg(75); end else target:addStatusEffect(effect,power,0,duration); spell:setMsg(237); end else spell:setMsg(85); end else spell:setMsg(284); end return effect; end;
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/mobskills/abyss_blast.lua
11
1085
--------------------------------------------- -- Abyss Blast -- -- Description: Blasts a single target with dark energy. Additional effect: Blind -- Type: Magical -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown -- Notes: Blinds target --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local typeEffect = dsp.effect.BLINDNESS local power = 15 local duration = 120 MobStatusEffectMove(mob, target, typeEffect, power, 0, duration) local dmgmod = 1 local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,dsp.magic.ele.DARK,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.DARK,MOBPARAM_IGNORE_SHADOWS) target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.DARK) return dmg end
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/abilities/pets/attachments/strobe.lua
11
1471
----------------------------------- -- Attachment: Strobe -- http://forum.square-enix.com/ffxi/threads/49065?p=565264#post565264 -- Values are currently PRIOR TO NOVEMBER 2015 UPDATE! ----------------------------------- require("scripts/globals/automaton") require("scripts/globals/status") ----------------------------------- function onEquip(pet) updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 5) pet:addListener("AUTOMATON_ATTACHMENT_CHECK", "ATTACHMENT_STROBE", function(automaton, target) if automaton:getLocalVar("provoke") < VanadielTime() and (automaton:checkDistance(target) - target:getModelSize()) < 7 then automaton:useMobAbility(1945) else return 0 end end) end function onUnequip(pet) updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 0) pet:removeListener("ATTACHMENT_STROBE") end function onManeuverGain(pet, maneuvers) onUpdate(pet, maneuvers) end function onManeuverLose(pet, maneuvers) onUpdate(pet, maneuvers - 1) end function onUpdate(pet, maneuvers) if maneuvers == 0 then updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 5) elseif maneuvers == 1 then updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 10) elseif maneuvers == 2 then updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 15) elseif maneuvers == 3 then updateModPerformance(pet, dsp.mod.ENMITY, 'strobe_mod', 20) end end
gpl-3.0
scscgit/scsc_wildstar_addons
ChaChing/lib/GeminiAddon.lua
2
24902
--- GeminiAddon-1.0 -- Formerly DaiAddon -- Inspired by AceAddon -- Modules and packages embeds are based heavily on AceAddon's functionally, so credit goes their authors. -- -- Allows the addon to have modules -- Allows for packages to be embedded (if supported) into the addon and it's modules -- -- The core callbacks have been "renamed" for consumption that are used when creating an addon: -- OnLoad -> OnInitialize -- -- New callback: -- OnEnable - Called when the character has been loaded and is in the world. Called after OnInitialize and after Restore would have occured -- -- General flow should be: -- OnInitialize -> OnEnable local MAJOR, MINOR = "Gemini:Addon-1.1", 1 local APkg = Apollo.GetPackage(MAJOR) if APkg and (APkg.nVersion or 0) >= MINOR then return -- no upgrade is needed end local GeminiAddon = APkg and APkg.tPackage or {} local error, type, tostring, select, pairs = error, type, tostring, select, pairs local setmetatable, getmetatable, xpcall = setmetatable, getmetatable, xpcall local assert, loadstring, rawset, next, unpack = assert, loadstring, rawset, next, unpack local tinsert, tremove, ostime = table.insert, table.remove, os.time GeminiAddon.Addons = GeminiAddon.Addons or {} -- addon collection GeminiAddon.AddonStatus = GeminiAddon.AddonStatus or {} -- status of addons GeminiAddon.Timers = GeminiAddon.Timers or {} -- Timers for OnEnable local mtGenTable = { __index = function(tbl, key) tbl[key] = {} return tbl[key] end } -- per addon lists GeminiAddon.Embeds = GeminiAddon.Embeds or setmetatable({}, mtGenTable) GeminiAddon.InitializeQueue = GeminiAddon.InitializeQueue or setmetatable({}, mtGenTable) -- addons that are new and not initialized GeminiAddon.EnableQueue = GeminiAddon.EnableQueue or setmetatable({}, mtGenTable) -- addons awaiting to be enabled -- Check if the player unit is available local function IsPlayerInWorld() return GameLib.GetPlayerUnit() ~= nil end local tLibError = Apollo.GetPackage("Gemini:LibError-1.0") local fnErrorHandler = tLibError and tLibError.tPackage and tLibError.tPackage.Error or Print -- xpcall safecall implementation local function CreateDispatcher(argCount) local code = [[ local xpcall, eh = ... local method, ARGS local function call() return method(ARGS) end local function dispatch(func, ...) method = func if not method then return end ARGS = ... return xpcall(call, eh) end return dispatch ]] local ARGS = {} for i = 1, argCount do ARGS[i] = "arg"..i end code = code:gsub("ARGS", table.concat(ARGS, ", ")) return assert(loadstring(code, "safecall Dispatcher[" .. argCount .. "]"))(xpcall, fnErrorHandler) end local Dispatchers = setmetatable({}, {__index=function(self, argCount) local dispatcher = CreateDispatcher(argCount) rawset(self, argCount, dispatcher) return dispatcher end}) Dispatchers[0] = function(func) return xpcall(func, fnErrorHandler) end local function safecall(func, ...) if type(func) == "function" then return Dispatchers[select('#', ...)](func, ...) end end local function AddonToString(self) return self.Name end local Enable, Disable, Embed, GetName, SetEnabledState, AddonLog local EmbedModule, EnableModule, DisableModule, NewModule, GetModule, SetDefaultModulePrototype, SetDefaultModuleState, SetDefaultModulePackages -- delay the firing the OnEnable callback until after Character is in world -- and OnRestore would have occured local function DelayedEnable(oAddon) local strName = oAddon:GetName() if GameLib.GetPlayerUnit() == nil then -- If the Player Unit doesn't exist we wait for the CharacterCreated event instead GeminiAddon.Timers[strName] = nil Apollo.RegisterEventHandler("CharacterCreated", "___OnDelayEnable", oAddon) return end local tEnableQueue = GeminiAddon.EnableQueue[strName] while #tEnableQueue > 0 do local oAddonToEnable = tremove(tEnableQueue, 1) GeminiAddon:EnableAddon(oAddonToEnable) end -- Cleanup GeminiAddon.EnableQueue[strName] = nil GeminiAddon.Timers[strName] = nil Apollo.RemoveEventHandler("CharacterCreated", oAddon) oAddon.___OnDelayEnable = nil end local function NewAddonProto(strInitAddon, oAddonOrName, oNilOrName) local oAddon, strAddonName -- get addon name if type(oAddonOrName) == "table" then oAddon = oAddonOrName strAddonName = oNilOrName else strAddonName = oAddonOrName end oAddon = oAddon or {} oAddon.Name = strAddonName -- use existing metatable if exists local addonmeta = {} local oldmeta = getmetatable(oAddon) if oldmeta then for k,v in pairs(oldmeta) do addonmeta[k] = v end end addonmeta.__tostring = AddonToString setmetatable(oAddon, addonmeta) -- setup addon skeleton GeminiAddon.Addons[strAddonName] = oAddon oAddon.Modules = {} oAddon.OrderedModules = {} oAddon.DefaultModulePackages = {} -- Embed any packages that are needed Embed( oAddon ) -- Add to Queue of Addons to be Initialized during OnLoad tinsert(GeminiAddon.InitializeQueue[strInitAddon], oAddon) return oAddon end -- Create a new addon using GeminiAddon -- The final addon object will be returned. -- @paramsig [object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...] -- @param object Table to use as the base for the addon (optional) -- @param strAddonName Name of the addon object to create -- @param bOnConfigure Add a button to the options list and fire OnConfigure when clicked. Instead of issuing true, you can pass custom text for the button. -- @param tDependencies List of dependencies for the addon -- @param strPkgName List of packages to embed into the addon - requires the packages to be registered with Apollo.RegisterPackage and for the packages to support embedding -- @usage -- -- Create a simple addon -- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.0").tPackage:NewAddon("MyAddon", false) -- -- -- Create a simple addon with a configure button with custom text -- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.0").tPackage:NewAddon("MyAddon", "Addon Options Button") -- -- -- Create a simple addon with a configure button and a dependency on ChatLog / ChatLogEx -- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.0").tPackage:NewAddon("MyAddon", true, { "ChatLog", "ChatLogEx" }) -- -- -- Create an addon with a base object -- local tAddonBase = { config = { ... some default settings ... }, ... } -- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.0").tPackage:NewAddon(tAddonBase, "MyAddon", false) -- -- -- Create an addon with a base object with a dependency on ChatLog / ChatLogEx -- local tAddonBase = { config = { ... some default settings ... }, ... } -- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.0").tPackage:NewAddon(tAddonBase, "MyAddon", false, { "ChatLog", "ChatLogEx" }) function GeminiAddon:NewAddon(oAddonOrName, ...) local oAddon, strAddonName local oNilOrName = nil local i = 1 -- get addon name if type(oAddonOrName) == "table" then strAddonName = ... oNilOrName = strAddonName i = 2 else strAddonName = oAddonOrName end if type(strAddonName) ~= "string" then error(("Usage: NewAddon([object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...]): 'strAddonName' - string expected got '%s'."):format(type(strAddonName)), 2) end if self.Addons[strAddonName] then error(("Usage: NewAddon([object, ] strAddonName, bOnConfigure[, tDependencies][, strPkgName, ...]): 'strAddonName' - Addon '%s' already registered in GeminiAddon."):format(strAddonName), 2) end -- get configure state local strConfigBtnName = select(i, ...) i = i + 1 local bConfigure = (strConfigBtnName == true or type(strConfigBtnName) == "string") if bConfigure then strConfigBtnName = type(strConfigBtnName) == "boolean" and strAddonName or strConfigBtnName else strConfigBtnName = "" end -- get dependencies local tDependencies if select(i,...) and type(select(i, ...)) == "table" then tDependencies = select(i, ...) i = i + 1 else tDependencies = {} end local oAddon = NewAddonProto(strAddonName, oAddonOrName, oNilOrName) self:EmbedPackages(oAddon, select(i, ...)) -- Setup callbacks for the addon -- Setup the OnLoad callback handler to initialize the addon -- and delay enable the addon oAddon.OnLoad = function(self) local strName = self:GetName() local tInitQueue = GeminiAddon.InitializeQueue[strName] while #tInitQueue > 0 do local oAddonToInit = tremove(tInitQueue, 1) local retVal = GeminiAddon:InitializeAddon(oAddonToInit) if retVal ~= nil then Apollo.AddAddonErrorText(self, retVal) return retVal end tinsert(GeminiAddon.EnableQueue[strName], oAddonToInit) end GeminiAddon.InitializeQueue[strName] = nil self.___OnDelayEnable = function() DelayedEnable(self) end -- Wait 0 seconds (hah?) this allows OnRestore to have occured GeminiAddon.Timers[strName] = ApolloTimer.Create(0, false, "___OnDelayEnable",self) end -- Register with Apollo Apollo.RegisterAddon(oAddon, bConfigure, strConfigBtnName, tDependencies) return oAddon end -- Get the addon object by its name from the internal GeminiAddon addon registry -- Throws an error if the addon object cannot be found (except if silent is set) -- @param strAddonName the addon name registered with GeminiAddon -- @param bSilent return nil if addon is not found instead of throwing an error -- @usage -- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.0").tPackage:GetAddon("MyAddon") function GeminiAddon:GetAddon(strAddonName, bSilent) if not bSilent and not self.Addons[strAddonName] then error(("Usage: GetAddon(strAddonName): 'strAddonName' - Cannot find an GeminiAddon called '%s'."):format(tostring(strAddonName)), 2) end return self.Addons[strAddonName] end --- Enable the addon -- Used internally when the player has entered the world -- -- **Note:** do not call this manually -- @param oAddon addon object to enable function GeminiAddon:EnableAddon(oAddon) if type(oAddon) == "string" then oAddon = self:GetAddon(oAddon) end local strAddonName = AddonToString(oAddon) if self.AddonStatus[strAddonName] or not oAddon.EnabledState then return false end self.AddonStatus[strAddonName] = true safecall(oAddon.OnEnable, oAddon) if self.AddonStatus[strAddonName] then -- embed packages local tEmbeds = self.Embeds[oAddon] for i = 1, #tEmbeds do local APkg = Apollo.GetPackage(tEmbeds[i]) local oPkg = APkg and APkg.tPackage or nil if oPkg then safecall(oPkg.OnEmbedEnable, oPkg, oAddon) end end -- enable modules local tModules = oAddon.OrderedModules for i = 1, #tModules do oAddon:EnableModule(tModules[i].ModuleName) end end return self.AddonStatus[strAddonName] end function GeminiAddon:DisableAddon(oAddon) if type(oAddon) == "string" then oAddon = self:GetAddon(oAddon) end local strAddonName = AddonToString(oAddon) if not self.AddonStatus[strAddonName] then return false end safecall( addon.OnDisable, oAddon ) if self.AddonStatus[strAddonName] then local tEmbeds = self.Embeds[oAddon] for i = 1, #tEmbeds do local APkg = Apollo.GetPackage(tEmbeds[i]) local oPkg = APkg and APkg.tPackage or nil if oPkg then safecall(oPkg.OnEmbedDisable, oPkg, oAddon) end end local tModules = oAddon.OrderedModules for i = 1, #tModules do oAddon:DisableModule(tModules[i]) end end return not self.AddonStatus[strAddonName] end --- Initialize the addon after creation -- Used internally when OnLoad is called for the addon -- -- **Note:** do not call this manually -- @param oAddon addon object to initialize function GeminiAddon:InitializeAddon(oAddon) local _, retVal = safecall(oAddon.OnInitialize, oAddon) if retVal ~= nil then return retVal end local tEmbeds = self.Embeds[oAddon] for i = 1, #tEmbeds do local APkg = Apollo.GetPackage(tEmbeds[i]) local oPkg = APkg and APkg.tPackage or nil if oPkg then local _, retVal = safecall(oPkg.OnEmbedInitialize, oPkg, oAddon) if retVal ~= nil then return retVal end end end end --- Embed packages into the specified addon -- @paramsig oAddon[, strPkgName, ...] -- @param oAddon The addon object to embed packages in -- @param strPkgName List of packages to embed into the addon function GeminiAddon:EmbedPackages(oAddon, ...) for i = 1, select('#', ...) do local strPkgName = select(i, ...) self:EmbedPackage(oAddon, strPkgName, false, 4) end end --- Embed a package into the specified addon -- -- **Note:** This function is for internal use by :EmbedPackages -- @paramsig strAddonName, strPkgName[, silent[, offset]] -- @param oAddon addon object to embed the package in -- @param strPkgName name of the package to embed -- @param bSilent marks an embed to fail silently if the package doesn't exist (optional) -- @param nOffset will push the error messages back to said offset, defaults to 2 (optional) function GeminiAddon:EmbedPackage(oAddon, strPkgName, bSilent, nOffset) local APkg = Apollo.GetPackage(strPkgName) local oPkg = APkg and APkg.tPackage or nil if not oPkg and not bSilent then error(("Usage: EmbedPackage(oAddon, strPkgName, bSilent, nOffset): 'strPkgName' - Cannot find a package instance of '%s'."):format(tostring(strPkgName)), nOffset or 2) elseif oPkg and type(oPkg.Embed) == "function" then oPkg:Embed(oAddon) tinsert(self.Embeds[oAddon], strPkgName) return true elseif oPkg then error(("Usage: EmbedPackage(oAddon, strPkgName, bSilent, nOffset): Package '%s' is not Embed capable."):format(tostring(strPkgName)), nOffset or 2) end end --- Return the specified module from an addon object. -- Throws an error if the addon object cannot be found (except if silent is set) -- @name //addon//:GetModule -- @paramsig strModuleName[, bSilent] -- @param strModuleName unique name of the module -- @param bSilent if true, the module is optional, silently return nil if its not found (optional) -- @usage -- local MyModule = MyAddon:GetModule("MyModule") function GetModule(self, strModuleName, bSilent) if not self.Modules[strModuleName] and not bSilent then error(("Usage: GetModule(strModuleName, bSilent): 'strModuleName' - Cannot find module '%s'."):format(tostring(strModuleName)), 2) end return self.Modules[strModuleName] end local function IsModuleTrue(self) return true end --- Create a new module for the addon. -- The new module can have its own embedded packages and/or use a module prototype to be mixed into the module. -- @name //addon//:NewModule -- @paramsig strName[, oPrototype|strPkgName[, strPkgName, ...]] -- @param strName unique name of the module -- @param oPrototype object to derive this module from, methods and values from this table will be mixed into the module (optional) -- @param strPkgName List of packages to embed into the module -- @usage -- -- Create a module with some embeded packages -- local MyModule = MyAddon:NewModule("MyModule", "PkgWithEmbed-1.0", "PkgWithEmbed2-1.0") -- -- -- Create a module with a prototype -- local oPrototype = { OnEnable = function(self) Print("OnEnable called!") end } -- local MyModule = MyAddon:NewModule("MyModule", oPrototype, "PkgWithEmbed-1.0", "PkgWithEmbed2-1.0") function NewModule(self, strName, oPrototype, ...) if type(strName) ~= "string" then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'strName' - string expected got '%s'."):format(type(strName)), 2) end if type(oPrototype) ~= "string" and type(oPrototype) ~= "table" and type(oPrototype) ~= "nil" then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'oPrototype' - table (oPrototype), string (strPkgName) or nil expected got '%s'."):format(type(oPrototype)), 2) end if self.Modules[strName] then error(("Usage: NewModule(strName, [oPrototype, [strPkgName, strPkgName, strPkgName, ...]): 'strName' - Module '%s' already exists."):format(strName), 2) end -- Go up the family tree to find the addon that started it all local oCurrParent, oNextParent = self, self.Parent while oNextParent do oCurrParent = oNextParent oNextParent = oCurrParent.Parent end local oModule = NewAddonProto(oCurrParent:GetName(), string.format("%s_%s", self:GetName() or tostring(self), strName)) oModule.IsModule = IsModuleTrue oModule:SetEnabledState(self.DefaultModuleState) oModule.ModuleName = strName oModule.Parent = self if type(oPrototype) == "string" then GeminiAddon:EmbedPackages(oModule, oPrototype, ...) else GeminiAddon:EmbedPackages(oModule, ...) end GeminiAddon:EmbedPackages(oModule, unpack(self.DefaultModulePackages)) if not oPrototype or type(oPrototype) == "string" then oPrototype = self.DefaultModulePrototype or nil --self:_Log("Using Prototype type: " .. tostring(oPrototype)) end if type(oPrototype) == "table" then local mt = getmetatable(oModule) mt.__index = oPrototype setmetatable(oModule, mt) end safecall(self.OnModuleCreated, self, oModule) self.Modules[strName] = oModule tinsert(self.OrderedModules, oModule) return oModule end --- returns the name of the addon or module without any prefix -- @name //addon|module//:GetName -- @paramsig -- @usage -- Print(MyAddon:GetName()) -- Print(MyAddon:GetModule("MyModule"):GetName()) function GetName(self) return self.ModuleName or self.Name end -- Check if the addon is queued to be enabled local function QueuedForInitialization(oAddon) for strAddonName, tAddonList in pairs(GeminiAddon.EnableQueue) do for nIndex = 1, #tAddonList do if tAddonList[nIndex] == oAddon then return true end end end return false end --- Enables the addon, if possible, returns true on success. -- This internally calls GeminiAddon:EnableAddon(), thus dispatching the OnEnable callback -- and enabling all modules on the addon (unless explicitly disabled) -- :Enable() also sets the internal `enableState` variable to true. -- @name //addon//:Enable -- @paramsig -- @usage function Enable(self) self:SetEnabledState(true) if not QueuedForInitialization(self) then return GeminiAddon:EnableAddon(self) end end function Disable(self) self:SetEnabledState(false) return GeminiAddon:DisableAddon(self) end --- Enables the Module, if possible, return true or false depending on success. -- Short-hand function that retrieves the module via `:GetModule` and calls `:Enable` on the module object. -- @name //addon//:EnableModule -- @paramsig name -- @usage -- -- Enable MyModule using :GetModule -- local MyModule = MyAddon:GetModule("MyModule") -- MyModule:Enable() -- -- -- Enable MyModule using the short-hand -- MyAddon:EnableModule("MyModule") function EnableModule(self, strModuleName) local oModule = self:GetModule(strModuleName) return oModule:Enable() end --- Disables the Module, if possible, return true or false depending on success. -- Short-hand function that retrieves the module via `:GetModule` and calls `:Disable` on the module object. -- @name //addon//:DisableModule -- @paramsig name -- @usage -- -- Disable MyModule using :GetModule -- local MyModule = MyAddon:GetModule("MyModule") -- MyModule:Disable() -- -- -- Disable MyModule using the short-hand -- local MyAddon:DisableModule("MyModule") function DisableModule(self, strModuleName) local oModule = self:GetModule(strModuleName) return oModule:Disable() end --- Set the default packages to be mixed into all modules created by this object. -- Note that you can only change the default module packages before any module is created. -- @name //addon//:SetDefaultModulePackages -- @paramsig strPkgName[, strPkgName, ...] -- @param strPkgName List of Packages to embed into the addon -- @usage -- -- Create the addon object -- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.0").tPackage:NewAddon("MyAddon") -- -- Configure default packages for modules -- MyAddon:SetDefaultModulePackages("MyEmbeddablePkg-1.0") -- -- Create a module -- local MyModule = MyAddon:NewModule("MyModule") function SetDefaultModulePackages(self, ...) if next(self.Modules) then error("Usage: SetDefaultModulePackages(...): cannot change the module defaults after a module has been registered.", 2) end self.DefaultModulePackages = {...} end --- Set the default state in which new modules are being created. -- Note that you can only change the default state before any module is created. -- @name //addon//:SetDefaultModuleState -- @paramsig state -- @param state Default state for new modules, true for enabled, false for disabled -- @usage -- -- Create the addon object -- local MyAddon = Apollo.GetPackage("Gemini:Addon-1.0").tPackage:NewAddon("MyAddon") -- -- Set the default state to "disabled" -- MyAddon:SetDefaultModuleState(false) -- -- Create a module and explicilty enable it -- local MyModule = MyAddon:NewModule("MyModule") -- MyModule:Enable() function SetDefaultModuleState(self, bState) if next(self.Modules) then error("Usage: SetDefaultModuleState(bState): cannot change the module defaults after a module has been registered.", 2) end self.DefaultModuleState = bState end --- Set the default prototype to use for new modules on creation. -- Note that you can only change the default prototype before any module is created. -- @name //addon//:SetDefaultModulePrototype -- @paramsig prototype -- @param prototype Default prototype for the new modules (table) -- @usage -- -- Define a prototype -- local prototype = { OnEnable = function(self) Print("OnEnable called!") end } -- -- Set the default prototype -- MyAddon:SetDefaultModulePrototype(prototype) -- -- Create a module and explicitly Enable it -- local MyModule = MyAddon:NewModule("MyModule") -- MyModule:Enable() -- -- should Print "OnEnable called!" now -- @see NewModule function SetDefaultModulePrototype(self, tPrototype) if next(self.Modules) then error("Usage: SetDefaultModulePrototype(tPrototype): cannot change the module defaults after a module has been registered.", 2) end if type(tPrototype) ~= "table" then error(("Usage: SetDefaultModulePrototype(tPrototype): 'tPrototype' - table expected got '%s'."):format(type(tPrototype)), 2) end self.DefaultModulePrototype = tPrototype end --- Set the state of an addon or module -- This should only be called before any enabling actually happened, e.g. in/before OnInitialize. -- @name //addon|module//:SetEnabledState -- @paramsig state -- @param state the state of an addon or module (enabled = true, disabled = false) function SetEnabledState(self, bState) self.EnabledState = bState end --- Return an iterator of all modules associated to the addon. -- @name //addon//:IterateModules -- @paramsig -- @usage -- -- Enable all modules -- for strModuleName, oModule in MyAddon:IterateModules() do -- oModule:Enable() -- end local function IterateModules(self) return pairs(self.Modules) end -- Returns an iterator of all embeds in the addon -- @name //addon//:IterateEmbeds -- @paramsig local function IterateEmbeds(self) return pairs(GeminiAddon.Embeds[self]) end --- Query the enabledState of an addon. -- @name //addon//:IsEnabled -- @paramsig -- @usage -- if MyAddon:IsEnabled() then -- MyAddon:Disable() -- end local function IsEnabled(self) return self.EnabledState end local function IsModule(self) return false end function AddonLog(self, t) self._DebugLog = self._DebugLog or {} tinsert(self._DebugLog, { what = t, when = ostime() }) end local tMixins = { NewModule = NewModule, GetModule = GetModule, Enable = Enable, Disable = Disable, EnableModule = EnableModule, DisableModule = DisableModule, IsEnabled = IsEnabled, SetDefaultModulePackages = SetDefaultModulePackages, SetDefaultModuleState = SetDefaultModuleState, SetDefaultModulePrototype = SetDefaultModulePrototype, SetEnabledState = SetEnabledState, IterateModules = IterateModules, IterateEmbeds = IterateEmbeds, GetName = GetName, -- _Log = AddonLog, DefaultModuleState = true, EnabledState = true, IsModule = IsModule, } -- Embed( target ) -- target (object) - target GeminiAddon object to embed in -- -- **Note:** This is for internal use only. Do not call manually function Embed(target) for k, v in pairs(tMixins) do target[k] = v end end --- Get an iterator over all registered addons. -- @usage -- -- Print a list of all registered GeminiAddons -- for name, addon in GeminiAddon:IterateAddons() do -- Print("Addon: " .. name) -- end function GeminiAddon:IterateAddons() return pairs(self.Addons) end --- Get an iterator over the internal status registry. -- @usage -- -- Print a list of all enabled addons -- for name, status in GeminiAddon:IterateAddonStatus() do -- if status then -- Print("EnabledAddon: " .. name) -- end -- end function GeminiAddon:IterateAddonStatus() return pairs(self.AddonStatus) end function GeminiAddon:OnLoad() end function GeminiAddon:OnDependencyError(strDep, strError) return false end Apollo.RegisterPackage(GeminiAddon, MAJOR, MINOR, {})
mit
RunAwayDSP/darkstar
scripts/globals/items/frostreaper.lua
12
1065
----------------------------------------- -- ID: 16784 -- Item: Frostreaper -- Additional Effect: Ice Damage ----------------------------------------- require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5 if (math.random(0,99) >= chance) then return 0,0,0 else local dmg = math.random(3,10) local params = {} params.bonusmab = 0 params.includemab = false dmg = addBonusesAbility(player, dsp.magic.ele.ICE, target, dmg, params) dmg = dmg * applyResistanceAddEffect(player,target,dsp.magic.ele.ICE,0) dmg = adjustForTarget(target,dmg,dsp.magic.ele.ICE) dmg = finalMagicNonSpellAdjustments(player,target,dsp.magic.ele.ICE,dmg) local message = dsp.msg.basic.ADD_EFFECT_DMG if (dmg < 0) then message = dsp.msg.basic.ADD_EFFECT_HEAL end return dsp.subEffect.ICE_DAMAGE,message,dmg end end
gpl-3.0
lichtl/darkstar
scripts/zones/Valkurm_Dunes/npcs/Nyata-Mobuta_WW.lua
14
3336
----------------------------------- -- Area: Valkurm Dunes -- NPC: Nyata-Mobuta, W.W. -- Type: Outpost Conquest Guards -- @pos 139.394 -7.885 100.384 103 ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Valkurm_Dunes/TextIDs"); local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ZULKHEIM; local csid = 0x7ff7; ----------------------------------- -- 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
lichtl/darkstar
scripts/zones/Bastok_Mines/npcs/Zemedars.lua
17
1780
----------------------------------- -- Area: Bastok Mines -- NPC: Zemedars -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,ZEMEDARS_SHOP_DIALOG); stock = { 0x3224, 23316,1, --Iron Subligar 0x3219, 5003,1, --Lizard Trousers 0x32A2, 14484,1, --Leggins 0x3299, 3162,1, --Lizard Ledelsens 0x300D, 31544,1, --Buckler 0x3221, 1840,2, --Brass Subligar 0x3218, 493,2, --Leather Trousers 0x32A1, 1140,2, --Brass Leggins 0x3298, 309,2, --Leather Highboots 0x300C, 11076,2, --Targe 0x3220, 191,3, --Bronze Subligar 0x3208, 11592,3, --Chain Gose 0x32A0, 117,3, --Bronze Leggins 0x3288, 7120,3, --Greaves 0x3002, 556,3, --Maple Shield 0x3001, 110,3 --Lauan Shield } showNationShop(player, NATION_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
LuaAdvanced/XTLanguage
start.lua
1
1347
XTL = require('src/XTL') -- Redis wget https://raw.githubusercontent.com/nrk/redis-lua/version-2.0/src/redis.lua redis_server = require('redis') redis = redis_server.connect('127.0.0.1', 6379) print('\n\nREDIS! TEST!') -- REDIS local ping = XTL.load_redis(redis) if ping then print('REDIS OK :)') else print('REDIS with problems :(') end print('\n\nTranslate! TEST!') -- Translate local lang = XTL.user("TiagoDanin", "EN") print('LANG USER: ' .. lang) local ok, res = XTL.set(lang, 'test', 'test... test ...') print('SET: ' .. ok) if res then print('GET: ' .. XTL.get(lang, 'test')) else print('GET: Error!') end print('\n\nVote translate! TEST!') -- Vote translate print('USER X1 Voted') XTL.vote('EN', 'test', 'TEST.......', 'X1') print('USER X2 Voted') XTL.vote('EN', 'test', 'TEST.......', 'X2', false) print('USER X3 Voted') XTL.vote('EN', 'test', 'TEST..TEST', 'X3', false, 21) print('USER X4 Voted') XTL.vote('EN', 'test', 'test..', 'X3', nil, -21) print('USER TiagoDanin Voted') XTL.vote('EN', 'test', 'TEST!', 'TiagoDanin', true, 50) -- :V print('\n LIST VOTES!') local result = 0 for v,i in pairs(XTL.listvote('EN', 'test')) do print(v .. ' == ' .. i) result = result + i end print('Total: ' .. result) print('\nSync Translate!') print(XTL.sync('EN', 'test')) print('\nWIN Translate!') print(XTL.get('EN', 'test'))
gpl-2.0
lichtl/darkstar
scripts/zones/La_Theine_Plateau/npcs/Augevinne.lua
14
1628
----------------------------------- -- Area: La Theine Plateau -- NPC: Augevinne -- Involved in Mission: The Rescue Drill -- @pos -361 39 266 102 ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/La_Theine_Plateau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(SANDORIA) == THE_RESCUE_DRILL) then local MissionStatus = player:getVar("MissionStatus"); if (MissionStatus >= 5 and MissionStatus <= 7) then player:startEvent(0x0067); elseif (MissionStatus == 8) then player:showText(npc, RESCUE_DRILL + 21); elseif (MissionStatus >= 9) then player:showText(npc, RESCUE_DRILL + 26); else player:showText(npc, RESCUE_DRILL); end else player:showText(npc, RESCUE_DRILL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
NiLuJe/koreader
frontend/ui/widget/container/alphacontainer.lua
4
1750
--[[-- AlphaContainer will paint its content (a single widget) at the specified opacity level (0..1) Example: local alpha alpha = AlphaContainer:new{ alpha = 0.7, FrameContainer:new{ background = Blitbuffer.COLOR_WHITE, bordersize = Size.border.default, margin = 0, padding = Size.padding.default } } --]] local Blitbuffer = require("ffi/blitbuffer") local WidgetContainer = require("ui/widget/container/widgetcontainer") local AlphaContainer = WidgetContainer:extend{ alpha = 1, -- we cache a blitbuffer object for re-use here: private_bb = nil, } function AlphaContainer:paintTo(bb, x, y) local contentSize = self[1]:getSize() if not self.private_bb or self.private_bb:getWidth() ~= contentSize.w or self.private_bb:getHeight() ~= contentSize.h then if self.private_bb then self.private_bb:free() -- free the one we're going to replace end -- create a private blitbuffer for our child widget to paint to self.private_bb = Blitbuffer.new(contentSize.w, contentSize.h, bb:getType()) -- fill it with our usual background color self.private_bb:fill(Blitbuffer.COLOR_WHITE) end -- now, compose our child widget's content on our private blitbuffer canvas self[1]:paintTo(self.private_bb, 0, 0) -- and finally blit the private blitbuffer to the target blitbuffer at the requested opacity level bb:addblitFrom(self.private_bb, x, y, 0, 0, contentSize.w, contentSize.h, self.alpha) end function AlphaContainer:onCloseWidget() if self.private_bb then self.private_bb:free() self.private_bb = nil end end return AlphaContainer
agpl-3.0
RunAwayDSP/darkstar
scripts/commands/promote.lua
22
1862
--------------------------------------------------------------------------------------------------- -- func: promote -- desc: Promotes the player to a new GM level. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "si" }; function error(player, msg) player:PrintToPlayer(msg); player:PrintToPlayer("!promote <player> <level>"); end; function onTrigger(player, target, level) -- determine maximum level player can promote to local maxLevel = player:getGMLevel() - 1; if (maxLevel < 1) then maxLevel = 0; end -- validate target local targ; if (target == nil) then error(player, "You must provide a player name."); return; else targ = GetPlayerByName(target); if (targ == nil) then error(player, string.format( "Player named '%s' not found!", target ) ); return; end end -- catch players trying to change level of equal or higher tiered GMs. if (targ:getGMLevel() >= player:getGMLevel()) then printf( "%s attempting to adjust same or higher tier GM %s.", player:getName(), targ:getName() ); targ:PrintToPlayer(string.format( "%s attempted to adjust your GM rank.", player:getName() )); error(player, "You can not use this command on same or higher tiered GMs."); return; end -- validate level if (level == nil or level < 0 or level > maxLevel) then error(player, string.format("Invalid level. Must be 0 to %i.", maxLevel )); return; end -- change target gm level targ:setGMLevel(level); player:PrintToPlayer(string.format( "%s set to tier %i.", targ:getName(), level )); targ:PrintToPlayer(string.format( "You have been set to tier %i.", level )); end;
gpl-3.0
lichtl/darkstar
scripts/zones/Bastok_Markets/npcs/Hortense.lua
15
1936
----------------------------------- -- Area: Bastok Markets -- NPC: Hortense -- Standard Merchant NPC -- -- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape ----------------------------------- 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) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,HORTENSE_SHOP_DIALOG); stock = { 0x1370, 64,3, --Scroll of Foe Requiem 0x1371, 441,3, --Scroll of Foe Requiem II 0x1372, 3960,3, --Scroll of Foe Requiem III 0x1373, 6912,3, --Scroll of Foe Requiem IV 0x1376, 47196,3, --Scroll of Foe Requiem VII 0x137A, 37,3, --Scroll of Army's Paeon 0x137B, 321,3, --Scroll of Army's Paeon II 0x137C, 3240,3, --Scroll of Army's Paeon III 0x137D, 5940,3, --Scroll of Army's Paeon IV 0x137F, 48944,3, --Scroll of Army's Paeon VI 0x138A, 21,3, --Scroll of Valor Minuet 0x138B, 1101,3, --Scroll of Valor Minuet II 0x138C, 5544,3, --Scroll of Valor Minuet III 0x138E, 53820,3 --Scroll of Valor Minuet V } showNationShop(player, NATION_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
vasilecristian/SDL2_ttf
prj/premake5.lua
1
1563
include "../../premake/common/" solution "SDL2_ttf" addCommonConfig() project "SDL2_ttf" files { "../src/SDL_ttf.c", "../include/*.h", } includedirs { "../include/", "../src/", "../../Freetype/include/", "../../SDL2/include", } kind "StaticLib" targetdir("../lib/" .. GetPathFromPlatform()) if (IsVisualStudio()) then defines {"WIN32"} end if IsWin8StoreApp() then -- WinRT removeflags { 'StaticRuntime' } flags { 'DisableWinRT' } end if IsIos() then defines {"OS_IPHONE"} buildoptions { "-std=c++11 -stdlib=libc++ -x objective-c++ -Wno-error" } -- kind "WindowedApp" -- files { GetPathFromPlatform() .. "/Info.plist" } else -- kind "ConsoleApp" end if IsXCode() then addCommonXcodeBuildSettings() xcodebuildsettings { --["CODE_SIGN_IDENTITY"] = "iPhone Developer: Valeri Vuchov (WDTMDP2J2J)", --["ARCHS"] = "$(ARCHS_STANDARD)"; --["TARGETED_DEVICE_FAMILY"] = "1,2"; ["ONLY_ACTIVE_ARCH"] = "NO" --["VALID_ARCHS"] = "arm64 armv7 armv7s"; } xcodebuildresources { "../data/**", } files { "../data/**", } defines {"OS_IPHONE"} buildoptions { "-std=c++11 -stdlib=libc++ -x objective-c++ -Wno-error" } -- kind "WindowedApp" -- files { GetPathFromPlatform() .. "/Info.plist" } end
mit
lichtl/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/qm8.lua
57
2181
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: qm8 (??? - Ancient Papyrus Shreds) -- Involved in Quest: In Defiant Challenge -- @pos 105.275 -32 92.551 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(ANCIENT_PAPYRUS_SHRED2); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED2); end if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1088, 1); player:messageSpecial(ITEM_OBTAINED, 1088); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088); end end if (player:hasItem(1088)) then player:delKeyItem(ANCIENT_PAPYRUS_SHRED1); player:delKeyItem(ANCIENT_PAPYRUS_SHRED2); player:delKeyItem(ANCIENT_PAPYRUS_SHRED3); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
ld-test/loop
lua/loop/debug/Inspector.lua
11
12926
-------------------------------------------------------------------------------- ---------------------- ## ##### ##### ###### ----------------------- ---------------------- ## ## ## ## ## ## ## ----------------------- ---------------------- ## ## ## ## ## ###### ----------------------- ---------------------- ## ## ## ## ## ## ----------------------- ---------------------- ###### ##### ##### ## ----------------------- ---------------------- ----------------------- ----------------------- Lua Object-Oriented Programming ------------------------ -------------------------------------------------------------------------------- -- Project: LOOP Class Library -- -- Release: 2.3 beta -- -- Title : Interactive Inspector of Application State -- -- Author : Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- local _G = _G local assert = assert local error = error local getfenv = getfenv local ipairs = ipairs local load = load local loadstring = loadstring local next = next local pairs = pairs local rawget = rawget local rawset = rawset local select = select local setfenv = setfenv local setmetatable = setmetatable local type = type local xpcall = xpcall local coroutine = require "coroutine" local debug = require "debug" local io = require "io" local table = require "table" local oo = require "loop.base" local Viewer = require "loop.debug.Viewer" module("loop.debug.Inspector", oo.class) active = true input = io.stdin viewer = Viewer local function call(self, op, ...) self = self[".thread"] if self then return op(self, ...) else return op(...) end end local self local infoflags = "Slnuf" local Command = {} function Command.see(...) self.viewer:write(...) self.viewer.output:write("\n") end function Command.loc(which, ...) local level = self[".level"] if level then local index = 1 local name, value repeat name, value = call(self, debug.getlocal, level, index) if not which and name then local viewer = self.viewer local output = viewer.output output:write(name) output:write(" = ") viewer:write(value) output:write("\n") elseif name == which then if select("#", ...) == 0 then return value else return call(self, debug.setlocal, level, index, (...)) end end index = index + 1 until not name end end function Command.upv(which, ...) local func = self[".current"].func local index = 1 local name, value repeat name, value = debug.getupvalue(func, index) if not which and name then local viewer = self.viewer local output = viewer.output output:write(name," = ") viewer:write(value) output:write("\n") elseif name == which then if select("#", ...) == 0 then return value else return debug.setupvalue(func, index, (...)) end end index = index + 1 until not name end function Command.env(which, ...) local env = getfenv(self[".current"].func) if which then if select("#", ...) == 0 then return env[which] else env[which] = (...) end else self.viewer:print(env) end end function Command.lua(which, ...) if which then if select("#", ...) == 0 then return _G[which] else _G[which] = (...) end else self.viewer:print(_G) end end function Command.goto(where) local kind = type(where) if kind == "thread" then local status = coroutine.status(where) if status ~= "running" and status ~= "suspended" then error("unable to inspect an inactive thread") end elseif kind ~= "function" then error("invalid inspection value, got `"..kind.."' (`function' or `thread' expected)") end if self[".level"] then rawset(self, #self+1, self[".level"]) rawset(self, #self+1, self[".thread"]) else rawset(self, #self+1, self[".current"].func) end if kind == "thread" then self[".level"] = 1 self[".thread"] = where self[".current"] = call(self, debug.getinfo, self[".level"], infoflags) else self[".level"] = false self[".thread"] = false self[".current"] = call(self, debug.getinfo, where, infoflags) end end function Command.goup() local level = self[".level"] if level then local next = call(self, debug.getinfo, level + 1, infoflags) if next then rawset(self, #self+1, -1) self[".level"] = level + 1 self[".current"] = next else error("top level reached") end else error("unable to go up in inactive functions") end end function Command.back() if #self > 0 then local kind = type(self[#self]) if kind == "number" then self[".level"] = self[".level"] + self[#self] self[".current"] = call(self, debug.getinfo, self[".level"], infoflags) self[#self] = nil elseif kind == "function" then self[".level"] = false self[".thread"] = false self[".current"] = call(self, debug.getinfo, self[#self], infoflags) self[#self] = nil else self[".thread"] = self[#self] self[#self] = nil self[".level"] = self[#self] self[#self] = nil self[".current"] = call(self, debug.getinfo, self[".level"], infoflags) end else error("no more backs avaliable") end end function Command.hist() local index = #self while self[index] ~= nil do local kind = type(self[index]) if kind == "number" then self.viewer:print(" up one level") index = index - 1 elseif kind == "function" then self.viewer:print(" left inactive ",self[index]) index = index - 1 else self.viewer:print(" left ",self[index] or "main thread"," at level ",self[index-1]) index = index - 2 end end end function Command.curr() local viewer = self.viewer local level = self[".level"] if level then local thread = self[".thread"] if thread then viewer:write(thread) else viewer.output:write("main thread") end viewer:print(", level ", call(self, debug.traceback, level, level)) else viewer:print("inactive function ",self[".current"].func) end end function Command.done() while #self > 0 do self[#self] = nil end self[".thread"] = false self[".level"] = false self[".current"] = false end function Command.step(level) if level == "in" then level = -1 elseif level == "out" then level = 1 else level = 0 end rawset(self, ".hook", level) Command.done() end function Command.lsbp() local breaks = {} for line, files in pairs(self.breaks) do for file in pairs(files) do breaks[#breaks+1] = file..":"..line end end table.sort(breaks) for _, bp in ipairs(breaks) do self.viewer:print(bp) end end function Command.mkbp(file, line) assert(type(file) == "string", "usage: mkbp(<file>, <line>)") assert(type(line) == "number", "usage: mkbp(<file>, <line>)") self.breaks[line][file] = true end function Command.rmbp(file, line) assert(type(file) == "string", "usage: rmbp(<file>, <line>)") assert(type(line) == "number", "usage: rmbp(<file>, <line>)") local files = rawget(self.breaks, line) if files then files[file] = nil if next(files) == nil then self.breaks[line] = nil end end end -------------------------------------------------------------------------------- local BreaksListMeta = { __index = function(self, line) local files = {} rawset(self, line, files) return files end, } function __init(self, object) self = oo.rawnew(self, object) self.breaks = setmetatable(self.breaks or {}, BreaksListMeta) function self.breakhook(event, line) local level = rawget(self, "break.level") if event == "line" then -- check for break points local files = rawget(self.breaks, line) if files then local source = debug.getinfo(2, "S").source for file in pairs(files) do if source:find(file, #source - #file + 1, true) then level = 0 break end end end if level == nil or level > 0 then return end self:console(2) level = rawget(self, ".hook") rawset(self, ".hook", nil) if level == nil then self:restorehook() end elseif level ~= nil then if event == "call" then level = level + 1 else level = level - 1 end end rawset(self, "break.level", level) local hookbak = rawget(self, "hook.bak") if hookbak then return hookbak(event, line) end end return self end function __index(inspector, field) if rawget(_M, field) ~= nil then return rawget(_M, field) end if Command[field] then self = inspector return Command[field] end local name, value local func = rawget(inspector, ".level") if func then local index = 1 repeat name, value = call(inspector, debug.getlocal, func, index) if name == field then return value else index = index + 1 end until not name end local func = rawget(inspector, ".current") if func then func = func.func local index = 1 repeat name, value = debug.getupvalue(func, index) if name == field then return value else index = index + 1 end until not name value = getfenv(func)[field] if value ~= nil then return value end return _G[field] end end function __newindex(inspector, field, value) if rawget(_M, field) == nil then local name local index local func = inspector[".level"] if func then index = 1 repeat name = call(inspector, debug.getlocal, func, index) if name == field then return call(inspector, debug.setlocal, func, index, value) else index = index + 1 end until not name end func = inspector[".current"] if func then func = func.func index = 1 repeat name = debug.getupvalue(func, index) if name == field then return debug.setupvalue(func, index, value) else index = index + 1 end until not name getfenv(func)[field] = value return end end rawset(inspector, field, value) end local function results(self, success, ...) if not success then io.stderr:write(..., "\n") elseif select("#", ...) > 0 then self.viewer:write(...) self.viewer.output:write("\n") end end function console(self, level) if self.active then assert(not rawget(self, ".current"), "cannot invoke inspector operation from the console") level = level or 1 rawset(self, ".thread", coroutine.running() or false) rawset(self, ".current", call(self, debug.getinfo, level + 2, infoflags)) -- call, stop rawset(self, ".level", level + 5) -- call, command, <inspection>, xpcall, stop local viewer = self.viewer local input = self.input local cmd, errmsg repeat local info = self[".current"] viewer.output:write( info.short_src or info.what, ":", (info.currentline ~= -1 and info.currentline) or (info.linedefined ~= -1 and info.linedefined) or "?", " ", info.namewhat, info.namewhat == "" and "" or " ", info.name or viewer:tostring(info.func), "> " ) cmd = assert(input:read()) local short = cmd:match("^%s*([%a_][%w_]*)%s*$") if short and Command[short] then cmd = short.."()" else cmd = cmd:gsub("^%s*=", "return ") end cmd, errmsg = loadstring(cmd, "inspection") if cmd then setfenv(cmd, self) results(self, xpcall(cmd, debug.traceback)) else viewer.output:write(errmsg, "\n") end until not rawget(self, ".current") end end -------------------------------------------------------------------------------- function restorehook(self) if next(self.breaks) == nil then debug.sethook( rawget(self, "hook.bak") or nil, rawget(self, "mask.bak"), rawget(self, "count.bak") ) rawset(self, "hook.bak", nil) rawset(self, "mask.bak", nil) rawset(self, "count.bak", nil) rawset(self, "break.level", nil) end end function setuphook(self) if rawget(self, "hook.bak") ~= self.breakhook then local hook, mask, count = debug.gethook() rawset(self, "hook.bak", hook or false) rawset(self, "mask.bak", mask) rawset(self, "count.bak", count) debug.sethook(self.breakhook, "crl", count) end end function stop(self, level) rawset(self, "break.level", level and level+2 or 3) self:setuphook() end function setbreak(self, file, line) self.breaks[line][file] = true self:setuphook() end function removebreak(self, file, line) local files = rawget(self.breaks, line) if files then files[file] = nil if next(files) == nil then self.breaks[line] = nil if rawget(self, "break.level") == nil then self:restorehook() end end end end local function ibreaks(self, file, line) local files = rawget(self.breaks, line) while files do file = next(files, file) if file then return file, line end line, files = next(self.breaks, line) end end function allbreaks(self) return ibreaks, self, nil, next(self.breaks) end
mit
pnorman/ClearTables
test-water.lua
2
2759
--[[ This file is part of ClearTables @author Paul Norman <penorman@mac.com> @copyright 2015-2016 Paul Norman, MIT license ]]-- require "water" print("water.lua tests") print("TESTING: accept_water_area") assert(not accept_water_area({}), "test failed: untagged") assert(not accept_water_area({foo="bar"}), "test failed: other tags") assert(accept_water_area({natural="water"}), "test failed: natural=water") assert(accept_water_area({waterway="riverbank"}), "test failed: waterway=riverbank") assert(accept_water_area({landuse="reservoir"}), "test failed: landuse=reservoir") print("TESTING: transform_water_area") assert(deepcompare(transform_water_area({}), {}), "test failed: no tags") assert(deepcompare(transform_water_area({natural="water"}), {}), "test failed: only natural") assert(transform_water_area({name="foo"}).name == "foo", "test failed: name") assert(transform_water_area({["name:en"]="foo"}).names == '"en"=>"foo"', "test failed: names") assert(deepcompare(transform_water_area({name="foo", bar="baz"}), {name="foo"}), "test failed: dropping other tags") assert(deepcompare(transform_water_area({water="foo"}), {water="foo"}), "test failed: water tag") assert(deepcompare(transform_water_area({waterway="riverbank"}), {water="river"}), "test failed: waterway") assert(deepcompare(transform_water_area({landuse="reservoir"}), {water="reservoir"}), "test failed: waterway") assert(deepcompare(transform_water_area({water="foo", waterway="riverbank"}), {water="foo"}), "test failed: water tag with riverbank") assert(deepcompare(transform_water_area({water="foo", landuse="reservoir"}), {water="foo"}), "test failed: water tag with riverbank") print("TESTING: accept_waterway") assert(not accept_waterway({}), "test failed: untagged") assert(not accept_waterway({foo="bar"}), "test failed: other tags") assert(accept_waterway({waterway="stream"}), "test failed: stream") assert(accept_waterway({waterway="river"}), "test failed: river") assert(accept_waterway({waterway="ditch"}), "test failed: ditch") assert(accept_waterway({waterway="canal"}), "test failed: canal") assert(accept_waterway({waterway="drain"}), "test failed: drain") print("TESTING: transform_waterway") assert(deepcompare(transform_waterway({}), {layer="0"}), "test failed: no tags") assert(transform_waterway({name="foo"}).name == "foo", "test failed: name") assert(transform_waterway({["name:en"]="foo"}).names == '"en"=>"foo"', "test failed: names") assert(deepcompare(transform_waterway({waterway="river"}), {waterway="river", layer="0"}), "test failed: river") assert(transform_waterway({waterway="river", bridge="yes"}).bridge == "true", "test failed: bridge") assert(transform_waterway({waterway="river", tunnel="yes"}).tunnel == "true", "test failed: tunnel")
mit
lichtl/darkstar
scripts/globals/items/slice_of_salted_hare.lua
18
1177
----------------------------------------- -- ID: 5737 -- Item: slice_of_salted_hare -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 10 -- Strength 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,5737); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_STR, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_STR, 1); end;
gpl-3.0
lichtl/darkstar
scripts/zones/Sealions_Den/mobs/Mammet-22_Zeta.lua
23
4284
----------------------------------- -- Area: Sealions Den -- Mob: Mammet-22_Zeta ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobEngaged Action ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) local MammetID = mob:getID(); -- printf("MammetID dead: %u",MammetID); local mammet_1_1 = GetMobAction(16908289); local mammet_1_2 = GetMobAction(16908290); local mammet_1_3 = GetMobAction(16908291); local mammet_1_4 = GetMobAction(16908292); local mammet_1_5 = GetMobAction(16908293); local mammet_2_1 = GetMobAction(16908296); local mammet_2_2 = GetMobAction(16908297); local mammet_2_3 = GetMobAction(16908298); local mammet_2_4 = GetMobAction(16908299); local mammet_2_5 = GetMobAction(16908300); local mammet_3_1 = GetMobAction(16908303); local mammet_3_2 = GetMobAction(16908304); local mammet_3_3 = GetMobAction(16908305); local mammet_3_4 = GetMobAction(16908306); local mammet_3_5 = GetMobAction(16908307); if (MammetID == 16908289 or MammetID == 16908290 or MammetID == 16908291 or MammetID == 16908292 or MammetID == 16908293) then if ((mammet_1_1 == 0 or mammet_1_1 == 21 or mammet_1_1 == 22 or mammet_1_1 == 23)and (mammet_1_2 == 0 or mammet_1_2 == 21 or mammet_1_2 == 22 or mammet_1_2 == 23)and (mammet_1_3 == 0 or mammet_1_3 == 21 or mammet_1_3 == 22 or mammet_1_3 == 23)and (mammet_1_4 == 0 or mammet_1_4 == 21 or mammet_1_4 == 22 or mammet_1_4 == 23)and (mammet_1_5 == 0 or mammet_1_5 == 21 or mammet_1_5 == 22 or mammet_1_5 == 23)) then player:startEvent(0x000b); end elseif (MammetID == 16908297 or MammetID == 16908298 or MammetID == 16908299 or MammetID == 16908300 or MammetID == 16908296) then if ((mammet_2_1 == 0 or mammet_2_1 == 21 or mammet_2_1 == 22 or mammet_2_1 == 23)and (mammet_2_2 == 0 or mammet_2_2 == 21 or mammet_2_2 == 22 or mammet_2_2 == 23)and (mammet_2_3 == 0 or mammet_2_3 == 21 or mammet_2_3 == 22 or mammet_2_3 == 23)and (mammet_2_4 == 0 or mammet_2_4 == 21 or mammet_2_4 == 22 or mammet_2_4 == 23)and (mammet_2_5 == 0 or mammet_2_5 == 21 or mammet_2_5 == 22 or mammet_2_5 == 23)) then player:startEvent(0x000b); end elseif (MammetID == 16908303 or MammetID == 16908304 or MammetID == 16908305 or MammetID == 16908306 or MammetID == 16908307) then if ((mammet_3_1 == 0 or mammet_3_1 == 21 or mammet_3_1 == 22 or mammet_3_1 == 23)and (mammet_3_2 == 0 or mammet_3_2 == 21 or mammet_3_2 == 22 or mammet_3_2 == 23)and (mammet_3_3 == 0 or mammet_3_3 == 21 or mammet_3_3 == 22 or mammet_3_3 == 23)and (mammet_3_4 == 0 or mammet_3_4 == 21 or mammet_3_4 == 22 or mammet_3_4 == 23)and (mammet_3_5 == 0 or mammet_3_5 == 21 or mammet_3_5 == 22 or mammet_3_5 == 23)) then player:startEvent(0x000b); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x000b) then local instance = player:getVar("bcnm_instanceid") --Players are healed in between the fights, but their TP is set to 0 player:setHP(player:getMaxHP()); player:setMP(player:getMaxMP()); player:setTP(0); if (instance == 1) then player:setPos(-779, -103, -80); SpawnMob(16908294); -- omega1 elseif (instance == 2) then player:setPos(-140, -23, -440); SpawnMob(16908301); -- omega2 else player:setPos(499, 56, -802); SpawnMob(16908308); -- omega 3 end player:addTitle(BRANDED_BY_LIGHTNING); end end;
gpl-3.0
Mudlet-cn/mudlet
src/mudlet-lua/lua/geyser/GeyserGeyser.lua
16
2423
-------------------------------------- -- -- -- The Geyser Layout Manager by guy -- -- -- -------------------------------------- --================================================== -- Create the Geyser Root Container --================================================== --- Create the Geyser namespace. -- Geyser is considered to be a "container window" for the purposes -- of default limits for new windows, in fact, it is the root container -- window, and is the metatable for Geyser.Container. It has the -- minimum number of functions needed to behave as a Container. Geyser = Geyser or {i = 0, x = 0, y = 0} --Layout policies. Fixed = Do not stretch/shrink, Dynamic = Do stretch/shrink Geyser.Fixed, Geyser.Dynamic = 0, 1 Geyser.width, Geyser.height = getMainWindowSize() Geyser.get_x = function () return 0 end Geyser.get_y = function () return 0 end Geyser.get_width = function () return getMainWindowSize() end Geyser.get_height = function () local w,h = getMainWindowSize() return h end Geyser.name = "Geyser Root Window" Geyser.__index = Geyser -- Create the window list for updates Geyser.windowList = Geyser.windowList or {} Geyser.windows = Geyser.windows or {} Geyser.defer_updates = false function Geyser:begin_update() self.defer_updates = true end function Geyser:end_update() self.defer_updates = false self:reposition() end function Geyser:reposition() if not self.defer_updates then GeyserReposition() end end --- Add a window to the list that this container manages. -- @param window The window to add this container function Geyser:add (window, cons) cons = cons or window -- 'cons' is optional -- Stop other container from controlling this window if window.container then window.container:remove(window) end -- Assume control of this window window.container = self self.windowList[window.name] = window table.insert(self.windows, window.name) Geyser.set_constraints(window, cons, self) if not self.defer_updates then window:reposition() end window:show() end --- Removes a window from the list that it manages -- @param window The window to remove from this container's -- windowList function Geyser:remove (window) self.windowList[window.name] = nil index = table.index_of(self.windows, window.name) or 0 table.remove(self.windows, index) end
gpl-2.0
amerlyq/airy
%wf/obsolete/imapfilter/cfg/filters.lua
1
1051
-- vim:ft=lua:ts=2:sw=2:sts=2 -- personal(m, accs[1]) -- TEMP:FIXED: until I fix imapfilter code to support base64 match_subject -- SEE: http://lua-users.org/wiki/BaseSixtyFour -- REQ: https://github.com/lefcha/imapfilter/issues/127 -- SEE: https://maildrop.cc/ function mv_from(acc, m, dst, tbl) for i, v in pairs(tbl) do m:contain_from(v):move_messages(acc[dst]) end end function mv_to(acc, m, dst, tbl) for i, v in pairs(tbl) do m:contain_to(v):move_messages(acc[dst]) end end function mv_subj(acc, m, dst, tbl) for i, v in pairs(tbl) do m:contain_subject(v):move_messages(acc[dst]) end end function mv_subj_rgx(acc, m, dst, patt) m:match_subject(patt):move_messages(acc[dst]) end function addr_person(m, nm) return m:contain_cc(nm) + m:contain_to(nm) + m:contain_from(nm) + m:contain_field('sender', nm) end function mv_any_addr(acc, m, nm, dst) addr_person(m, nm):move_messages(acc[dst]) end -- function deleteold(m, days) -- todelete=m:is_older(days)-mine(m) -- todelete:move_messages(acc['Trash']) -- end
mit
lc412/skynet
3rd/lpeg/re.lua
160
6286
-- $Id: re.lua,v 1.44 2013/03/26 20:11:40 roberto Exp $ -- imported functions and modules local tonumber, type, print, error = tonumber, type, print, error local setmetatable = setmetatable local m = require"lpeg" -- 'm' will be used to parse expressions, and 'mm' will be used to -- create expressions; that is, 're' runs on 'm', creating patterns -- on 'mm' local mm = m -- pattern's metatable local mt = getmetatable(mm.P(0)) -- No more global accesses after this point local version = _VERSION if version == "Lua 5.2" then _ENV = nil end local any = m.P(1) -- Pre-defined names local Predef = { nl = m.P"\n" } local mem local fmem local gmem local function updatelocale () mm.locale(Predef) Predef.a = Predef.alpha Predef.c = Predef.cntrl Predef.d = Predef.digit Predef.g = Predef.graph Predef.l = Predef.lower Predef.p = Predef.punct Predef.s = Predef.space Predef.u = Predef.upper Predef.w = Predef.alnum Predef.x = Predef.xdigit Predef.A = any - Predef.a Predef.C = any - Predef.c Predef.D = any - Predef.d Predef.G = any - Predef.g Predef.L = any - Predef.l Predef.P = any - Predef.p Predef.S = any - Predef.s Predef.U = any - Predef.u Predef.W = any - Predef.w Predef.X = any - Predef.x mem = {} -- restart memoization fmem = {} gmem = {} local mt = {__mode = "v"} setmetatable(mem, mt) setmetatable(fmem, mt) setmetatable(gmem, mt) end updatelocale() local I = m.P(function (s,i) print(i, s:sub(1, i-1)); return i end) local function getdef (id, defs) local c = defs and defs[id] if not c then error("undefined name: " .. id) end return c end local function patt_error (s, i) local msg = (#s < i + 20) and s:sub(i) or s:sub(i,i+20) .. "..." msg = ("pattern error near '%s'"):format(msg) error(msg, 2) end local function mult (p, n) local np = mm.P(true) while n >= 1 do if n%2 >= 1 then np = np * p end p = p * p n = n/2 end return np end local function equalcap (s, i, c) if type(c) ~= "string" then return nil end local e = #c + i if s:sub(i, e - 1) == c then return e else return nil end end local S = (Predef.space + "--" * (any - Predef.nl)^0)^0 local name = m.R("AZ", "az", "__") * m.R("AZ", "az", "__", "09")^0 local arrow = S * "<-" local seq_follow = m.P"/" + ")" + "}" + ":}" + "~}" + "|}" + (name * arrow) + -1 name = m.C(name) -- a defined name only have meaning in a given environment local Def = name * m.Carg(1) local num = m.C(m.R"09"^1) * S / tonumber local String = "'" * m.C((any - "'")^0) * "'" + '"' * m.C((any - '"')^0) * '"' local defined = "%" * Def / function (c,Defs) local cat = Defs and Defs[c] or Predef[c] if not cat then error ("name '" .. c .. "' undefined") end return cat end local Range = m.Cs(any * (m.P"-"/"") * (any - "]")) / mm.R local item = defined + Range + m.C(any) local Class = "[" * (m.C(m.P"^"^-1)) -- optional complement symbol * m.Cf(item * (item - "]")^0, mt.__add) / function (c, p) return c == "^" and any - p or p end * "]" local function adddef (t, k, exp) if t[k] then error("'"..k.."' already defined as a rule") else t[k] = exp end return t end local function firstdef (n, r) return adddef({n}, n, r) end local function NT (n, b) if not b then error("rule '"..n.."' used outside a grammar") else return mm.V(n) end end local exp = m.P{ "Exp", Exp = S * ( m.V"Grammar" + m.Cf(m.V"Seq" * ("/" * S * m.V"Seq")^0, mt.__add) ); Seq = m.Cf(m.Cc(m.P"") * m.V"Prefix"^0 , mt.__mul) * (#seq_follow + patt_error); Prefix = "&" * S * m.V"Prefix" / mt.__len + "!" * S * m.V"Prefix" / mt.__unm + m.V"Suffix"; Suffix = m.Cf(m.V"Primary" * S * ( ( m.P"+" * m.Cc(1, mt.__pow) + m.P"*" * m.Cc(0, mt.__pow) + m.P"?" * m.Cc(-1, mt.__pow) + "^" * ( m.Cg(num * m.Cc(mult)) + m.Cg(m.C(m.S"+-" * m.R"09"^1) * m.Cc(mt.__pow)) ) + "->" * S * ( m.Cg((String + num) * m.Cc(mt.__div)) + m.P"{}" * m.Cc(nil, m.Ct) + m.Cg(Def / getdef * m.Cc(mt.__div)) ) + "=>" * S * m.Cg(Def / getdef * m.Cc(m.Cmt)) ) * S )^0, function (a,b,f) return f(a,b) end ); Primary = "(" * m.V"Exp" * ")" + String / mm.P + Class + defined + "{:" * (name * ":" + m.Cc(nil)) * m.V"Exp" * ":}" / function (n, p) return mm.Cg(p, n) end + "=" * name / function (n) return mm.Cmt(mm.Cb(n), equalcap) end + m.P"{}" / mm.Cp + "{~" * m.V"Exp" * "~}" / mm.Cs + "{|" * m.V"Exp" * "|}" / mm.Ct + "{" * m.V"Exp" * "}" / mm.C + m.P"." * m.Cc(any) + (name * -arrow + "<" * name * ">") * m.Cb("G") / NT; Definition = name * arrow * m.V"Exp"; Grammar = m.Cg(m.Cc(true), "G") * m.Cf(m.V"Definition" / firstdef * m.Cg(m.V"Definition")^0, adddef) / mm.P } local pattern = S * m.Cg(m.Cc(false), "G") * exp / mm.P * (-any + patt_error) local function compile (p, defs) if mm.type(p) == "pattern" then return p end -- already compiled local cp = pattern:match(p, 1, defs) if not cp then error("incorrect pattern", 3) end return cp end local function match (s, p, i) local cp = mem[p] if not cp then cp = compile(p) mem[p] = cp end return cp:match(s, i or 1) end local function find (s, p, i) local cp = fmem[p] if not cp then cp = compile(p) / 0 cp = mm.P{ mm.Cp() * cp * mm.Cp() + 1 * mm.V(1) } fmem[p] = cp end local i, e = cp:match(s, i or 1) if i then return i, e - 1 else return i end end local function gsub (s, p, rep) local g = gmem[p] or {} -- ensure gmem[p] is not collected while here gmem[p] = g local cp = g[rep] if not cp then cp = compile(p) cp = mm.Cs((cp / rep + 1)^0) g[rep] = cp end return cp:match(s) end -- exported names local re = { compile = compile, match = match, find = find, gsub = gsub, updatelocale = updatelocale, } if version == "Lua 5.1" then _G.re = re end return re
mit
Benjarobbi/UzzBott
plugins/media.lua
297
1590
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
qenter/vlc-android
vlc/share/lua/modules/dkjson.lua
95
25741
--[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.1* This module writes no global values, not even the module table. Import it using json = require ("dkjson") Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This is mainly useful for tables that can be empty. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.1"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the functions `quotestring` and `decode`. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable this option: --]==] local always_try_using_lpeg = true --[==[ In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. You can contact the author by sending an e-mail to 'kolf' at the e-mail provider 'gmx.de'. --------------------------------------------------------------------- *Copyright (C) 2010, 2011 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall = error, require, pcall local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local concat = table.concat local common = require ("common") local us_tostring = common.us_tostring if _VERSION == 'Lua 5.1' then local function noglobals (s,k,v) error ("global access: " .. k, 2) end setfenv (1, setmetatable ({}, { __index = noglobals, __newindex = noglobals })) end local _ENV = nil -- blocking globals in Lua 5.2 local json = { version = "dkjson 2.1" } pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = us_tostring (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local metatype = valmeta and valmeta.__jsontype local isa, n if metatype == 'array' then isa = true n = value.n or #value elseif metatype == 'object' then isa = false else isa, n = isarray (value) end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 1 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = tonumber (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end function json.decode (str, pos, nullval, objectmeta, arraymeta) objectmeta = objectmeta or {__jsontype = 'object'} arraymeta = arraymeta or {__jsontype = 'array'} return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") local pegmatch = g.match local P, S, R, V = g.P, g.S, g.R, g.V local SpecialChars = (R"\0\31" + S"\"\\\127" + P"\194" * (R"\128\159" + P"\173") + P"\216" * R"\128\132" + P"\220\132" + P"\225\158" * S"\180\181" + P"\226\128" * (R"\140\143" + S"\168\175") + P"\226\129" * R"\160\175" + P"\239\187\191" + P"\229\191" + R"\176\191") / escapeutf8 local QuoteStr = g.Cs (g.Cc "\"" * (SpecialChars + 1)^0 * g.Cc "\"") quotestring = function (str) return pegmatch (QuoteStr, str) end json.quotestring = quotestring local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/tonumber local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, objectmeta, arraymeta) local state = { objectmeta = objectmeta or {__jsontype = 'object'}, arraymeta = arraymeta or {__jsontype = 'array'} } local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
lichtl/darkstar
scripts/zones/Norg/npcs/Laisrean.lua
5
2353
----------------------------------- -- Area: Norg -- NPC: Laisrean -- Starts and Ends Quest: The Sahagin's Stash -- @zone 252 -- @pos -2.251 -1 21.654 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Stash = player:getQuestStatus(OUTLANDS,THE_SAHAGINS_STASH); mLvl = player:getMainLvl(); SeaStatue = player:hasKeyItem(SEA_SERPENT_STATUE); if (Stash == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 4 and mLvl >= 5) then player:startEvent(0x0021); -- Start quest elseif (Stash == QUEST_ACCEPTED) then if (SeaStatue == true) then player:startEvent(0x0023,SEA_SERPENT_STATUE); -- Finish quest else player:startEvent(0x0022); -- Reminder Dialogue end else player:startEvent(0x0053); -- Standard Conversation 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 == 0x0021 and option == 1) then player:addQuest(OUTLANDS,THE_SAHAGINS_STASH); elseif (csid == 0x0023) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4946); else player:delKeyItem(SEA_SERPENT_STATUE); player:addItem(4946); -- Scroll of Utsusemi: Ichi player:messageSpecial(ITEM_OBTAINED, 4946); player:addTitle(TREASUREHOUSE_RANSACKER); player:addFame(OUTLANDS,75); player:completeQuest(OUTLANDS,THE_SAHAGINS_STASH); end end end;
gpl-3.0
ali123345/ali-
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-3.0
telergybot/5252265
plugins/ingroup.lua
527
44020
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function user_msgs(user_id, chat_id) local user_info local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_user' then if not msg.service then -- return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end --[[if matches[1] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^[!/](add)$", "^[!/](add) (realm)$", "^[!/](rem)$", "^[!/](rem) (realm)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](promote)", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](kill) (chat)$", "^[!/](kill) (realm)$", "^[!/](demote) (.*)$", "^[!/](demote)", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](setowner)", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", -- "^[!/](public) (.*)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "^[!/](kickinactive)$", "^[!/](kickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
lichtl/darkstar
scripts/zones/Abyssea-Empyreal_Paradox/Zone.lua
33
1376
----------------------------------- -- -- Zone: Abyssea - Empyreal_Paradox -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Empyreal_Paradox/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Abyssea-Empyreal_Paradox/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(-495,0,483,205); -- BC Area player:setPos(540,-500,-565,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
lichtl/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Machionage.lua
14
1611
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Machionage -- @zone 80 -- @pos -255 -3 109 ----------------------------------- 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,0)) then player:startEvent(0x01C) -- Gifts of Griffon Trade end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x026B); -- 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 == 0x01C) then player:tradeComplete() local mask = player:getVar("GiftsOfGriffonPlumes"); player:setMaskBit(mask,"GiftsOfGriffonPlumes",0,true); end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Temple_of_Uggalepih/npcs/_4fx.lua
9
1492
----------------------------------- -- Area: Temple of Uggalepih -- NPC: Granite Door -- !pos 340 0.1 329 159 ----------------------------------- local ID = require("scripts/zones/Temple_of_Uggalepih/IDs") require("scripts/globals/keyitems") require("scripts/globals/missions") require("scripts/globals/npc_util") ----------------------------------- function onTrade(player, npc, trade) if npcUtil.tradeHas(trade, 1143) and player:getZPos() < 332 then -- Cursed Key if player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.AWAKENING_OF_THE_GODS and player:getCharVar("MissionStatus") == 4 then player:confirmTrade() player:startEvent(23) else player:confirmTrade() player:messageSpecial(ID.text.YOUR_KEY_BREAKS, 0, 1143) player:startEvent(25) end else player:messageSpecial(ID.text.NOTHING_HAPPENS) end end function onTrigger(player, npc) if player:getZPos() < 332 then player:messageSpecial(ID.text.DOOR_LOCKED) else player:startEvent(26) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if csid == 23 then player:setPos(340, 0, 333) player:delKeyItem(dsp.ki.BLANK_BOOK_OF_THE_GODS) player:addKeyItem(dsp.ki.BOOK_OF_THE_GODS) player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.BOOK_OF_THE_GODS) player:setCharVar("MissionStatus", 5) end end
gpl-3.0
lichtl/darkstar
scripts/globals/mobskills/red_lotus_blade.lua
18
1364
--------------------------------------------- -- red lotus blade -- -- Description: Delivers a four-hit attack. Chance of critical varies with TP. -- Type: Physical -- Shadow per hit -- Range: Melee --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/zones/Qubia_Arena/TextIDs"); require("scripts/zones/Throne_Room/TextIDs"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:getFamily() == 482) then target:showText(mob,NO_HIDE_AWAY); return 0; elseif (mob:getFamily() == 483) then target:showText(mob,RLB_PREPARE); return 0; else return 0; end end; function onMobWeaponSkill(target, mob, skill) if (mob:getFamily() == 482) then target:showText(mob,FEEL_MY_PAIN); elseif (mob:getFamily() == 483) then target:showText(mob,RLB_LAND); else mob:messageBasic(43, 0, 687+256); end skill:setSkillchain(40); local numhits = 4; local accmod = 1; local dmgmod = 1.25; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_CRIT_VARIES,1.1,1.2,1.3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); target:delHP(dmg); return dmg; end;
gpl-3.0
da03/OpenNMT
test/onmt/MemoryOptimizerTest.lua
8
1492
require('onmt.init') local tester = ... local memoryOptimizerTest = torch.TestSuite() local function testSequential(sequential, input, shareOutputs) local sequencer = onmt.Sequencer(sequential) sequencer:training() local memoryOptimizer = onmt.utils.MemoryOptimizer.new({ sequencer }) local output = sequencer:net(1):forward(input) local _ = sequencer:net(1):backward(input, output:clone():uniform(-0.1, 0.1)) memoryOptimizer:optimize() for i, m in ipairs(sequential.modules) do tester:eq(m.gradInputSharedIdx ~= nil, i > 1) tester:eq(m.outputSharedIdx ~= nil, shareOutputs[i]) end end local function testModule(mod, input, shareInput, shareOutput) local sequential = nn.Sequential() :add(nn.Copy(nil, nil, true, true)) :add(mod) :add(nn.Copy(nil, nil, true, true)) testSequential(sequential, input, { shareInput, shareOutput, false }) end function memoryOptimizerTest.exposedTensor() local sequential = nn.Sequential() :add(nn.Identity()) testSequential(sequential, torch.Tensor(5), { false }) end function memoryOptimizerTest.transferFunctions() local input = torch.Tensor(5):uniform(-0.1, 0.1) local transfers = { nn.Sigmoid(), nn.SoftMax(), nn.Tanh() } for _, t in ipairs(transfers) do testModule(t, input, true, false) end end function memoryOptimizerTest.linear() local input = torch.Tensor(5):uniform(-0.1, 0.1) testModule(nn.Linear(5, 10), input, false, true) end return memoryOptimizerTest
mit
NiLuJe/koreader
frontend/ui/widget/overlapgroup.lua
4
3209
--[[-- A layout widget that puts objects above each other. --]] local BD = require("ui/bidi") local Geom = require("ui/geometry") local WidgetContainer = require("ui/widget/container/widgetcontainer") local OverlapGroup = WidgetContainer:extend{ -- Note: we default to allow_mirroring = true. -- When using LeftContainer, RightContainer or HorizontalGroup -- in an OverlapGroup, mostly when they take the whole width, -- either OverlapGroup, or all the others, need to have -- allow_mirroring=false (otherwise, some upper mirroring would -- cancel a lower one...). -- It's usually safer to set it to false on the OverlapGroup, -- but some thinking is needed when many of them are nested. allow_mirroring = true, _size = nil, } function OverlapGroup:getSize() if not self._size then self._size = {w = 0, h = 0} self._offsets = { x = math.huge, y = math.huge } for i, widget in ipairs(self) do local w_size = widget:getSize() if self._size.h < w_size.h then self._size.h = w_size.h end if self._size.w < w_size.w then self._size.w = w_size.w end end end return self._size end -- NOTE: OverlapGroup is one of those special snowflakes that will compute self.dimen at init, -- instead of at paintTo... function OverlapGroup:init() self:getSize() -- populate self._size -- sync self._size with self.dimen, self.dimen has higher priority if self.dimen then -- Jump through some extra hoops because this may not be a Geom... if self.dimen.w then self._size.w = self.dimen.w end if self.dimen.h then self._size.h = self.dimen.h end end -- Regardless of what was passed to the constructor, make sure dimen is actually a Geom self.dimen = Geom:new{x = 0, y = 0, w = self._size.w, h = self._size.h} end function OverlapGroup:paintTo(bb, x, y) local size = self:getSize() for i, wget in ipairs(self) do local wget_size = wget:getSize() local overlap_align = wget.overlap_align if BD.mirroredUILayout() and self.allow_mirroring then -- Checks in the same order as how they are checked below if overlap_align == "right" then overlap_align = "left" elseif overlap_align == "center" then overlap_align = "center" elseif wget.overlap_offset then wget.overlap_offset[1] = size.w - wget_size.w - wget.overlap_offset[1] else overlap_align = "right" end -- see if something to do with wget.overlap_offset end if overlap_align == "right" then wget:paintTo(bb, x+size.w-wget_size.w, y) elseif overlap_align == "center" then wget:paintTo(bb, x+math.floor((size.w-wget_size.w)/2), y) elseif wget.overlap_offset then wget:paintTo(bb, x+wget.overlap_offset[1], y+wget.overlap_offset[2]) else -- default to left wget:paintTo(bb, x, y) end end end return OverlapGroup
agpl-3.0
RunAwayDSP/darkstar
scripts/zones/Northern_San_dOria/npcs/Andreas.lua
12
2331
----------------------------------- -- Area: Northern San d'Oria -- NPC: Andreas -- Type: Guildworker's Union Representative -- !pos -189.282 10.999 262.626 231 ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/crafting"); local ID = require("scripts/zones/Northern_San_dOria/IDs"); local keyitems = { [0] = { id = dsp.ki.WOOD_PURIFICATION, rank = 3, cost = 40000 }, [1] = { id = dsp.ki.WOOD_ENSORCELLMENT, rank = 3, cost = 40000 }, [2] = { id = dsp.ki.LUMBERJACK, rank = 3, cost = 10000 }, [3] = { id = dsp.ki.BOLTMAKER, rank = 3, cost = 10000 }, [4] = { id = dsp.ki.WAY_OF_THE_CARPENTER, rank = 9, cost = 20000 } }; local items = { [0] = { id = 15444, -- Carpenter's Belt rank = 1, cost = 10000 }, [1] = { id = 14830, -- Carpenter's Gloves rank = 5, cost = 70000 }, [2] = { id = 14392, -- Carpenter's Apron rank = 7, cost = 100000 }, [3] = { id = 28, -- Drawing Desk rank = 9, cost = 150000 }, [4] = { id = 341, -- Carpenter's Signboard rank = 9, cost = 200000 }, [5] = { id = 15819, -- Carpenter's Ring rank = 6, cost = 80000 }, [6] = { id = 3672, -- Carpenter's Kit rank = 8, cost = 50000 }, [7] = { id = 3331, -- Carpenter's Emblem rank = 9, cost = 15000 } }; function onTrade(player,npc,trade) unionRepresentativeTrade(player, npc, trade, 732, 1); end; function onTrigger(player,npc) unionRepresentativeTrigger(player, 1, 731, "guild_woodworking", keyitems); end; function onEventUpdate(player,csid,option,target) if (csid == 731) then unionRepresentativeTriggerFinish(player, option, target, 1, "guild_woodworking", keyitems, items); end end; function onEventFinish(player,csid,option,target) if (csid == 731) then unionRepresentativeTriggerFinish(player, option, target, 1, "guild_woodworking", keyitems, items); elseif (csid == 732) then player:messageSpecial(ID.text.GP_OBTAINED, option); end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/spells/paralyze.lua
12
1661
----------------------------------------- -- Spell: Paralyze -- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and MND. ----------------------------------------- require("scripts/globals/magic") require("scripts/globals/msg") require("scripts/globals/status") require("scripts/globals/utils") ----------------------------------------- function onMagicCastingCheck(caster, target, spell) return 0 end function onSpellCast(caster, target, spell) local dMND = caster:getStat(dsp.mod.MND) - target:getStat(dsp.mod.MND) -- Calculate potency. local potency = utils.clamp(math.floor(dMND / 4) + 15, 5, 25) potency = calculatePotency(potency, spell:getSkillType(), caster, target) -- Calculate duration. local duration = calculateDuration(120, spell:getSkillType(), spell:getSpellGroup(), caster, target) -- printf("Duration : %u",duration) -- printf("Potency : %u",potency) local params = {} params.diff = dMND params.skillType = dsp.skill.ENFEEBLING_MAGIC params.bonus = 0 params.effect = dsp.effect.PARALYSIS local resist = applyResistanceEffect(caster, target, spell, params) if resist >= 0.5 then -- There are no quarter or less hits, if target resists more than .5 spell is resisted completely if target:addStatusEffect(params.effect, potency, 0, duration * resist) then spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS) else -- no effect spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end else -- resist spell:setMsg(dsp.msg.basic.MAGIC_RESIST) end return params.effect end
gpl-3.0
lichtl/darkstar
scripts/globals/spells/enchanting_etude.lua
27
1848
----------------------------------------- -- Spell: Enchanting Etude -- Static CHR Boost, BRD 22 ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 0; if (sLvl+iLvl <= 181) then power = 3; elseif ((sLvl+iLvl >= 182) and (sLvl+iLvl <= 235)) then power = 4; elseif ((sLvl+iLvl >= 236) and (sLvl+iLvl <= 288)) then power = 5; elseif ((sLvl+iLvl >= 289) and (sLvl+iLvl <= 342)) then power = 6; elseif ((sLvl+iLvl >= 343) and (sLvl+iLvl <= 396)) then power = 7; elseif ((sLvl+iLvl >= 397) and (sLvl+iLvl <= 449)) then power = 8; elseif (sLvl+iLvl >= 450) then power = 9; end local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_ETUDE,power,0,duration,caster:getID(), MOD_CHR, 1)) then spell:setMsg(75); end return EFFECT_ETUDE; end;
gpl-3.0
qenter/vlc-android
vlc/share/lua/sd/icecast.lua
82
2757
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Fabio Ritrovato <sephiroth87 at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] lazily_loaded = false function lazy_load() if lazily_loaded then return nil end require "simplexml" lazily_loaded = true end function descriptor() return { title="Icecast Radio Directory" } end function dropnil(s) if s == nil then return "" else return s end end function main() lazy_load() local tree = simplexml.parse_url("http://dir.xiph.org/yp.xml") for _, station in ipairs( tree.children ) do simplexml.add_name_maps( station ) local station_name = station.children_map["server_name"][1].children[1] if station_name == "Unspecified name" or station_name == "" or station_name == nil then station_name = station.children_map["listen_url"][1].children[1] if string.find( station_name, "radionomy.com" ) then station_name = string.match( station_name, "([^/]+)$") station_name = string.gsub( station_name, "-", " " ) end end vlc.sd.add_item( {path=station.children_map["listen_url"][1].children[1], title=station_name, genre=dropnil(station.children_map["genre"][1].children[1]), nowplaying=dropnil(station.children_map["current_song"][1].children[1]), uiddata=station.children_map["listen_url"][1].children[1] .. dropnil(station.children_map["server_name"][1].children[1]), meta={ ["Listing Source"]="dir.xiph.org", ["Listing Type"]="radio", ["Icecast Bitrate"]=dropnil(station.children_map["bitrate"][1].children[1]), ["Icecast Server Type"]=dropnil(station.children_map["server_type"][1].children[1]) }} ) end end
gpl-2.0
NiLuJe/koreader
frontend/device/android/event_map.lua
9
1241
return { [29] = "A", [30] = "B", [31] = "C", [32] = "D", [33] = "E", [34] = "F", [35] = "G", [36] = "H", [37] = "I", [38] = "J", [39] = "K", [40] = "L", [41] = "M", [42] = "N", [43] = "O", [44] = "P", [45] = "Q", [46] = "R", [47] = "S", [48] = "T", [49] = "U", [50] = "V", [51] = "W", [52] = "X", [53] = "Y", [54] = "Z", [ 7] = "0", [ 8] = "1", [ 9] = "2", [10] = "3", [11] = "4", [12] = "5", [13] = "6", [14] = "7", [15] = "8", [16] = "9", [4] = "Back", -- BACK [19] = "Up", -- DPAD_UP [20] = "Down", -- DPAD_UP [21] = "Left", -- DPAD_LEFT [22] = "Right", -- DPAD_RIGHT [23] = "Press", -- DPAD_CENTER [24] = "LPgBack", -- VOLUME_UP [25] = "LPgFwd", -- VOLUME_DOWN [27] = "Camera", -- CAMERA [56] = ".", -- PERIOD [59] = "Shift", -- SHIFT_LEFT [60] = "Shift", -- SHIFT_RIGHT [62] = " ", -- SPACE [63] = "Sym", -- SYM [66] = "Press", -- ENTER [67] = "Del", -- DEL [76] = "/", -- SLASH [82] = "Menu", -- MENU [84] = "Search",--SEARCH [92] = "LPgBack", -- PAGE_UP [93] = "LPgFwd", -- PAGE_DOWN [104] = "LPgBack", -- T68 PageUp [109] = "LPgFwd", -- T68 PageDown [139] = "Menu", -- T68 Menu }
agpl-3.0
lichtl/darkstar
scripts/zones/Promyvion-Holla/mobs/Memory_Receptacle.lua
15
7516
----------------------------------- -- Area: Promyvion-Holla -- MOB: Memory Receptacle -- Todo: clean up disgustingly bad formatting ----------------------------------- package.loaded["scripts/zones/Promyvion-Holla/TextIDs"] = nil; ----------------------------------- require( "scripts/zones/Promyvion-Holla/TextIDs" ); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 100); -- 10% Regain for now mob:SetAutoAttackEnabled(false); -- Recepticles only use TP moves. end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local Mem_Recep = mob:getID(); if (Mem_Recep == 16842781) then -- Floor 1 for i = Mem_Recep+1, Mem_Recep+3 do -- Keep pets linked if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end elseif (Mem_Recep == 16842839 or Mem_Recep == 16842846 or Mem_Recep == 16842853 or Mem_Recep == 16842860) then -- Floor 2 for i = Mem_Recep+1, Mem_Recep+5 do if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end elseif (Mem_Recep == 16842886 or Mem_Recep == 16842895 or Mem_Recep == 16842904 or Mem_Recep == 16842938 or Mem_Recep == 16842947 or -- Floor 3 Mem_Recep == 16842956) then for i = Mem_Recep+1, Mem_Recep+7 do if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end end -- Summons a single stray every 30 seconds. if (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16842781) and mob:AnimationSub() == 2) then -- Floor 1 for i = Mem_Recep+1, Mem_Recep+3 do if (GetMobAction(i) == 0) then -- My Stray is deeaaaaaad! mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle return; end end elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16842839 or Mem_Recep == 16842846 or Mem_Recep == 16842853 or -- Floor 2 Mem_Recep == 16842860) and mob:AnimationSub() == 2) then for i = Mem_Recep+1, Mem_Recep+5 do if (GetMobAction(i) == 0) then mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle return; end end elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16842886 or Mem_Recep == 16842895 or Mem_Recep == 16842904 or -- Floor 3 Mem_Recep == 16842938 or Mem_Recep == 16842947 or Mem_Recep == 16842956) and mob:AnimationSub() == 2) then for i = Mem_Recep+1, Mem_Recep+7 do if (GetMobAction(i) == 0) then mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); return; end end else mob:AnimationSub(2); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) local rand = 0; local mobID = mob:getID(); local difX = player:getXPos()-mob:getXPos(); local difY = player:getYPos()-mob:getYPos(); local difZ = player:getZPos()-mob:getZPos(); local killeranimation = player:getAnimation(); local Distance = math.sqrt( math.pow(difX,2) + math.pow(difY,2) + math.pow(difZ,2) ); --calcul de la distance entre les "killer" et le memory receptacle -- print(mob:getID); mob:AnimationSub(0); -- Set ani. sub to default or the recepticles wont work properly if (VanadielMinute() % 2 == 1) then player:setVar("MemoryReceptacle",2); rnd = 2; else player:setVar("MemoryReceptacle",1); rnd = 1; end switch (mob:getID()) : caseof { [16842781] = function (x) GetNPCByID(16843057):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x0025); end end, [16842839] = function (x) GetNPCByID(16843053):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd == 2) then player:startEvent(0x0021); else player:startEvent(0x0022); end end end, [16842846] = function (x) GetNPCByID(16843054):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd == 2) then player:startEvent(0x0021); else player:startEvent(0x0022); end end end, [16842860] = function (x) GetNPCByID(16843056):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd == 2) then player:startEvent(0x0021); else player:startEvent(0x0022); end end end, [16842853] = function (x) GetNPCByID(16843055):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd == 2) then player:startEvent(0x0021); else player:startEvent(0x0022); end end end, [16842886] = function (x) GetNPCByID(16843050):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E); end end, [16842895] = function (x) GetNPCByID(16843051):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E); end end, [16842904] = function (x) GetNPCByID(16843052):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E) end end, [16842938] = function (x) GetNPCByID(16843058):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E); end end, [16842947] = function (x) GetNPCByID(16843059):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E); end end, [16842956] = function (x) GetNPCByID(16843060):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E); end end, } end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ---------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (option==1) then player:setVar("MemoryReceptacle",0); end end;
gpl-3.0
Anarchid/Zero-K
LuaRules/Gadgets/cmd_block_ally_attack.lua
5
2588
function gadget:GetInfo() return { name = "Block Ally and Neutral Attack", desc = "Blocks attack command from being issued on allies and neutrals.", author = "GoogleFrog", date = "29 July 2017", license = "GNU GPL, v2 or later", layer = 0, enabled = true, } end include("LuaRules/Configs/customcmds.h.lua") local allyTeamByTeam = {} local teamList = Spring.GetTeamList() for i = 1, #teamList do local allyTeamID = select(6, Spring.GetTeamInfo(teamList[i], false)) allyTeamByTeam[teamList[i]] = allyTeamID end local CMD_ATTACK = CMD.ATTACK local CMD_INSERT = CMD.INSERT local allyTargetUnits = { [UnitDefNames["jumpsumo"].id] = true, [UnitDefNames["turretimpulse"].id] = true, [UnitDefNames["jumpblackhole"].id] = true, [UnitDefNames["amphlaunch"].id] = true, } ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- if gadgetHandler:IsSyncedCode() then -- SYNCED ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions) if allyTargetUnits[unitDefID] then return true end local targetID if cmdID == CMD_INSERT and cmdParams[2] == CMD_ATTACK and #cmdParams == 4 then targetID = cmdParams[4] end if cmdID == CMD_ATTACK and #cmdParams == 1 then targetID = cmdParams[1] end if not targetID then return true end if Spring.GetUnitNeutral(targetID) then if Spring.GetUnitRulesParam(targetID, "avoidAttackingNeutral") == 1 then return false end return true end local allyTeamID = Spring.GetUnitAllyTeam(targetID) if allyTeamID and allyTeamID == allyTeamByTeam[teamID] then return false end return true end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- else -- UNSYNCED ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function gadget:DefaultCommand(targetType, targetID) if (targetType == 'unit') and targetID and Spring.GetUnitNeutral(targetID) then if (Spring.GetUnitRulesParam(targetID, "avoidAttackingNeutral") == 1) or (Spring.GetUnitRulesParam(targetID, "avoidRightClickAttack") == 1) then return CMD_RAW_MOVE end end end end
gpl-2.0
Anarchid/Zero-K
effects/fires.lua
7
10955
-- flamer -- fire1_burn1_flame1 -- fire1_smoke1 -- fire1_burnlight -- fire1_burn1_flame3 -- fire1_burn1_flame4 -- fire1_burn1 -- fire1_burn1_flame2 -- fire1 return { ["flamer"] = { fire = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[0.7 0.7 0.7 0.01 1 0.3 0.3 0.5 0 0 0 0]], directional = true, --emitmul = [[0, 2, 0]], emitrot = 0, emitrotspread = 0, emitvector = [[dir]], gravity = [[0.2 r-0.4, 0.2, 0.2 r-0.4]], numparticles = 1, particlelife = 12, particlelifespread = 6, particlesize = 8, particlesizespread = 4, particlespeed = 0.1, particlespeedspread = 0.1, pos = [[6 r-12, 6 r-12, 6 r-12]], sizegrowth = 1, sizemod = 1.0, texture = [[flame]], }, }, }, ["flamer_koda"] = { fire = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[0.7 0.7 0.7 0.01 1 0.5 0.5 0.5 0 0 0 0]], directional = true, emitrot = 0, emitrotspread = 0, emitvector = [[dir]], gravity = [[0.15 r-0.3, 0.2 r-0.3, 0.15 r-0.3]], numparticles = 1, particlelife = 8, particlelifespread = 5, particlesize = 8, particlesizespread = 4, particlespeed = 0.1, particlespeedspread = 0.1, pos = [[6 r-12, 6 r-12, 6 r-12]], sizegrowth = 0.7, sizemod = 1.0, texture = [[flame]], }, }, }, ["gravityless_flamer"] = { fire = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[0.7 0.7 0.7 0.01 1 0.3 0.3 0.5 0 0 0 0]], directional = true, --emitmul = [[0, 2, 0]], emitrot = 0, emitrotspread = 0, emitvector = [[dir]], gravity = [[0.2 r-0.4, 0.2-r0.4, 0.2 r-0.4]], numparticles = 1, particlelife = 12, particlelifespread = 6, particlesize = 8, particlesizespread = 4, particlespeed = 0.1, particlespeedspread = 0.1, pos = [[6 r-12, 6 r-12, 6 r-12]], sizegrowth = 1, sizemod = 1.0, texture = [[flame]], }, }, }, ["fire1_burn1_flame1"] = { fire = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[0 0 0 0.01 1 1 1 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 15.3, particlelifespread = 0, particlesize = 5.23, particlesizespread = 10.23, particlespeed = 0, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[fire1]], }, }, }, ["fire1_smoke1"] = { fire = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0 0 0 0.01 1 1 1 1 0.7 0.7 0.7 1 0.5 0.5 0.5 0.7 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 5, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0.05]], numparticles = 1, particlelife = 30, particlelifespread = 30, particlesize = 9, particlesizespread = 11, particlespeed = 2, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0.05, sizemod = 1.0, texture = [[orangesmoke]], }, }, }, ["fire1_burnlight"] = { air = true, count = 1, ground = true, usedefaultexplosions = false, water = true, groundflash = { circlealpha = 1, circlegrowth = 1, flashalpha = 1, flashsize = 20, ttl = 15, color = { [1] = 1, [2] = 0.44999998807907, [3] = 0.69999998807907, }, }, }, ["fire1_burn1_flame3"] = { fire = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[0 0 0 0.01 1 1 1 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 15.3, particlelifespread = 0, particlesize = 5.23, particlesizespread = 10.23, particlespeed = 0, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[fire3]], }, }, }, ["fire1_burn1_flame4"] = { fire = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[0 0 0 0.01 1 1 1 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 15.3, particlelifespread = 0, particlesize = 5.23, particlesizespread = 10.23, particlespeed = 0, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[fire4]], }, }, }, ["fire1_burn1"] = { flame1 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:FIRE1_BURN1_FLAME1]], pos = [[0, 1, 0]], }, }, flame2 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 5, explosiongenerator = [[custom:FIRE1_BURN1_FLAME2]], pos = [[0, 1, 0]], }, }, flame3 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 10, explosiongenerator = [[custom:FIRE1_BURN1_FLAME3]], pos = [[0, 1, 0]], }, }, flame4 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 15, explosiongenerator = [[custom:FIRE1_BURN1_FLAME4]], pos = [[0, 1, 0]], }, }, }, ["fire1_burn1_flame2"] = { fire = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[0 0 0 0.01 1 1 1 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 15.3, particlelifespread = 0, particlesize = 5.23, particlesizespread = 10.23, particlespeed = 0, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[fire2]], }, }, }, ["fire1"] = { flame = { air = true, class = [[CExpGenSpawner]], count = 5, ground = true, water = true, properties = { delay = [[0 i20]], explosiongenerator = [[custom:FIRE1_BURN1]], pos = [[0, 1, 0]], }, }, groundflash = { air = true, class = [[CExpGenSpawner]], count = 100, ground = true, water = true, properties = { delay = [[0 i1]], explosiongenerator = [[custom:FIRE1_BURNLIGHT]], pos = [[0, 1, 0]], }, }, smoke1 = { air = true, class = [[CExpGenSpawner]], count = 100, ground = true, water = true, properties = { delay = [[0 i1]], explosiongenerator = [[custom:FIRE1_SMOKE1]], pos = [[0, 1, 0]], }, }, }, }
gpl-2.0
PichotM/DarkRP
gamemode/modules/hitmenu/sh_init.lua
5
3198
local plyMeta = FindMetaTable("Player") local hitmanTeams = {} local minHitDistanceSqr = GM.Config.minHitDistance * GM.Config.minHitDistance function plyMeta:isHitman() return hitmanTeams[self:Team()] end function plyMeta:hasHit() return self:getDarkRPVar("hasHit") or false end function plyMeta:getHitTarget() return self:getDarkRPVar("hitTarget") end function plyMeta:getHitPrice() return self:getDarkRPVar("hitPrice") or GAMEMODE.Config.minHitPrice end function DarkRP.addHitmanTeam(job) if not job or not RPExtraTeams[job] then return end if DarkRP.DARKRP_LOADING and DarkRP.disabledDefaults["hitmen"][RPExtraTeams[job].command] then return end hitmanTeams[job] = true end DarkRP.getHitmanTeams = fp{fn.Id, hitmanTeams} function DarkRP.hooks:canRequestHit(hitman, customer, target, price) if not hitman:isHitman() then return false, DarkRP.getPhrase("player_not_hitman") end if customer:GetPos():DistToSqr(hitman:GetPos()) > minHitDistanceSqr then return false, DarkRP.getPhrase("distance_too_big") end if hitman == target then return false, DarkRP.getPhrase("hitman_no_suicide") end if hitman == customer then return false, DarkRP.getPhrase("hitman_no_self_order") end if not customer:canAfford(price) then return false, DarkRP.getPhrase("cant_afford", DarkRP.getPhrase("hit")) end if price < GAMEMODE.Config.minHitPrice then return false, DarkRP.getPhrase("price_too_low") end if hitman:hasHit() then return false, DarkRP.getPhrase("hitman_already_has_hit") end if IsValid(target) and ((target:getDarkRPVar("lastHitTime") or -GAMEMODE.Config.hitTargetCooldown) > CurTime() - GAMEMODE.Config.hitTargetCooldown) then return false, DarkRP.getPhrase("hit_target_recently_killed_by_hit") end if IsValid(customer) and ((customer.lastHitAccepted or -GAMEMODE.Config.hitCustomerCooldown) > CurTime() - GAMEMODE.Config.hitCustomerCooldown) then return false, DarkRP.getPhrase("customer_recently_bought_hit") end return true end hook.Add("onJobRemoved", "hitmenuUpdate", function(i, job) hitmanTeams[i] = nil end) --[[--------------------------------------------------------------------------- DarkRPVars ---------------------------------------------------------------------------]] DarkRP.registerDarkRPVar("hasHit", net.WriteBit, fn.Compose{tobool, net.ReadBit}) DarkRP.registerDarkRPVar("hitTarget", net.WriteEntity, net.ReadEntity) DarkRP.registerDarkRPVar("hitPrice", fn.Curry(fn.Flip(net.WriteInt), 2)(32), fn.Partial(net.ReadInt, 32)) DarkRP.registerDarkRPVar("lastHitTime", fn.Curry(fn.Flip(net.WriteInt), 2)(32), fn.Partial(net.ReadInt, 32)) --[[--------------------------------------------------------------------------- Chat commands ---------------------------------------------------------------------------]] DarkRP.declareChatCommand{ command = "hitprice", description = "Set the price of your hits", condition = plyMeta.isHitman, delay = 10 } DarkRP.declareChatCommand{ command = "requesthit", description = "Request a hit from the player you're looking at", delay = 5, condition = fn.Compose{fn.Not, fn.Null, fn.Curry(fn.Filter, 2)(plyMeta.isHitman), player.GetAll} }
mit
amircheshme/megatron
plugins/gnuplot.lua
622
1813
--[[ * Gnuplot plugin by psykomantis * dependencies: * - gnuplot 5.00 * - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html * ]] -- Gnuplot needs absolute path for the plot, so i run some commands to find where we are local outputFile = io.popen("pwd","r") io.input(outputFile) local _pwd = io.read("*line") io.close(outputFile) local _absolutePlotPath = _pwd .. "/data/plot.png" local _scriptPath = "./data/gnuplotScript.gpl" do local function gnuplot(msg, fun) local receiver = get_receiver(msg) -- We generate the plot commands local formattedString = [[ set grid set terminal png set output "]] .. _absolutePlotPath .. [[" plot ]] .. fun local file = io.open(_scriptPath,"w"); file:write(formattedString) file:close() os.execute("gnuplot " .. _scriptPath) os.remove (_scriptPath) return _send_photo(receiver, _absolutePlotPath) end -- Check all dependencies before executing local function checkDependencies() local status = os.execute("gnuplot -h") if(status==true) then status = os.execute("gnuplot -e 'set terminal png'") if(status == true) then return 0 -- OK ready to go! else return 1 -- missing libgd2-xpm-dev end else return 2 -- missing gnuplot end end local function run(msg, matches) local status = checkDependencies() if(status == 0) then return gnuplot(msg,matches[1]) elseif(status == 1) then return "It seems that this bot miss a dependency :/" else return "It seems that this bot doesn't have gnuplot :/" end end return { description = "use gnuplot through telegram, only plot single variable function", usage = "!gnuplot [single variable function]", patterns = {"^!gnuplot (.+)$"}, run = run } end
gpl-2.0
mnemnion/grym
src/Orbit/header.lua
1
1316
local L = require "lpeg" local Node = require "espalier/node" local m = require "Orbit/morphemes" local H = setmetatable({}, { __index = Node }) H.id = "header" H.__index = H H.__tostring = function(header) return "Lvl " .. tostring(header.level) .. " ^: " .. tostring(header.line) end function H.dotLabel(header) return tostring(header.level) .. " : " .. header.line end function H.toMarkdown(header) local haxen = "" if header.level > 0 then haxen = ("#"):rep(header.level) end return haxen .. " " .. header.line end local h = {} function h.match(str) if str ~= "" and L.match(m.header, str) then local trimmed = str:sub(L.match(m.WS, str)) local level = L.match(m.tars, trimmed) - 1 local bareline = trimmed:sub(L.match(m.tars * m.WS, trimmed)) return true, level, bareline else return false, 0, "" end end local function new(Header, line, level, first, last, str) local header = setmetatable({}, H) header.line = line header.level = level header.first = first header.last = last header.str = str return header end function H.howdy() io.write("Why hello!\n") end h.__call = new h.__index = h return setmetatable({}, h)
mit
Whit3Tig3R/bestspammbot2
plugins/quotes.lua
651
1630
local quotes_file = './data/quotes.lua' local quotes_table function read_quotes_file() local f = io.open(quotes_file, "r+") if f == nil then print ('Created a new quotes file on '..quotes_file) serialize_to_file({}, quotes_file) else print ('Quotes loaded: '..quotes_file) f:close() end return loadfile (quotes_file)() end function save_quote(msg) local to_id = tostring(msg.to.id) if msg.text:sub(11):isempty() then return "Usage: !addquote quote" end if quotes_table == nil then quotes_table = {} end if quotes_table[to_id] == nil then print ('New quote key to_id: '..to_id) quotes_table[to_id] = {} end local quotes = quotes_table[to_id] quotes[#quotes+1] = msg.text:sub(11) serialize_to_file(quotes_table, quotes_file) return "done!" end function get_quote(msg) local to_id = tostring(msg.to.id) local quotes_phrases quotes_table = read_quotes_file() quotes_phrases = quotes_table[to_id] return quotes_phrases[math.random(1,#quotes_phrases)] end function run(msg, matches) if string.match(msg.text, "!quote$") then return get_quote(msg) elseif string.match(msg.text, "!addquote (.+)$") then quotes_table = read_quotes_file() return save_quote(msg) end end return { description = "Save quote", description = "Quote plugin, you can create and retrieve random quotes", usage = { "!addquote [msg]", "!quote", }, patterns = { "^!addquote (.+)$", "^!quote$", }, run = run }
gpl-2.0
alireza1998/supergroup
plugins/quotes.lua
651
1630
local quotes_file = './data/quotes.lua' local quotes_table function read_quotes_file() local f = io.open(quotes_file, "r+") if f == nil then print ('Created a new quotes file on '..quotes_file) serialize_to_file({}, quotes_file) else print ('Quotes loaded: '..quotes_file) f:close() end return loadfile (quotes_file)() end function save_quote(msg) local to_id = tostring(msg.to.id) if msg.text:sub(11):isempty() then return "Usage: !addquote quote" end if quotes_table == nil then quotes_table = {} end if quotes_table[to_id] == nil then print ('New quote key to_id: '..to_id) quotes_table[to_id] = {} end local quotes = quotes_table[to_id] quotes[#quotes+1] = msg.text:sub(11) serialize_to_file(quotes_table, quotes_file) return "done!" end function get_quote(msg) local to_id = tostring(msg.to.id) local quotes_phrases quotes_table = read_quotes_file() quotes_phrases = quotes_table[to_id] return quotes_phrases[math.random(1,#quotes_phrases)] end function run(msg, matches) if string.match(msg.text, "!quote$") then return get_quote(msg) elseif string.match(msg.text, "!addquote (.+)$") then quotes_table = read_quotes_file() return save_quote(msg) end end return { description = "Save quote", description = "Quote plugin, you can create and retrieve random quotes", usage = { "!addquote [msg]", "!quote", }, patterns = { "^!addquote (.+)$", "^!quote$", }, run = run }
gpl-2.0
alex85k/osm2pgsql
multi.lua
6
9017
-- This is an example Lua transform for a multi style -- It is not intended for use directly with --tag-transform-script but -- for use from multi.style.json -- -- See docs/lua.md and docs/multi.md -- These are copied from default.style -- If new "tags" are being generated in the Lua code they should normally be -- added here. This is why name_.* is dropped. In the raw OSM data -- multi-lingual names are stored in name:*. delete_tags = {'name_.*', 'note', 'note:.*', 'source', 'source_ref', 'source:.*', 'attribution', 'comment', 'fixme', 'created_by', 'odbl', 'odbl:note', 'SK53_bulk:load', 'tiger:.*', 'NHD:.*', 'nhd:.*', 'gnis:.*', 'geobase:.*', 'accuracy:meters', 'sub_sea:type', 'waterway:type', 'KSJ2:.*', 'yh:.*', 'osak:.*', 'kms:.*', 'ngbe:.*', 'naptan:.*', 'CLC:.*', '3dshapes:ggmodelk', 'AND_nosr_r', 'import', 'it:fvg:.*'} -- In a real transform the Lua code might be split into multiple files with -- common code included with "dofile" but a single file is easier for an example -- A function to determine if the tags make the object "interesting" to the -- buildings table function building_interesting (kv) return kv["building"] and kv["building"] ~= "no" end function building_transform (kv) kv["name_en"] = name_lang(kv, "en") kv["name_de"] = name_lang(kv, "de") kv["name_fr"] = name_lang(kv, "fr") return kv end -- If we weren't generating multilingual names we could omit building_transform function building_ways (kv, num_keys) return generic_ways(building_interesting, kv, true, building_transform) end function building_rels (kv, num_keys) return generic_rels(building_interesting, kv) end function building_rel_members (kv, keyvaluemembers, roles, membercount) return generic_rel_members(building_interesting, kv, keyvaluemembers, roles, membercount, building_transform) end -- A function to determine if the tags make the object "interesting" to the -- bus stop table function bus_interesting (kv) return kv["highway"] == "bus_stop" end function bus_transform (kv) kv["shelter"] = yesno(kv["shelter"]) kv["bench"] = yesno(kv["bench"]) kv["wheelchair"] = yesno(kv["wheelchair"]) kv["name_en"] = name_lang(kv, "en") kv["name_de"] = name_lang(kv, "de") kv["name_fr"] = name_lang(kv, "fr") return kv end function bus_nodes (kv, num_keys) return generic_nodes(bus_interesting, kv, bus_transform) end -- lookup tables for highways. Using an enum would be better in some ways, but -- would require creating the type before importing with osm2pgsql, which is -- not well suited to an example. highway_lookup = {motorway = 0, trunk = 1, primary = 2, secondary = 3, tertiary = 4, unclassified = 5, residential = 5} link_lookup = {motorway_link = 0, trunk_link = 1, primary_link = 2, secondary_link = 3, tertiary_link = 4} function highway_interesting (kv) -- The kv["highway"] check is not necessary but helps performance return kv["highway"] and (highway_lookup[kv["highway"]] or link_lookup[kv["highway"]]) end function highway_transform (kv) -- Thanks to highway_interesting we know that kv["highway"] is in one of -- highway_lookup or link_lookup kv["road_class"] = highway_lookup[kv["highway"]] or link_lookup[kv["highway"]] -- This is a lua way of doing an inline conditional kv["road_type"] = highway_lookup[kv["highway"]] and "road" or "link" kv["name_en"] = name_lang(kv, "en") kv["name_de"] = name_lang(kv, "de") kv["name_fr"] = name_lang(kv, "fr") return kv end function highway_ways (kv, num_keys) return generic_ways(highway_interesting, kv, false, highway_transform) end -- Some generic and utility helper functions -- This function normalizes a tag to true/false. It turns no or false into -- false and anything else to true. The result can then be used with a -- boolean column. -- > = yesno(nil) -- nil -- > = yesno("no") -- false -- > = yesno("false") -- false -- > = yesno("yes") -- true -- > = yesno("foo") -- true -- -- A typical usage would be on a tag like bridge, tunnel, or shelter, but not -- a tag like oneway which could be yes, no, reverse, or unset function yesno (v) -- This is a way of doing an inline condition in Lua return v ~= nil and ((v == "no" or v == "false") and "false" or "true") or nil end -- Converts a name and name:lang tag into one combined name -- By passing an optional name_tag parameter it can also work with other -- multi-lingual tags function name_lang(kv, lang, name_tag) if kv then -- Default to the name tag, which is what this will generally be used on. name_tag = name_tag or "name" -- Defaulting to en is a bit of complete Anglo-centrism lang = lang or "en" name = kv[name_tag] name_trans = kv[name_tag .. ":" .. lang] -- If we don't have a translated name, just use the name (which may be blank) if not name_trans then return name end -- If we do have a translated name and not a local language name, use the translated if not name then return name_trans end -- if they're the same, return one of them if name == name_trans then return name end -- This method presents some problems when multiple names get put in the -- name tag. return name_trans .. "(" .. name .. ")" end end -- This function gets rid of an object we don't care about function drop_all (...) return 1, {} end -- This eliminates tags to be deleted function preprocess_tags (kv) tags = {} for k, v in pairs (kv) do match = false for _, d in ipairs(delete_tags) do match = match or string.find(k, d) end if not match then tags[k] = v end end return tags end -- A generic way to process nodes, given a function which determines if tags are interesting -- Takes an optional function to process tags function generic_nodes (f, kv, t) if f(kv) then t = t or function (kv) return kv end tags = t(kv) return 0, tags else return 1, {} end end -- A generic way to process ways, given a function which determines if tags are interesting -- Takes an optional function to process tags. function generic_ways (interesting, kv, area, transform) if interesting(kv) then t = transform or function (kv) return kv end tags = t(preprocess_tags(kv)) return 0, tags, area and 1 or 0, 0 else return 1, {}, 0, 0 end end -- A generic way to process relations, given a function which determines if -- tags are interesting. The tag transformation work is done in -- generic_rel_members so we don't need to pass in a transformation function. function generic_rels (f, kv) if kv["type"] == "multipolygon" and f(kv) then tags = kv return 0, tags else return 1, {} end end -- Basically taken from style.lua, with the potential for a transform added function generic_rel_members (f, keyvals, keyvaluemembers, roles, membercount, transform) filter = 0 boundary = 0 polygon = 0 roads = 0 t = transform or function (kv) return kv end --mark each way of the relation to tell the caller if its going --to be used in the relation or by itself as its own standalone way --we start by assuming each way will not be used as part of the relation membersuperseeded = {} for i = 1, membercount do membersuperseeded[i] = 0 end --remember the type on the relation and erase it from the tags type = keyvals["type"] keyvals["type"] = nil if (type == "multipolygon") and keyvals["boundary"] == nil then --check if this relation has tags we care about polygon = 1 filter = f(keyvals) --if the relation didn't have the tags we need go grab the tags from --any members that are marked as outers of the multipolygon if (filter == 1) then for i = 1,membercount do if (roles[i] == "outer") then for j,k in ipairs(tags) do v = keyvaluemembers[i][k] if v then keyvals[k] = v filter = 0 end end end end end if filter == 1 then tags = t(keyvals) return filter, tags, membersuperseeded, boundary, polygon, roads end --for each tag of each member if the relation have the tag or has a non matching value for it --then we say the member will not be used in the relation and is there for not superseeded --ie it is kept as a standalone way for i = 1,membercount do superseeded = 1 for k,v in pairs(keyvaluemembers[i]) do if ((keyvals[k] == nil) or (keyvals[k] ~= v)) then superseeded = 0; break end end membersuperseeded[i] = superseeded end end tags = t(keyvals) return filter, tags, membersuperseeded, boundary, polygon, roads end
gpl-2.0
jerizm/kong
spec/01-unit/08-entities_schemas_spec.lua
3
17098
local api_schema = require "kong.dao.schemas.apis" local consumer_schema = require "kong.dao.schemas.consumers" local plugins_schema = require "kong.dao.schemas.plugins" local validations = require "kong.dao.schemas_validation" local validate_entity = validations.validate_entity --require "kong.tools.ngx_stub" describe("Entities Schemas", function() for k, schema in pairs({api = api_schema, consumer = consumer_schema, plugins = plugins_schema}) do it(k.." schema should have some required properties", function() assert.is_table(schema.primary_key) assert.is_table(schema.fields) assert.is_string(schema.table) end) end -- -- API -- describe("APIs", function() it("should refuse an empty object", function() local valid, errors = validate_entity({}, api_schema) assert.False(valid) assert.truthy(errors) end) describe("name", function() it("should not accept a name with reserved URI characters in it", function() for _, name in ipairs({"mockbin#2", "mockbin/com", "mockbin\"", "mockbin:2", "mockbin?", "[mockbin]"}) do local t = {name = name, upstream_url = "http://mockbin.com", request_host = "mockbin.com"} local valid, errors = validate_entity(t, api_schema) assert.False(valid) assert.truthy(errors) assert.equal("name must only contain alphanumeric and '., -, _, ~' characters", errors.name) end end) end) describe("upstream_url", function() it("should return error with wrong upstream_url", function() local valid, errors = validate_entity({ name = "mockbin", request_host = "mockbin.com", upstream_url = "asdasd" }, api_schema) assert.False(valid) assert.equal("upstream_url is not a url", errors.upstream_url) end) it("should return error with wrong upstream_url protocol", function() local valid, errors = validate_entity({ name = "mockbin", request_host = "mockbin.com", upstream_url = "wot://mockbin.com/" }, api_schema) assert.False(valid) assert.equal("Supported protocols are HTTP and HTTPS", errors.upstream_url) end) it("should validate with upper case protocol", function() local valid, errors = validate_entity({ name = "mockbin", request_host = "mockbin.com", upstream_url = "HTTP://mockbin.com/world" }, api_schema) assert.falsy(errors) assert.True(valid) end) end) describe("request_host", function() it("should complain if it is an empty string", function() local t = {request_host = "", upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.False(valid) assert.equal("At least a 'request_host' or a 'request_path' must be specified", errors.request_host) assert.equal("At least a 'request_host' or a 'request_path' must be specified", errors.request_path) end) it("should not accept an invalid request_host", function() local invalids = {"/mockbin", ".mockbin", "mockbin.", "mock;bin", "mockbin.com/org", "mockbin-.org", "mockbin.org-", "hello..mockbin.com", "hello-.mockbin.com"} for _, v in ipairs(invalids) do local t = {request_host = v, upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.equal("Invalid value: "..v, (errors and errors.request_host or "")) assert.falsy(errors.request_path) assert.False(valid) end end) it("should accept valid request_host", function() local valids = {"hello.com", "hello.fr", "test.hello.com", "1991.io", "hello.COM", "HELLO.com", "123helloWORLD.com", "mockbin.123", "mockbin-api.com", "hello.abcd", "mockbin_api.com", "localhost", -- punycode examples from RFC3492; https://tools.ietf.org/html/rfc3492#page-14 -- specifically the japanese ones as they mix ascii with escaped characters "3B-ww4c5e180e575a65lsy2b", "-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n", "Hello-Another-Way--fc4qua05auwb3674vfr0b", "2-u9tlzr9756bt3uc0v", "MajiKoi5-783gue6qz075azm5e", "de-jg4avhby1noc0d", "d9juau41awczczp", } for _, v in ipairs(valids) do local t = {request_host = v, upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.falsy(errors) assert.True(valid) end end) it("should accept valid wildcard request_host", function() local valids = {"mockbin.*", "*.mockbin.org"} for _, v in ipairs(valids) do local t = {request_host = v, upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.falsy(errors) assert.True(valid) end end) it("should refuse request_host with more than one wildcard", function() local api_t = { name = "mockbin", request_host = "*.mockbin.*", upstream_url = "http://mockbin.com" } local valid, errors = validate_entity(api_t, api_schema) assert.False(valid) assert.equal("Only one wildcard is allowed: *.mockbin.*", errors.request_host) end) it("should refuse invalid wildcard request_host", function() local invalids = {"*mockbin.com", "www.mockbin*", "mock*bin.com"} for _, v in ipairs(invalids) do local t = {request_host = v, upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.equal("Invalid wildcard placement: "..v, (errors and errors.request_host or "")) assert.False(valid) end end) end) describe("request_path", function() it("should complain if it is an empty string", function() local t = {request_path = "", upstream_url = "http://mockbin.com"} local valid, errors = validate_entity(t, api_schema) assert.False(valid) assert.equal("At least a 'request_host' or a 'request_path' must be specified", errors.request_host) assert.equal("At least a 'request_host' or a 'request_path' must be specified", errors.request_path) end) it("should not accept reserved characters from RFC 3986", function() local invalids = {"/[a-z]{3}"} for _, v in ipairs(invalids) do local t = {request_path = v, upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.False(valid) assert.equal("must only contain alphanumeric and '., -, _, ~, /, %' characters", errors.request_path) end end) it("should accept unreserved characters from RFC 3986", function() local valids = {"/abcd~user-2"} for _, v in ipairs(valids) do local t = {request_path = v, upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.falsy(errors) assert.True(valid) end end) it("should not accept bad %-encoded characters", function() local invalids = { "/some%2words", "/some%0Xwords", "/some%2Gwords", "/some%20words%", "/some%20words%a", "/some%20words%ax", } local errstr = { "%2w", "%0X", "%2G", "%", "%a", "%ax" } for i, v in ipairs(invalids) do local t = {request_path = v, upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.False(valid) assert.equal("must use proper encoding; '"..errstr[i].."' is invalid", errors.request_path) end end) it("should accept properly %-encoded characters", function() local valids = {"/abcd%aa%10%ff%AA%FF"} for _, v in ipairs(valids) do local t = {request_path = v, upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.falsy(errors) assert.True(valid) end end) it("should not accept without prefix slash", function() local invalids = {"status", "status/123"} for _, v in ipairs(invalids) do local t = {request_path = v, upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.False(valid) assert.equal("must be prefixed with slash: '"..v.."'", errors.request_path) end end) it("should accept root (prefix slash)", function() local valid, errors = validate_entity({ name = "mockbin", request_path = "/", upstream_url = "http://mockbin.com" }, api_schema) assert.falsy(errors) assert.True(valid) end) it("should not accept invalid URI", function() local invalids = {"//status", "/status//123", "/status/123//"} for _, v in ipairs(invalids) do local t = {request_path = v, upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.False(valid) assert.equal("invalid: '"..v.."'", errors.request_path) end end) it("should remove trailing slash", function() local valids = {"/status/", "/status/123/"} for _, v in ipairs(valids) do local t = {request_path = v, upstream_url = "http://mockbin.com", name = "mockbin"} local valid, errors = validate_entity(t, api_schema) assert.falsy(errors) assert.equal(string.sub(v, 1, -2), t.request_path) assert.True(valid) end end) end) it("should validate without a request_path", function() local valid, errors = validate_entity({ request_host = "mockbin.com", upstream_url = "http://mockbin.com" }, api_schema) assert.falsy(errors) assert.True(valid) end) it("should complain if missing request_host and request_path", function() local valid, errors = validate_entity({ name = "mockbin" }, api_schema) assert.False(valid) assert.equal("At least a 'request_host' or a 'request_path' must be specified", errors.request_path) assert.equal("At least a 'request_host' or a 'request_path' must be specified", errors.request_host) local valid, errors = validate_entity({ name = "mockbin", request_path = true }, api_schema) assert.False(valid) assert.equal("request_path is not a string", errors.request_path) assert.equal("At least a 'request_host' or a 'request_path' must be specified", errors.request_host) end) it("should set the name from request_host if not set", function() local t = {request_host = "mockbin.com", upstream_url = "http://mockbin.com"} local valid, errors = validate_entity(t, api_schema) assert.falsy(errors) assert.True(valid) assert.equal("mockbin.com", t.name) end) it("should set the name from request_path if not set", function() local t = {request_path = "/mockbin", upstream_url = "http://mockbin.com"} local valid, errors = validate_entity(t, api_schema) assert.falsy(errors) assert.True(valid) assert.equal("mockbin", t.name) end) it("should normalize a name for URI if coming from request_host or request_path", function() local t = {upstream_url = "http://mockbin.com", request_host = "mockbin.com"} local valid, errors = validate_entity(t, api_schema) assert.True(valid) assert.falsy(errors) assert.equal("mockbin.com", t.name) t = {upstream_url = "http://mockbin.com", request_path = "/mockbin/status"} valid, errors = validate_entity(t, api_schema) assert.True(valid) assert.falsy(errors) assert.equal("mockbin-status", t.name) end) end) -- -- Consumer -- describe("Consumers", function() it("should require a `custom_id` or `username`", function() local valid, errors = validate_entity({}, consumer_schema) assert.False(valid) assert.equal("At least a 'custom_id' or a 'username' must be specified", errors.username) assert.equal("At least a 'custom_id' or a 'username' must be specified", errors.custom_id) valid, errors = validate_entity({ username = "" }, consumer_schema) assert.False(valid) assert.equal("At least a 'custom_id' or a 'username' must be specified", errors.username) assert.equal("At least a 'custom_id' or a 'username' must be specified", errors.custom_id) valid, errors = validate_entity({ username = true }, consumer_schema) assert.False(valid) assert.equal("username is not a string", errors.username) assert.equal("At least a 'custom_id' or a 'username' must be specified", errors.custom_id) end) end) -- -- Plugins -- describe("Plugins Configurations", function() local dao_stub = { find_all = function() return {} end } it("should not validate if the plugin doesn't exist (not installed)", function() local valid, errors = validate_entity({name = "world domination"}, plugins_schema) assert.False(valid) assert.equal("Plugin \"world domination\" not found", errors.config) end) it("should validate a plugin configuration's `config` field", function() -- Success local plugin = {name = "key-auth", api_id = "stub", config = {key_names = {"x-kong-key"}}} local valid = validate_entity(plugin, plugins_schema, {dao = dao_stub}) assert.True(valid) -- Failure plugin = {name = "rate-limiting", api_id = "stub", config = { second = "hello" }} local valid, errors = validate_entity(plugin, plugins_schema, {dao = dao_stub}) assert.False(valid) assert.equal("second is not a number", errors["config.second"]) end) it("should have an empty config if none is specified and if the config schema does not have default", function() -- Insert key-auth, whose config has some default values that should be set local plugin = {name = "key-auth", api_id = "stub"} local valid = validate_entity(plugin, plugins_schema, {dao = dao_stub}) assert.same({key_names = {"apikey"}, hide_credentials = false}, plugin.config) assert.True(valid) end) it("should be valid if no value is specified for a subfield and if the config schema has default as empty array", function() -- Insert response-transformer, whose default config has no default values, and should be empty local plugin2 = {name = "response-transformer", api_id = "stub"} local valid = validate_entity(plugin2, plugins_schema, {dao = dao_stub}) assert.same({ remove = { headers = {}, json = {} }, replace = { headers = {}, json = {} }, add = { headers = {}, json = {} }, append = { headers = {}, json = {} } }, plugin2.config) assert.True(valid) end) describe("self_check", function() it("should refuse `consumer_id` if specified in the config schema", function() local stub_config_schema = { no_consumer = true, fields = { string = {type = "string", required = true} } } plugins_schema.fields.config.schema = function() return stub_config_schema end local valid, _, err = validate_entity({name = "stub", api_id = "0000", consumer_id = "0000", config = {string = "foo"}}, plugins_schema) assert.False(valid) assert.equal("No consumer can be configured for that plugin", err.message) valid, err = validate_entity({name = "stub", api_id = "0000", config = {string = "foo"}}, plugins_schema, {dao = dao_stub}) assert.True(valid) assert.falsy(err) end) end) end) describe("update", function() it("should only validate updated fields", function() local t = {request_host = "", upstream_url = "http://mockbin.com"} local valid, errors = validate_entity(t, api_schema, { update = true }) assert.False(valid) assert.same({ request_host = "At least a 'request_host' or a 'request_path' must be specified" }, errors) end) end) end)
apache-2.0
Neopallium/lua-pb
pb/proto/grammar.lua
1
5648
-- Copyright (c) 2010-2011 by Robert G. Jakabosky <bobby@neoawareness.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local upper = string.upper local sfind = string.find local mod_path = string.match(...,".*%.") or '' local lp = require"lpeg" local util = require(mod_path .. 'util') local scanner = require(mod_path .. 'scanner') local error = scanner.error local P=lp.P local S=lp.S local V=lp.V local R=lp.R local B=lp.B local C=lp.C local Cf=lp.Cf local Cc=lp.Cc module(...) -- Copyright (c) 2007 Humberto Saraiva Nazareno dos Anjos. -- function 'rfind' copied from "leg.parser" in "Leg - LPeg-powered Lua 5.1 grammar" -- Searches for the last substring in s which matches pattern local function rfind(s, pattern, init, finish) init = init or #s finish = finish or 1 for i = init, finish, -1 do local lfind, rfind = sfind(s, pattern, i) if lfind and rfind then return lfind, rfind end end return nil end local function eV(val) return (V(val) + error("expected '" .. val .. "'")) end local function eP(str) return (P(str) + error("expected '" .. str .. "'")) end ------------------------------------------------------------------------------- ------------------------- Protocol Buffers grammer rules ------------------------------------------------------------------------------- local S=V'IGNORED' local listOf = util.listOf local E=S* eV';' rules = { -- initial rule [1] = 'Proto'; IGNORED = scanner.IGNORED, -- seen as S below EPSILON = P(true), EOF = scanner.EOF, BOF = scanner.BOF, ID = scanner.IDENTIFIER, IntLit = scanner.INTEGER, SIntLit = scanner.SINTEGER, NumLit = scanner.NUMERIC, SNumLit = scanner.SNUMERIC, StrLit = scanner.STRING, -- identifiers Ident = scanner.IDENTIFIER, Name = V'Ident' * ( V'.' * V'Ident')^0, GroupName = R'AZ' * (V'Ident')^0, UserType = (V'.')^-1 * V'Name', -- Top-level Proto = (S* (V'Message' + V'Extend' + V'Enum' + V'Syntax' + V'Import' + V'Package' + V'Option' + V'Service' + V';'))^0 *S, Syntax = V'SYNTAX' *S* eV'=' *S* eV'StrLit' *E, Import = V'IMPORT' *S* eV'StrLit' *E, Package = V'PACKAGE' *S* eV'Name' *E, Option = V'OPTION' *S* V'OptionBody' *E, OptionBody = eV'Name' *S* eV'=' *S* eV'Constant', Extend = V'EXTEND' *S* eV'UserType' *S* eV'{' * V'ExtendBody' *S* eV'}', ExtendBody = (S* (V'Group' + V'Field' + V';'))^0, Enum = V'ENUM' *S* V'ID' *S* eV'{' * (S* (V'Option' + V'EnumField' + V';'))^0 *S* eV'}', EnumField = V'ID' *S* eV'=' *S* eV'SIntLit' *E, Service = V'SERVICE' *S* eV'ID' *S* eV'{' * (S* (V'Option' + V'rpc' + V';'))^0 *S* eV'}', rpc = V'RPC' *S* eV'ID' *S* eV'(' *S* V'UserType' *S* V')' *S* eV'RETURNS' *S* eV'(' *S* eV'UserType' *S* eV')' *E, Group = V'FieldRule' *S* V'GROUP' *S* eV'GroupName' *S* eV'=' *S* eV'IntLit' *S* eV'{' * V'MessageBody' *S* eV'}', Message = V'MESSAGE' *S* eV'ID' *S* eV'{' * V'MessageBody' *S* eV'}', MessageBody = (S* (V'Group' + V'Field' + V'Enum' + V'Message' + V'Extend' + V'Extensions' + V'Option' + V';'))^0, Field = V'FieldRule' *S* eV'Type' *S* eV'ID' *S* eV'=' *S* eV'IntLit' *S* ( V'[' *S* V'FieldOptions' *S* eV']')^-1 *E, FieldOptions = listOf(V'OptionBody', S* V',' *S), FieldRule = (V'REQUIRED' + V'OPTIONAL' + V'REPEATED'), Extensions = V'EXTENSIONS' *S* V'ExtensionList' *E, ExtensionList = listOf(V'Extension', S* V',' *S), Extension = eV'IntLit' *S* (V'TO' *S* (V'IntLit' + V'MAX' + error("expected integer or 'max'")) )^-1, Type = (V'DOUBLE' + V'FLOAT' + V'INT32' + V'INT64' + V'UINT32' + V'UINT64' + V'SINT32' + V'SINT64' + V'FIXED32' + V'FIXED64' + V'SFIXED32' + V'SFIXED64' + V'BOOL' + V'STRING' + V'BYTES' + V'UserType'), BoolLit = (V'TRUE' + V'FALSE'), Constant = (V'BoolLit' + V'ID' + V'SNumLit' + V'StrLit'), } -- add keywords and symbols to grammar util.complete(rules, scanner.keywords) util.complete(rules, scanner.symbols) -- Copyright (c) 2007 Humberto Saraiva Nazareno dos Anjos. -- function 'check' copied from "leg.parser" in "Leg - LPeg-powered Lua 5.1 grammar" function check(input) local builder = P(rules) local result = builder:match(input) if result ~= #input + 1 then -- failure, build the error message local init, _ = rfind(input, '\n*', result - 1) local _, finish = sfind(input, '\n*', result + 1) init = init or 0 finish = finish or #input local line = scanner.lines(input:sub(1, result)) local vicinity = util.show_text(input:sub(init + 1, finish)) return false, 'Syntax error at line '..line..', near "'..vicinity..'"' end return true end function apply(extraRules, captures) return util.apply(rules, extraRules, captures) end
mit
Mortazamakasaadi/conky
AConky/AConky/.lua.lua
1
6347
--[[ Ring Meters by londonali1010 (2009) This script draws percentage meters as rings. It is fully customisable; all options are described in the script. IMPORTANT: if you are using the 'cpu' function, it will cause a segmentation fault if it tries to draw a ring straight away. The if statement on line 145 uses a delay to make sure that this doesn't happen. It calculates the length of the delay by the number of updates since Conky started. Generally, a value of 5s is long enough, so if you update Conky every 1s, use update_num > 5 in that if statement (the default). If you only update Conky every 2s, you should change it to update_num > 3; conversely if you update Conky every 0.5s, you should use update_num > 10. ALSO, if you change your Conky, is it best to use "killall conky; conky" to update it, otherwise the update_num will not be reset and you will get an error. To call this script in Conky, use the following (assuming that you save this script to ~/scripts/rings.lua): lua_load ~/scripts/rings-v1.2.1.lua lua_draw_hook_pre ring_stats Changelog: + v1.2.1 -- Fixed minor bug that caused script to crash if conky_parse() returns a nil value (20.10.2009) + v1.2 -- Added option for the ending angle of the rings (07.10.2009) + v1.1 -- Added options for the starting angle of the rings, and added the "max" variable, to allow for variables that output a numerical value rather than a percentage (29.09.2009) + v1.0 -- Original release (28.09.2009) ]] settings_table = { { name='cpu', arg='cpu0', max=100, bg_colour=0xffffff, bg_alpha=0.0, fg_colour=0x00C9FF, fg_alpha=1.0, x=35, y=35, radius=29, thickness=7, start_angle=0, end_angle=360 }, { name='memperc', arg='', max=100, bg_colour=0xffffff, bg_alpha=0.0, fg_colour=0xf0f8ff, fg_alpha=1.0, x=35, y=135, radius=29, thickness=7, start_angle=0, end_angle=360 }, { name='swapperc', arg='', max=100, bg_colour=0xffffff, bg_alpha=0.0, fg_colour=0x47B13E, fg_alpha=1.0, x=35, y=235, radius=29, thickness=7, start_angle=0, end_angle=360 }, { name='upspeedf', arg='wlp8s0', max=50, bg_colour=0xffffff, bg_alpha=0.0, fg_colour=0x00FF00, fg_alpha=1.0, x=35, y=335, radius=29, thickness=7, start_angle=0, end_angle=360 }, { name='downspeedf', arg='wlp8s0', max=100, bg_colour=0xffffff, bg_alpha=0.0, fg_colour=0x1ba1e2, fg_alpha=1.0, x=35, y=435, radius=29, thickness=7, start_angle=0, end_angle=360 }, { name='fs_used_perc', arg='/', max=100, bg_colour=0xffffff, bg_alpha=0.0, fg_colour=0xFF2C34, fg_alpha=1.0, x=35, y=535, radius=29, thickness=7, start_angle=0, end_angle=360 }, { name='fs_used_perc', arg='/home', max=100, bg_colour=0xffffff, bg_alpha=0.0, fg_colour=0xEAE710, fg_alpha=1.0, x=35, y=635, radius=29, thickness=7, start_angle=0, end_angle=360 }, { name='battery_percent', arg='/BAT1', max=100, bg_colour=0xffffff, bg_alpha=0.0, fg_colour=0x00C9FF, fg_alpha=1.0, x=279, y=130, radius=115, thickness=5, start_angle=0, end_angle=360 }, } settings_t = { } require 'cairo' function rgb_to_r_g_b(colour,alpha) return ((colour / 0x10000) % 0x100) / 255., ((colour / 0x100) % 0x100) / 255., (colour % 0x100) / 255., alpha end function draw_ring(cr,t,pt) local w,h=conky_window.width,conky_window.height local xc,yc,ring_r,ring_w,sa,ea=pt['x'],pt['y'],pt['radius'],pt['thickness'],pt['start_angle'],pt['end_angle'] local bgc, bga, fgc, fga=pt['bg_colour'], pt['bg_alpha'], pt['fg_colour'], pt['fg_alpha'] local angle_0=sa*(2*math.pi/360)-math.pi/2 local angle_f=ea*(2*math.pi/360)-math.pi/2 local t_arc=t*(angle_f-angle_0) -- Draw background ring cairo_arc(cr,xc,yc,ring_r,angle_0,angle_f) cairo_set_source_rgba(cr,rgb_to_r_g_b(bgc,bga)) cairo_set_line_width(cr,ring_w) cairo_stroke(cr) -- Draw indicator ring cairo_arc(cr,xc,yc,ring_r,angle_0,angle_0+t_arc) cairo_set_source_rgba(cr,rgb_to_r_g_b(fgc,fga)) cairo_stroke(cr) end function draw_ring_cc(cr,t,pt) local w,h=conky_window.width,conky_window.height local xc,yc,ring_r,ring_w,sa,ea=pt['x'],pt['y'],pt['radius'],pt['thickness'],pt['start_angle'],pt['end_angle'] local bgc, bga, fgc, fga=pt['bg_colour'], pt['bg_alpha'], pt['fg_colour'], pt['fg_alpha'] local angle_0=sa*(2*math.pi/360)-math.pi/2 local angle_f=ea*(2*math.pi/360)-math.pi/2 local t_arc=t*(angle_f-angle_0) -- Draw background ring cairo_arc_negative(cr,xc,yc,ring_r,angle_0,angle_f) cairo_set_source_rgba(cr,rgb_to_r_g_b(bgc,bga)) cairo_set_line_width(cr,ring_w) cairo_stroke(cr) -- Draw indicator ring cairo_arc_negative(cr,xc,yc,ring_r,angle_0,angle_0+t_arc) cairo_set_source_rgba(cr,rgb_to_r_g_b(fgc,fga)) cairo_stroke(cr) end function conky_ring_stats() local function setup_rings(cr,pt) local str='' local value=0 str=string.format('${%s %s}',pt['name'],pt['arg']) str=conky_parse(str) value=tonumber(str) if value == nil then value = 0 end pct=value/pt['max'] draw_ring(cr,pct,pt) end local function setup_rings_cc(cr,pt) local str='' local value=0 str=string.format('${%s %s}',pt['name'],pt['arg']) str=conky_parse(str) value=tonumber(str) if value == nil then value = 0 end pct=value/pt['max'] draw_ring_cc(cr,pct,pt) end if conky_window==nil then return end local cs=cairo_xlib_surface_create(conky_window.display,conky_window.drawable,conky_window.visual, conky_window.width,conky_window.height) local cr=cairo_create(cs) local updates=conky_parse('${updates}') update_num=tonumber(updates) if update_num>5 then for i in pairs(settings_table) do setup_rings(cr,settings_table[i]) end for i in pairs(settings_t) do setup_rings_cc(cr,settings_t[i]) end end end require 'imlib2' function init_drawing_surface() imlib_set_cache_size(4096 * 1024) imlib_context_set_dither(1) end function draw_image() init_drawing_surface() --you'll need to change the path here (keep it absolute!) image = imlib_load_image("/home/mak/.conky/AConky/conky.png") if image == nil then return end imlib_context_set_image(image) imlib_render_image_on_drawable(0,0) imlib_free_image() end function conky_start() if conky_window == nil then return end draw_image() end
gpl-2.0
rathersleepy/gamecode4
Assets/Scripts/TeapotStates.lua
44
13650
--======================================================================== -- ActorManager.lua : Defines all the states for an AI controlled teapot -- -- Part of the GameCode4 Application -- -- GameCode4 is the sample application that encapsulates much of the source code -- discussed in "Game Coding Complete - 4th Edition" by Mike McShaffry and David -- "Rez" Graham, published by Charles River Media. -- ISBN-10: 1133776574 | ISBN-13: 978-1133776574 -- -- If this source code has found it's way to you, and you think it has helped you -- in any way, do the authors a favor and buy a new copy of the book - there are -- detailed explanations in it that compliment this code well. Buy a copy at Amazon.com -- by clicking here: -- http://www.amazon.com/gp/product/1133776574/ref=olp_product_details?ie=UTF8&me=&seller= -- -- There's a companion web site at http://www.mcshaffry.com/GameCode/ -- -- The source code is managed and maintained through Google Code: -- http://code.google.com/p/gamecode4/ -- -- (c) Copyright 2012 Michael L. McShaffry and David Graham -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser GPL v3 -- as published by the Free Software Foundation. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See -- http://www.gnu.org/licenses/lgpl-3.0.txt for more details. -- -- You should have received a copy of the GNU Lesser GPL v3 -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -- --======================================================================== ----------------------------------------------------------------------------------------------------------------------- -- TeapotState - Chapter 18, page 619 -- This is the base class for all Teapot states ----------------------------------------------------------------------------------------------------------------------- TeapotState = class(nil, { _teapot = nil, _teapotMoveSpeed = 5.25, }); function TeapotState:Init() if (self._teapot == nil) then print("Invalid teapot in TeapotState"); return false; end return true; end function TeapotState:Update(deltaMs) error("Calling unimplemented TeapotState.Update() fucntion"); end ----------------------------------------------------------------------------------------------------------------------- -- PatrolState ----------------------------------------------------------------------------------------------------------------------- PatrolState = class(TeapotState, { name = "PatrolState", _patrolPoints = { Vec3:Create({ x = 20, y = 1, z = 20 }), Vec3:Create({ x = -20, y = 1, z = 20 }), }; _patrolPointIndex = 1; _patrolSpeedMultiplier = 0.75; _hasStartedRotation = false; _hasFinishedRotating = false; _angularAcceleration = 7; _waitTimer = 0; }); function PatrolState:Update(deltaMs) if (self._waitTimer > 0) then self._waitTimer = self._waitTimer - deltaMs; return; end local teapotPos = Vec3:Create(self._teapot:GetPos()); local diff = self._patrolPoints[self._patrolPointIndex] - teapotPos; if (not self._hasFinishedRotating) then -- get necessary rotation local targetOrientation = GccMath.GetYRotationFromVector(diff); -- this is the orientation we need to be at to face the player local currOrientation = self._teapot:GetYOrientationRadians(); -- if we're not facing the right direction, start rotating if we haven't already if (math.abs(targetOrientation - currOrientation) > 0.01) then if (not self._hasStartedRotation) then self._teapot:RotateY(targetOrientation); self._targetOrientation = targetOrientation; self._hasStartedRotation = true; end else self._hasFinishedRotating = true; end else -- done rotating -- grab the distance to the patrol point and see if we're already there local distanceToPatrolPoint = diff:Length(); if (distanceToPatrolPoint < 0.1) then self:GetNextPatrolPoint(); return; end -- not there yet so calculate the velocity vector, which provides direction and speed local velocityVector = Vec3:Create(diff); -- clone the diff vector velocityVector:Normalize(); local speed = (self._teapotMoveSpeed * self._patrolSpeedMultiplier) * (deltaMs / 1000); velocityVector = velocityVector * speed; -- if we're about to overshoot our desitination, adjust the velocity so that we land on it if (velocityVector:Length() > distanceToPatrolPoint) then velocityVector = diff; end -- send the event teapotPos = teapotPos + velocityVector; self._teapot:SetPosition(teapotPos.x, teapotPos.y, teapotPos.z); end end function PatrolState:GetNextPatrolPoint() -- update the patrol point index and wrap if necessary self._patrolPointIndex = self._patrolPointIndex + 1; if (self._patrolPointIndex > #self._patrolPoints) then self._patrolPointIndex = 1; end -- reset rotation flags self._hasStartedRotation = false; self._hasFinishedRotating = false; -- wait here for a bit self._waitTimer = 1000; end ----------------------------------------------------------------------------------------------------------------------- -- AttackState ----------------------------------------------------------------------------------------------------------------------- AttackState = class(TeapotState, { name = "AttackState", _hasStartedRotating = false, _targetOrientation = nil, _weaponsRange = {15, 18}, _fireInterval = 1500, _fireTimer = 0, }); function AttackState:Init() self.base.Init(self); -- initialize target orientation to something reasonable self._targetOrientation = self._teapot:GetYOrientationRadians(); end function AttackState:Update(deltaMs) -- update the fire timer self._fireTimer = self._fireTimer + deltaMs; -- get necessary rotation local playerPos = Vec3:Create(g_actorMgr:GetPlayer():GetPos()); local teapotPos = Vec3:Create(self._teapot:GetPos()); local diff = playerPos - teapotPos; local targetOrientation = GccMath.GetYRotationFromVector(diff); -- this is the orientation we need to be at to face the player local currOrientation = self._teapot:GetYOrientationRadians(); -- see if we need to recalculate the rotation if (math.abs(self._targetOrientation - targetOrientation) > 0.01) then self._hasStartedRotation = false; end -- if we're not facing the right direction, start rotating if we haven't already if (math.abs(targetOrientation - currOrientation) > 0.01) then if (not self._hasStartedRotation) then self._teapot:RotateY(targetOrientation); self._targetOrientation = targetOrientation; self._hasStartedRotation = true; end -- if we're already facing the right direction, pretend we rotated there elseif (not self._hasStartedRotation) then self._hasStartedRotation = true; -- if we get here, we're done rotating else self._hasStartedRotation = false; local distanceToPlayer = diff:Length(); diff:Normalize(); -- check to see if we're within firing range if (distanceToPlayer >= self._weaponsRange[1] and distanceToPlayer <= self._weaponsRange[2]) then self:_AttemptToFireWeapon(); -- not in range, so towards (or away from) then player else -- teapot is too close, back up if (distanceToPlayer < self._weaponsRange[1]) then diff = diff * -1; end local speed = self._teapotMoveSpeed * (deltaMs / 1000); diff = diff * speed; -- QueueEvent(EventType.EvtData_AiTranslate, {id = self._teapot:GetActorId(), distanceAndDirection = diff}); teapotPos = teapotPos + diff; self._teapot:SetPosition(teapotPos.x, teapotPos.y, teapotPos.z); end end end function AttackState:_AttemptToFireWeapon() if (self._fireTimer >= self._fireInterval) then QueueEvent(EventType.EvtData_Fire_Weapon, {id = self._teapot:GetActorId()}); self._fireTimer = 0; end end ----------------------------------------------------------------------------------------------------------------------- -- RunAwayState ----------------------------------------------------------------------------------------------------------------------- RunAwayState = class(TeapotState, { name = "RunAwayState", _runPoints = { Vec3:Create({ x = 25, y = 1, z = 25 }), Vec3:Create({ x = -25, y = 1, z = 25 }), Vec3:Create({ x = 25, y = 1, z = -25 }), Vec3:Create({ x = -25, y = 1, z = -25 }), }, _runPointIndex = 0; _hasRotated = false; _checkForBetterRunPointTimer = 0; _checkForBetterRunPointFrequency = 2000; -- check for a better run point every 2 seconds }); function RunAwayState:Init() self.base.Init(self); self:_FindRunPoint(); end function RunAwayState:Update(deltaMs) -- update the timer and see if it's time to check for a better run point self._checkForBetterRunPointTimer = self._checkForBetterRunPointTimer + deltaMs; if (self._checkForBetterRunPointTimer >= self._checkForBetterRunPointFrequency) then self:_FindRunPoint(); self._checkForBetterRunPointTimer = 0; end -- grab the teapot position and the delta to the run point local teapotPos = Vec3:Create(self._teapot:GetPos()); local diff = self._runPoints[self._runPointIndex] - teapotPos; if (not self._hasRotated) then local teapotPos = Vec3:Create(self._teapot:GetPos()); local diff = self._runPoints[self._runPointIndex] - teapotPos; local targetOrientation = GccMath.GetYRotationFromVector(diff); -- this is the orientation we need to be at to face the player local currOrientation = self._teapot:GetYOrientationRadians(); -- already facing the right way if (math.abs(currOrientation - targetOrientation) < 0.01) then self._hasRotated = true; -- start rotating else self._teapot:RotateY(targetOrientation); self._hasRotated = true; end return; -- teapot has already started rotation so start moving else -- grab the distance to the run point and see if we're already there local distanceToRunPoint = diff:Length(); if (distanceToRunPoint < 0.1) then return; end -- not there yet so calculate the velocity vector, which provides direction and speed local velocityVector = Vec3:Create(diff); -- clone the diff vector velocityVector:Normalize(); local speed = self._teapotMoveSpeed * (deltaMs / 1000); velocityVector = velocityVector * speed; -- if we're about to overshoot our desitination, adjust the velocity so that we land on it if (velocityVector:Length() > distanceToRunPoint) then velocityVector = diff; end -- send the event -- QueueEvent(EventType.EvtData_AiTranslate, {id = self._teapot:GetActorId(), distanceAndDirection = velocityVector}); teapotPos = teapotPos + velocityVector; self._teapot:SetPosition(teapotPos.x, teapotPos.y, teapotPos.z); end end function RunAwayState:_FindRunPoint() local oldRunPoint = self._runPointIndex; local playerPos = Vec3:Create(g_actorMgr:GetPlayer():GetPos()); -- find the furthest run point from the player local bestDistance2 = nil; for index, value in ipairs(self._runPoints) do local diff = value - playerPos; local distance2 = diff:Length2(); if (bestDistance2 == nil or distance2 > bestDistance2) then self._runPointIndex = index; bestDistance2 = distance2; end end -- if we found a better run point, we need to rotate to the new point if (self._runPointIndex ~= oldRunPoint) then self._hasRotated = false; end return (self._runPointIndex ~= oldRunPoint); end ----------------------------------------------------------------------------------------------------------------------- -- WatchPlayerState (for debugging) ----------------------------------------------------------------------------------------------------------------------- WatchPlayerState = class(TeapotState, { name = "WatchPlayerState" }); function WatchPlayerState:Init() self.base.Init(self); end function WatchPlayerState:Update(deltaMs) -- grab the teapot position and the delta to the run point local teapotPos = Vec3:Create(self._teapot:GetPos()); local playerPos = Vec3:Create(g_actorMgr:GetPlayer():GetPos()); local diff = playerPos - teapotPos; local targetOrientation = GccMath.GetYRotationFromVector(diff); -- this is the orientation we need to be at to face the player self._teapot:RotateY(targetOrientation); end ----------------------------------------------------------------------------------------------------------------------- -- RotateState (for debugging) ----------------------------------------------------------------------------------------------------------------------- RotateState = class(TeapotState, { name = "RotateState" }); function RotateState:Init() self.base.Init(self); self._teapot:RotateY(0); self._nextOrientation = 0.5; self._delayTime = 5000; self._timer = self._delayTime; end function RotateState:Update(deltaMs) -- update timer if (self._timer > 0) then self._timer = self._timer - deltaMs; return; end self._timer = self._delayTime; self._teapot:RotateY(self._nextOrientation); self._nextOrientation = self._nextOrientation + 0.5; GccMath.WrapPi(self._nextOrientation); end
lgpl-3.0
syj2010syj/All-star-Battle
map/lua/game.lua
1
6885
game = {} local game = game game.debug = jass.s__sys_Debug game.heroes = {} game.trg_hero_spell = jass.CreateTrigger() game.trg_hero_skill = jass.CreateTrigger() function game.initHero(u) table.insert(game.heroes, u) if jass.GetOwningPlayer(u) == jass.GetLocalPlayer() then game.selfHero = u end local p = player.j_player(jass.GetOwningPlayer(u)) p.hero = u event('注册英雄', {hero = u, player = p}) jass.TriggerRegisterUnitEvent(game.trg_hero_spell, u, jass.EVENT_UNIT_SPELL_EFFECT) jass.TriggerRegisterUnitEvent(game.trg_hero_skill, u, jass.EVENT_UNIT_HERO_SKILL) end jass.TriggerAddCondition(game.trg_hero_spell, jass.Condition( function() event('英雄发动技能', {from = jass.GetTriggerUnit(), to = jass.GetSpellTargetUnit(), skill = jass.GetSpellAbilityId()}) end )) jass.TriggerAddCondition(game.trg_hero_skill, jass.Condition( function() event('英雄学习技能', {from = jass.GetTriggerUnit(), skill = jass.GetLearnedSkill()}) end )) game.trg_unit_spell = jass.CreateTrigger() for i = 1, 12 do jass.TriggerRegisterPlayerUnitEvent(game.trg_unit_spell, player[i].handle, jass.EVENT_PLAYER_UNIT_SPELL_EFFECT, nil) end jass.TriggerAddCondition(game.trg_unit_spell, jass.Condition( function() event('单位发动技能', {from = jass.GetTriggerUnit(), to = jass.GetSpellTargetUnit(), skill = jass.GetSpellAbilityId(), player = player.j_player(jass.GetTriggerPlayer())}) end )) game.trg_unit_death = jass.CreateTrigger() for i = 1, 12 do jass.TriggerRegisterPlayerUnitEvent(game.trg_unit_death, player[i].handle, jass.EVENT_PLAYER_UNIT_DEATH, nil) end jass.TriggerAddCondition(game.trg_unit_death, jass.Condition( function() event('单位死亡', {from = jass.GetKillingUnit(), to = jass.GetSpellTargetUnit(), player = player.j_player(jass.GetTriggerPlayer())}) end )) function game.self() return game.selfHero end function hook.UnitWakeUp(u, f) game.initHero(u) end function hook.SetUnitRescueRange(u, r, f) if jass.GetUnitTypeId(u) == 0 then if r + 0 == 23333 then cmd.start() end return end if r < 0 then game[math.floor(0 - r)](u) else return f(u, r) end end --一方通行-重力移动冷却2秒 game[1] = function(u) local ab = japi.EXGetUnitAbility(u, |A0II|) local lv = jass.GetUnitAbilityLevel(u, |A0II|) japi.EXSetAbilityDataReal(ab, lv, 105, 2) japi.EXSetAbilityState(ab, 1, 2) japi.EXSetAbilityDataReal(ab, lv, 105, 0) end --一方通行-重力移动冷却1秒 game[2] = function(u) local ab = japi.EXGetUnitAbility(u, |A0II|) local lv = jass.GetUnitAbilityLevel(u, |A0II|) japi.EXSetAbilityDataReal(ab, lv, 105, 1) japi.EXSetAbilityState(ab, 1, 1) japi.EXSetAbilityDataReal(ab, lv, 105, 0) end --三笠阿克曼-技能耗蓝增加50%(废弃) game.table_3 = {} game.table_4 = { [|A0PX|] = true, [|A0PZ|] = true, [|A0Q0|] = true, [|A0Q1|] = true, } game[3] = function(u) local data = {} local t = timer.loop(0.1, true, function() for i = 0, 99 do local ab = japi.EXGetUnitAbilityByIndex(u, i) if ab == 0 then return end local id = japi.EXGetAbilityId(ab) local lv = jass.GetUnitAbilityLevel(u, id) local mp = japi.EXGetAbilityDataInteger(ab, lv, 104) if mp > 0 and game.table_4[id] then if data[id] then mp = mp - (data[id][lv] or 0) end data[id] = {} data[id][lv] = math.floor(mp * 0.5) mp = mp + data[id][lv] japi.EXSetAbilityDataInteger(ab, lv, 104, mp) end end end ) game.table_3[u] = {t, data} end game[4] = function(u) if not game.table_3[u] then return end local t = game.table_3[u][1] local data = game.table_3[u][2] t:destroy() for i = 0, 99 do local ab = japi.EXGetUnitAbilityByIndex(u, i) if ab == 0 then return end local id = japi.EXGetAbilityId(ab) local lv = jass.GetUnitAbilityLevel(u, id) local mp = japi.EXGetAbilityDataInteger(ab, lv, 104) if mp > 0 and game.table_4[id] then if data[id] then mp = mp - (data[id][lv] or 0) end japi.EXSetAbilityDataInteger(ab, lv, 104, mp) end end end --连杀后死亡 game[5] = function(u) local name = jass.GetPlayerName(jass.Player(12)) local p = jass.GetOwningPlayer(u) jass.SetPlayerName(jass.Player(12), '阎魔爱') if p == jass.GetLocalPlayer() then japi.EXDisplayChat(jass.Player(12), 3, '|cff505050充满罪恶的灵魂、想死一遍看看吗?|r') end jass.SetPlayerName(jass.Player(12), name) end --克劳德暴击触发 game.table_6 = setmetatable({}, {__index = function() return 0 end}) game.table_7 = setmetatable({}, {__index = function() return 0 end}) game[6] = function(u) game.table_6[u] = game.table_6[u] + 1 end game[7] = function(u) game.table_7[u] = game.table_7[u] + 1 if game.table_7[u] % 10 == 0 then jass.SetPlayerName(jass.Player(12), '|cffff88cc' .. cmd.getMaidName(true) .. '|r') if jass.GetOwningPlayer(u) == jass.GetLocalPlayer() then japi.EXDisplayChat(jass.Player(12), 3, ('|cffff88cc主人,从您学习了[一刀两断]后一共攻击了%d次,其中暴击了%d次|r'):format(game.table_6[u], game.table_7[u])) local s = game.table_7[u] / game.table_6[u] * 100 local w if s > 33 then w = '赶紧去买彩票吧!' elseif s > 25 then w = 'RP真不错啊!' elseif s < 15 then w = '建议洗把脸再回来玩?' else w = '加油加油~' end japi.EXDisplayChat(jass.Player(12), 3, ('|cffff88cc综合暴击率为%.2f%%,%s|r'):format(s, w)) end end end
apache-2.0
lxl1140989/dmsdk
feeds/luci/applications/luci-samba/luasrc/model/cbi/samba.lua
79
2602
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("samba", translate("Network Shares")) s = m:section(TypedSection, "samba", "Samba") s.anonymous = true s:tab("general", translate("General Settings")) s:tab("template", translate("Edit Template")) s:taboption("general", Value, "name", translate("Hostname")) s:taboption("general", Value, "description", translate("Description")) s:taboption("general", Value, "workgroup", translate("Workgroup")) s:taboption("general", Value, "homes", translate("Share home-directories"), translate("Allow system users to reach their home directories via " .. "network shares")) tmpl = s:taboption("template", Value, "_tmpl", translate("Edit the template that is used for generating the samba configuration."), translate("This is the content of the file '/etc/samba/smb.conf.template' from which your samba configuration will be generated. " .. "Values enclosed by pipe symbols ('|') should not be changed. They get their values from the 'General Settings' tab.")) tmpl.template = "cbi/tvalue" tmpl.rows = 20 function tmpl.cfgvalue(self, section) return nixio.fs.readfile("/etc/samba/smb.conf.template") end function tmpl.write(self, section, value) value = value:gsub("\r\n?", "\n") nixio.fs.writefile("//etc/samba/smb.conf.template", value) end s = m:section(TypedSection, "sambashare", translate("Shared Directories")) s.anonymous = true s.addremove = true s.template = "cbi/tblsection" s:option(Value, "name", translate("Name")) pth = s:option(Value, "path", translate("Path")) if nixio.fs.access("/etc/config/fstab") then pth.titleref = luci.dispatcher.build_url("admin", "system", "fstab") end s:option(Value, "users", translate("Allowed users")).rmempty = true ro = s:option(Flag, "read_only", translate("Read-only")) ro.rmempty = false ro.enabled = "yes" ro.disabled = "no" go = s:option(Flag, "guest_ok", translate("Allow guests")) go.rmempty = false go.enabled = "yes" go.disabled = "no" cm = s:option(Value, "create_mask", translate("Create mask"), translate("Mask for new files")) cm.rmempty = true cm.size = 4 dm = s:option(Value, "dir_mask", translate("Directory mask"), translate("Mask for new directories")) dm.rmempty = true dm.size = 4 return m
gpl-2.0
Sewerbird/blooming-suns
src_old/resource/SpriteInstance.lua
1
1560
--SpriteInstance SpriteInstance = {} SpriteInstance.new = function (init) local init = init or {} if init.sprite == nil then error("Sprite instance without sprite ref: " .. inspect(init)) end local self = { sprite_ref = init.sprite_ref or GlobalSpriteBank.sprites[init.sprite], curr_anim = init.curr_anim or "idle", curr_frame = init.curr_frame or 1, timer = init.timer or 0, position = init.position or nil } self.changeAnim = function (anim) if anim == self.curr_anim then return end self.curr_anim = anim self.curr_frame = 1 self.timer = 0 end self.update = function (dt) self.timer = self.timer + dt if self.timer > self.sprite_ref.frame_duration then self.timer = self.timer % self.sprite_ref.frame_duration self.curr_frame = self.curr_frame + 1 if self.curr_frame > table.getn(self.sprite_ref.animations[self.curr_anim]) then self.curr_frame = 1 end end end self.draw = function () love.graphics.draw( self.sprite_ref.spritesheet.img, self.sprite_ref.animations[self.curr_anim][self.curr_frame], self.position.x, self.position.y, 0, --rotation self.sprite_ref.scale_x, self.sprite_ref.scale_y ) end self.getCurrentDimension = function () local cutout = self.sprite_ref.anim_spec[self.curr_anim][self.curr_frame] local width = (cutout[3]) * self.sprite_ref.scale_x local height = (cutout[4]) * self.sprite_ref.scale_y return {w = width, h = height} end return self end
gpl-3.0
Mutos/SoC-Test-001
dat/factions/spawn/civilian.lua
11
1283
include("dat/factions/spawn/common.lua") -- @brief Spawns a single small ship. function spawn_patrol () local pilots = {} local civships = {{"Civilian Schroedinger", 8}, {"Civilian Llama", 8}, {"Civilian Gawain", 8}, {"Civilian Hyena", 13} } local select = rnd.rnd(1, #civships) scom.addPilot( pilots, civships[select][1], civships[select][2] ); return pilots end -- @brief Creation hook. function create ( max ) local weights = {} -- Create weights for spawn table weights[ spawn_patrol ] = 100 -- Create spawn table base on weights spawn_table = scom.createSpawnTable( weights ) -- Calculate spawn data spawn_data = scom.choose( spawn_table ) return scom.calcNextSpawn( 0, scom.presence(spawn_data), max ) end -- @brief Spawning hook function spawn ( presence, max ) local pilots -- Over limit if presence > max then return 5 end -- Actually spawn the pilots pilots = scom.spawn( spawn_data ) -- Calculate spawn data spawn_data = scom.choose( spawn_table ) return scom.calcNextSpawn( presence, scom.presence(spawn_data), max ), pilots end
gpl-3.0
Insurgencygame/LivingDead
TheLivingDeadv0.1.sdd/units/unused/corack.lua
1
3031
return { corack = { acceleration = 0.2039999961853, brakerate = 0.42500001192093, buildcostenergy = 5428, buildcostmetal = 319, builddistance = 136, builder = true, buildpic = "CORACK.DDS", buildtime = 9709, canmove = true, category = "KBOT MOBILE ALL NOTSUB NOWEAPON NOTSHIP NOTAIR NOTHOVER SURFACE", corpse = "DEAD", description = "Tech Level 2", energymake = 14, energystorage = 100, energyuse = 14, explodeas = "BIG_UNITEX", footprintx = 2, footprintz = 2, idleautoheal = 5, idletime = 1800, maxdamage = 900, maxslope = 20, maxvelocity = 1.1000000238419, maxwaterdepth = 25, metalmake = 0.14000000059605, metalstorage = 100, movementclass = "KBOT2", name = "Advanced Construction Kbot", objectname = "CORACK", radardistance = 50, seismicsignature = 0, selfdestructas = "BIG_UNIT", sightdistance = 318.5, smoothanim = true, terraformspeed = 900, turnrate = 935, upright = true, workertime = 180, buildoptions = { [10] = "corarad", [11] = "corshroud", [12] = "corfort", [13] = "corasp", [14] = "cortarg", [15] = "corsd", [16] = "corgate", [17] = "cortoast", [18] = "corvipe", [19] = "cordoom", [1] = "corfus", [20] = "corflak", [21] = "screamer", [22] = "cortron", [23] = "corfmd", [24] = "corsilo", [25] = "corint", [26] = "corbuzz", [27] = "corlab", [28] = "coralab", [2] = "corgant", [3] = "cmgeo", [4] = "corbhmth", [5] = "cormoho", [6] = "cormexp", [7] = "cormmkr", [8] = "coruwadves", [9] = "coruwadvms", }, featuredefs = { dead = { blocking = true, category = "corpses", collisionvolumeoffsets = "0.0 -1.11450195313e-05 -6.82949829102", collisionvolumescales = "22.0 23.11277771 24.3265991211", collisionvolumetype = "Box", damage = 540, description = "Advanced Construction Kbot Wreckage", energy = 0, featuredead = "HEAP", featurereclamate = "SMUDGE01", footprintx = 2, footprintz = 2, height = 20, hitdensity = 100, metal = 207, object = "CORACK_DEAD", reclaimable = true, seqnamereclamate = "TREE1RECLAMATE", world = "All Worlds", }, heap = { blocking = false, category = "heaps", damage = 270, description = "Advanced Construction Kbot Heap", energy = 0, featurereclamate = "SMUDGE01", footprintx = 2, footprintz = 2, height = 4, hitdensity = 100, metal = 83, object = "2X2B", reclaimable = true, seqnamereclamate = "TREE1RECLAMATE", world = "All Worlds", }, }, sounds = { build = "nanlath2", canceldestruct = "cancel2", capture = "capture2", repair = "repair2", underattack = "warning1", working = "reclaim1", cant = { [1] = "cantdo4", }, count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, ok = { [1] = "kbcormov", }, select = { [1] = "kbcorsel", }, }, }, }
gpl-2.0
reborndb/reborn
extern/redis-2.8.13/deps/lua/test/sort.lua
889
1494
-- two implementations of a sort function -- this is an example only. Lua has now a built-in function "sort" -- extracted from Programming Pearls, page 110 function qsort(x,l,u,f) if l<u then local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u x[l],x[m]=x[m],x[l] -- swap pivot to first position local t=x[l] -- pivot value m=l local i=l+1 while i<=u do -- invariant: x[l+1..m] < t <= x[m+1..i-1] if f(x[i],t) then m=m+1 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m] end i=i+1 end x[l],x[m]=x[m],x[l] -- swap pivot to a valid place -- x[l+1..m-1] < x[m] <= x[m+1..u] qsort(x,l,m-1,f) qsort(x,m+1,u,f) end end function selectionsort(x,n,f) local i=1 while i<=n do local m,j=i,i+1 while j<=n do if f(x[j],x[m]) then m=j end j=j+1 end x[i],x[m]=x[m],x[i] -- swap x[i] and x[m] i=i+1 end end function show(m,x) io.write(m,"\n\t") local i=1 while x[i] do io.write(x[i]) i=i+1 if x[i] then io.write(",") end end io.write("\n") end function testsorts(x) local n=1 while x[n] do n=n+1 end; n=n-1 -- count elements show("original",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort",x) selectionsort(x,n,function (x,y) return x>y end) show("after reverse selection sort",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort again",x) end -- array to be sorted x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"} testsorts(x)
mit