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
hanxi/cocos2d-x-v3.1
src/RankScene.lua
1
6446
local RankScene = {} local visibleSize = cc.Director:getInstance():getVisibleSize() local origin = cc.Director:getInstance():getVisibleOrigin() local function scrollViewDidScroll(view) print("scrollViewDidScroll") end local function scrollViewDidZoom(view) print("scrollViewDidZoom") end local function tableCellTouched(table,cell) print("cell touched at index: " .. cell:getIdx()) end local function cellSizeForTable(table,idx) return 20,20 end local TAG_LABEL_RANK = 0x101 local TAG_LABEL_NAME = 0x102 local TAG_LABEL_SCORE = 0x103 local TAG_LABEL_LEVEL = 0x104 local function tableCellAtIndex(table, idx) local rank = idx+1 local rankStr = string.format("%d",rank) local nameStr = "hanxi" local scoreStr = "110" local labelRank = nil local labelName = nil local labelScore = nil local cell = table:dequeueCell() if nil == cell then cell = cc.TableViewCell:new() --local sprite = cc.Sprite:create("logo.png") --sprite:setAnchorPoint(cc.p(0,0)) --sprite:setPosition(cc.p(0, 0)) --cell:addChild(sprite) labelRank = util.createLabel(rankStr,15) labelRank:setPosition(cc.p(visibleSize.width*0.2,0)) labelRank:setAnchorPoint(cc.p(0,0)) labelRank:setTag(TAG_LABEL_RANK) labelRank:setColor(cc.c3b(0,0,0)) cell:addChild(labelRank) labelName = util.createLabel(nameStr,15) labelName:setPosition(cc.p(visibleSize.width*0.35,0)) labelName:setAnchorPoint(cc.p(0,0)) labelName:setTag(TAG_LABEL_NAME) labelName:setColor(cc.c3b(0,0,0)) cell:addChild(labelName) labelScore = util.createLabel(scoreStr,15) labelScore:setPosition(cc.p(visibleSize.width*0.7,0)) labelScore:setAnchorPoint(cc.p(0,0)) labelScore:setTag(TAG_LABEL_SCORE) labelScore:setColor(cc.c3b(0,0,0)) cell:addChild(labelScore) else labelRank = cell:getChildByTag(TAG_LABEL_RANK) if nil ~= labelRank then labelRank:setString(rankStr) end labelName = cell:getChildByTag(TAG_LABEL_NAME) if nil ~= labelName then labelName:setString(nameStr) end labelScore = cell:getChildByTag(TAG_LABEL_SCORE) if nil ~= labelScore then labelScore:setString(scoreStr) end end return cell end local function numberOfCellsInTableView(table) return 25 end function RankScene.newScene() local scene = cc.Scene:create() local layer = cc.Layer:create() layer:setPosition(origin.x,origin.y) -- Title local titleLabel = util.createLabel(STR_RANK,30) titleLabel:setPosition(cc.p(visibleSize.width/2, visibleSize.height*0.85)) titleLabel:setColor(cc.c3b(0,0,0)) layer:addChild(titleLabel, 5) labelRank = util.createLabel(STR_RANK_T1,20) labelRank:setPosition(cc.p(visibleSize.width*0.2,visibleSize.height*0.7)) labelRank:setAnchorPoint(cc.p(0,0)) labelRank:setTag(TAG_LABEL_RANK) labelRank:setColor(cc.c3b(0,0,0)) layer:addChild(labelRank,5) labelName = util.createLabel(STR_RANK_T2,20) labelName:setPosition(cc.p(visibleSize.width*0.35,visibleSize.height*0.7)) labelName:setAnchorPoint(cc.p(0,0)) labelName:setTag(TAG_LABEL_NAME) labelName:setColor(cc.c3b(0,0,0)) layer:addChild(labelName,5) labelScore = util.createLabel(STR_RANK_T3,20) labelScore:setPosition(cc.p(visibleSize.width*0.7,visibleSize.height*0.7)) labelScore:setAnchorPoint(cc.p(0,0)) labelScore:setTag(TAG_LABEL_SCORE) labelScore:setColor(cc.c3b(0,0,0)) layer:addChild(labelScore,5) local tableView = cc.TableView:create(cc.size(visibleSize.width, visibleSize.height*0.55)) tableView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL) tableView:setPosition(cc.p(0, visibleSize.height*0.15)) tableView:setDelegate() tableView:setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN) layer:addChild(tableView,5) tableView:registerScriptHandler(scrollViewDidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) tableView:registerScriptHandler(scrollViewDidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) tableView:registerScriptHandler(tableCellTouched,cc.TABLECELL_TOUCHED) tableView:registerScriptHandler(cellSizeForTable,cc.TABLECELL_SIZE_FOR_INDEX) tableView:registerScriptHandler(tableCellAtIndex,cc.TABLECELL_SIZE_AT_INDEX) tableView:registerScriptHandler(numberOfCellsInTableView,cc.NUMBER_OF_CELLS_IN_TABLEVIEW) tableView:reloadData() local menus = STR_MENUS local function menuCallback(pSender) local gameLevel = pSender:getTag() print("gameLevel",gameLevel) for i=1,#menus do local node = layer:getChildByTag(i) if i==gameLevel then node:setEnabled(false) else node:setEnabled(true) node:getTitleLabel():setColor(cc.c3b(255,255,0)) end end end local h = visibleSize.height/(#menus+4) for i=1,#menus do local y = h*(#menus-i+2) local button = util.creatButtun(menus[i],20) button:setAnchorPoint(cc.p(0, 0.5)) button:setTag(i) button:setPosition(cc.p(0,y)) button:registerControlEventHandler(menuCallback,cc.CONTROL_EVENTTYPE_TOUCH_DOWN ) layer:addChild(button,6) end menuCallback(layer:getChildByTag(1)) local labelMy = util.createLabel("我:",20) labelMy:setPosition(cc.p(visibleSize.width*0.1,visibleSize.height*0.1)) labelMy:setColor(cc.c3b(255,0,0)) layer:addChild(labelMy, 5) local labelMyRank = util.createLabel("30",15) labelMyRank:setPosition(cc.p(visibleSize.width*0.25,visibleSize.height*0.1)) labelMyRank:setColor(cc.c3b(255,0,0)) layer:addChild(labelMyRank, 5) local labelMyName = util.createLabel("涵曦",15) labelMyName:setPosition(cc.p(visibleSize.width*0.4,visibleSize.height*0.1)) labelMyName:setColor(cc.c3b(255,0,0)) layer:addChild(labelMyName, 5) local labelMyScore = util.createLabel("2333",15) labelMyScore:setPosition(cc.p(visibleSize.width*0.75,visibleSize.height*0.1)) labelMyScore:setColor(cc.c3b(255,0,0)) layer:addChild(labelMyScore, 5) local background = cc.LayerColor:create(cc.c4b(255, 255, 255, 255), visibleSize.width,visibleSize.height) layer:addChild(background, 0) scene:addChild(layer) return scene end return RankScene
mit
kitala1/darkstar
scripts/zones/Temenos/mobs/Dark_Elemental.lua
33
1233
----------------------------------- -- Area: Temenos E T -- NPC: Dark_Elemental ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); switch (mobID): caseof { -- 100 a 106 inclut (Temenos -Northern Tower ) [16928892] = function (x) GetNPCByID(16928768+70):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+70):setStatus(STATUS_NORMAL); end , [16928893] = function (x) GetNPCByID(16928768+123):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+123):setStatus(STATUS_NORMAL); end , } end;
gpl-3.0
kitala1/darkstar
scripts/globals/weaponskills/fast_blade.lua
30
1345
----------------------------------- -- Fast Blade -- Sword weapon skill -- Skill Level: 5 -- Delivers a two-hit attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Soil Gorget. -- Aligned with the Soil Belt. -- Element: None -- Modifiers: STR:20% ; DEX:20% -- 100%TP 200%TP 300%TP -- 1.00 1.50 2.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 2; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; params.str_wsc = 0.2; params.dex_wsc = 0.2; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.4; params.dex_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
kitala1/darkstar
scripts/globals/weaponskills/namas_arrow.lua
12
1755
----------------------------------- -- Skill Level: N/A -- Description: Additional Effect: Temporarily improves Ranged Accuracy -- Aligned with the Light Gorget, Snow Gorget & Aqua Gorget. -- Properties -- Element: N/A -- Skillchain Properties: Light/Distortion -- Modifiers: STR: 40% AGI: 40% -- Damage Multipliers by TP: -- 100%TP 200%TP 300%TP -- 2.75 2.75 2.75 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 2.75; params.ftp200 = 2.75; params.ftp300 = 2.75; params.str_wsc = 0.4; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.4; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params); if((player:getEquipID(SLOT_RANGED) == 18348) and (player:getMainJob() == JOB_RNG or JOB_SAM)) then if(damage > 0) then if(player:getTP() >= 100 and player:getTP() < 200) then player:addStatusEffect(EFFECT_AFTERMATH, 20, 0, 20, 0, 12); elseif(player:getTP() >= 200 and player:getTP() < 300) then player:addStatusEffect(EFFECT_AFTERMATH, 20, 0, 40, 0, 12); elseif(player:getTP() == 300) then player:addStatusEffect(EFFECT_AFTERMATH, 20, 0, 60, 0, 12); end end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end;
gpl-3.0
kmiku7/redis-2.8.21-annotated
deps/lua/test/life.lua
888
2635
-- life.lua -- original by Dave Bollinger <DBollinger@compuserve.com> posted to lua-l -- modified to use ANSI terminal escape sequences -- modified to use for instead of while local write=io.write ALIVE="¥" DEAD="þ" ALIVE="O" DEAD="-" function delay() -- NOTE: SYSTEM-DEPENDENT, adjust as necessary for i=1,10000 do end -- local i=os.clock()+1 while(os.clock()<i) do end end function ARRAY2D(w,h) local t = {w=w,h=h} for y=1,h do t[y] = {} for x=1,w do t[y][x]=0 end end return t end _CELLS = {} -- give birth to a "shape" within the cell array function _CELLS:spawn(shape,left,top) for y=0,shape.h-1 do for x=0,shape.w-1 do self[top+y][left+x] = shape[y*shape.w+x+1] end end end -- run the CA and produce the next generation function _CELLS:evolve(next) local ym1,y,yp1,yi=self.h-1,self.h,1,self.h while yi > 0 do local xm1,x,xp1,xi=self.w-1,self.w,1,self.w while xi > 0 do local sum = self[ym1][xm1] + self[ym1][x] + self[ym1][xp1] + self[y][xm1] + self[y][xp1] + self[yp1][xm1] + self[yp1][x] + self[yp1][xp1] next[y][x] = ((sum==2) and self[y][x]) or ((sum==3) and 1) or 0 xm1,x,xp1,xi = x,xp1,xp1+1,xi-1 end ym1,y,yp1,yi = y,yp1,yp1+1,yi-1 end end -- output the array to screen function _CELLS:draw() local out="" -- accumulate to reduce flicker for y=1,self.h do for x=1,self.w do out=out..(((self[y][x]>0) and ALIVE) or DEAD) end out=out.."\n" end write(out) end -- constructor function CELLS(w,h) local c = ARRAY2D(w,h) c.spawn = _CELLS.spawn c.evolve = _CELLS.evolve c.draw = _CELLS.draw return c end -- -- shapes suitable for use with spawn() above -- HEART = { 1,0,1,1,0,1,1,1,1; w=3,h=3 } GLIDER = { 0,0,1,1,0,1,0,1,1; w=3,h=3 } EXPLODE = { 0,1,0,1,1,1,1,0,1,0,1,0; w=3,h=4 } FISH = { 0,1,1,1,1,1,0,0,0,1,0,0,0,0,1,1,0,0,1,0; w=5,h=4 } BUTTERFLY = { 1,0,0,0,1,0,1,1,1,0,1,0,0,0,1,1,0,1,0,1,1,0,0,0,1; w=5,h=5 } -- the main routine function LIFE(w,h) -- create two arrays local thisgen = CELLS(w,h) local nextgen = CELLS(w,h) -- create some life -- about 1000 generations of fun, then a glider steady-state thisgen:spawn(GLIDER,5,4) thisgen:spawn(EXPLODE,25,10) thisgen:spawn(FISH,4,12) -- run until break local gen=1 write("\027[2J") -- ANSI clear screen while 1 do thisgen:evolve(nextgen) thisgen,nextgen = nextgen,thisgen write("\027[H") -- ANSI home cursor thisgen:draw() write("Life - generation ",gen,"\n") gen=gen+1 if gen>2000 then break end --delay() -- no delay end end LIFE(40,20)
bsd-3-clause
kitala1/darkstar
scripts/zones/North_Gustaberg_[S]/npcs/Mining_Point.lua
29
1114
----------------------------------- -- Area: North Gustaberg [S] -- NPC: Mining Point ----------------------------------- package.loaded["scripts/zones/North_Gustaberg_[S]/TextIDs"] = nil; ------------------------------------- require("scripts/globals/mining"); require("scripts/zones/North_Gustaberg_[S]/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startMining(player,player:getZoneID(),npc,trade,0x00D3); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(MINING_IS_POSSIBLE_HERE,605); 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
kitala1/darkstar
scripts/zones/Castle_Oztroja/npcs/Antiqix.lua
19
7281
----------------------------------- -- Area: Castle Oztroja -- NPC: Antiqix -- Type: Dynamis Vendor -- @pos -207.835 -0.751 -25.498 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/dynamis"); ----------------------------------- -- 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) == true) then if (count == 1 and gil == TIMELESS_HOURGLASS_COST) then -- Hourglass purchase player:startEvent(54); elseif (gil == 0) then if (count == 1 and trade:hasItemQty(4236,1)) then -- Bringing back a Timeless Hourglass player:startEvent(97); -- Currency Exchanges elseif (count == CURRENCY_EXCHANGE_RATE and trade:hasItemQty(1449,CURRENCY_EXCHANGE_RATE)) then -- Single -> Hundred player:startEvent(55,CURRENCY_EXCHANGE_RATE); elseif (count == CURRENCY_EXCHANGE_RATE and trade:hasItemQty(1450,CURRENCY_EXCHANGE_RATE)) then -- Hundred -> Ten thousand player:startEvent(56,CURRENCY_EXCHANGE_RATE); elseif (count == 1 and trade:hasItemQty(1451,1)) then -- Ten thousand -> 100 Hundreds player:startEvent(58,1451,1450,CURRENCY_EXCHANGE_RATE); -- Currency Shop elseif (count == 7 and trade:hasItemQty(1450,7)) then -- Angel Skin (1312) buying = true; exchange = {7, 1312}; elseif (count == 23 and trade:hasItemQty(1450,23)) then -- Chronos Tooth (1463) buying = true; exchange = {23,1463}; elseif (count == 8 and trade:hasItemQty(1450,8)) then -- Colossal Skull (1518) buying = true; exchange = {8, 1518}; elseif (count == 28 and trade:hasItemQty(1450,28)) then -- Damascus Ingot (658) buying = true; exchange = {28, 658}; elseif (count == 9 and trade:hasItemQty(1450,9)) then -- Lancewood Log (1464) buying = true; exchange = {9, 1464}; elseif (count == 25 and trade:hasItemQty(1450,25)) then -- Lancewood Lumber (1462) buying = true; exchange = {25, 1462}; elseif (count == 24 and trade:hasItemQty(1450,24)) then -- Relic Steel (1467) buying = true; exchange = {24, 1467}; 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(57,1450,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(53, 1449, CURRENCY_EXCHANGE_RATE, 1450, CURRENCY_EXCHANGE_RATE, 1451, TIMELESS_HOURGLASS_COST, 4236, TIMELESS_HOURGLASS_COST); else player:startEvent(50); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("Update CSID: %u",csid); -- printf("Update RESULT: %u",option); if (csid == 53) 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(1451, 1450, 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(7,1312,23,1463,8,1518,28,658); elseif (option == 3) then -- Hundreds sales menu Page 2 (price1 item1 price2 item2 price3 item3) player:updateEvent(9,1464,25,1462,24,1467); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("Finish CSID: %u",csid); -- printf("Finish RESULT: %u",option); if(csid == 54)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 == 97) then -- Bringing back an hourglass for gil. player:tradeComplete(); player:addGil(TIMELESS_HOURGLASS_COST); player:messageSpecial(GIL_OBTAINED,TIMELESS_HOURGLASS_COST); elseif (csid == 55) then -- Trading Singles for a Hundred if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1450); else player:tradeComplete(); player:addItem(1450); player:messageSpecial(ITEM_OBTAINED,1450); end elseif (csid == 56) then -- Trading 100 Hundreds for Ten thousand if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1451); else player:tradeComplete(); player:addItem(1451); player:messageSpecial(ITEM_OBTAINED,1451); end elseif (csid == 58) then -- Trading Ten thousand for 100 Hundreds if (player:getFreeSlotsCount() <= 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1450); else player:tradeComplete(); player:addItem(1450,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(1450,CURRENCY_EXCHANGE_RATE - 99); end player:messageSpecial(ITEMS_OBTAINED,1450,CURRENCY_EXCHANGE_RATE); end end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/LaisavieXBerlends1.lua
36
1080
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Laisavie X Berlends -- @zone 80 -- @pos 26 2 6 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again! 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
paulosalvatore/maruim_server
data/modules/scripts/equipobject/equipobject.lua
2
3758
EquipObject = {} EquipObject.Slots = { [48] = CONST_SLOT_LEFT, [49] = CONST_SLOT_HEAD, [50] = CONST_SLOT_NECKLACE, [52] = CONST_SLOT_BACKPACK, [56] = CONST_SLOT_ARMOR, [112] = CONST_SLOT_LEGS, [176] = CONST_SLOT_FEET, [304] = CONST_SLOT_RING, [560] = CONST_SLOT_AMMO, [2096] = SLOTP_TWO_HAND -- We only use slot position in this! } function onRecvbyte(player, msg, byte) local itemType = Game.getItemIdByClientId(msg:getU16()) local item = player:getItemById(itemType:getId(), true) if not item then item = player:getItemById(itemType:getTransformEquipId(), true) if not item then item = player:getItemById(itemType:getTransformDeEquipId(), true) end if not item then return player:sendCancelMessage("Sorry not possible.") end end local newItemType = ItemType(item:getId()) local slotP = EquipObject.Slots[newItemType:getSlotPosition()] if newItemType:getWeaponType() == WEAPON_SHIELD then slotP = CONST_SLOT_RIGHT end if slotP == CONST_SLOT_BACKPACK then player:sendCancelMessage("You can't equip a backpack.") elseif slotP == SLOTP_TWO_HAND then local slotLeft_item = player:getSlotItem(CONST_SLOT_LEFT) local slotRight_Item = player:getSlotItem(CONST_SLOT_RIGHT) if slotLeft_item then if slotLeft_item:getId() == newItemType:getId() then slotLeft_item:moveToSlot(player, 0) else if slotRight_Item then slotRight_Item:moveToSlot(player, 0) end item:moveToSlot(player, CONST_SLOT_LEFT) end else if slotRight_Item then slotRight_Item:moveToSlot(player, 0) end item:moveToSlot(player, CONST_SLOT_LEFT) end elseif slotP == CONST_SLOT_RING then local slotRing_item = player:getSlotItem(CONST_SLOT_RING) if slotRing_item then if slotRing_item:getId() == newItemType:getId() then slotRing_item:moveToSlot(player, 0) elseif slotRing_item:getId() == newItemType:getTransformEquipId() then slotRing_item:moveToSlot(player, 0) elseif slotRing_item:getId() == newItemType:getTransformDeEquipId() then slotRing_item:moveToSlot(player, 0) else item:moveToSlot(player, CONST_SLOT_RING) end else item:moveToSlot(player, CONST_SLOT_RING) end elseif slotP == CONST_SLOT_RIGHT then local slotRight_Item = player:getSlotItem(CONST_SLOT_RIGHT) local slotLeft_item = player:getSlotItem(CONST_SLOT_LEFT) if slotRight_Item then if slotRight_Item:getId() == item:getId() then slotRight_Item:moveToSlot(player, 0) else item:moveToSlot(player, CONST_SLOT_RIGHT) end else if slotLeft_item and EquipObject.Slots[ItemType(slotLeft_item:getId()):getSlotPosition()] == SLOTP_TWO_HAND then slotLeft_item:moveToSlot(player, 0) end item:moveToSlot(player, CONST_SLOT_RIGHT) end elseif slotP then local slotItem = player:getSlotItem(slotP) if slotItem then if slotItem:getId() == item:getId() then item:moveToSlot(player, 0) else EquipObject.StackAdd(player, item, slotP, newItemType:isStackable()) end else EquipObject.StackAdd(player, item, slotP, newItemType:isStackable()) end end return player:sendCancelMessage("You are exhausted.") end EquipObject.StackAdd = function(player, item, slotP, isStackable) if isStackable and item:getCount() < 100 and item:getCount() < player:getItemCount(item:getId()) then local itemId, count = item:getId(), 0 while player:getItemCount(itemId) do if count == 100 then break end local _item = player:getItemById(itemId, true) if not _item then break end if _item:getCount() > 100 - count then _item:remove(100 - count) count = 100 else count = count + _item:getCount() _item:remove() end end player:addItem(itemId, count, true, 1, slotP) else item:moveToSlot(player, slotP) end end
gpl-2.0
dtrip/.ubuntu
awesome/3.4/volume.lua
2
1055
volume_widget = widget({ type = "textbox", name = "tb_volume", align = "right" }) function update_volume(widget) local fd = io.popen("amixer sget Master") local status = fd:read("*all") fd:close() local volume = tonumber(string.match(status, "(%d?%d?%d)%%")) / 100 -- volume = string.format("% 3d", volume) status = string.match(status, "%[(o[^%]]*)%]") -- starting colour local sr, sg, sb = 0x3F, 0x3F, 0x3F -- ending colour local er, eg, eb = 0xDC, 0xDC, 0xCC local ir = volume * (er - sr) + sr local ig = volume * (eg - sg) + sg local ib = volume * (eb - sb) + sb interpol_colour = string.format("%.2x%.2x%.2x", ir, ig, ib) if string.find(status, "on", 1, true) then volume = " <span background='#" .. interpol_colour .. "'> </span>" else volume = " <span color='red' background='#" .. interpol_colour .. "'> M </span>" end widget.text = volume end update_volume(volume_widget) awful.hooks.timer.register(1, function () update_volume(volume_widget) end)
mit
kitala1/darkstar
scripts/globals/items/noble_lady.lua
17
1392
----------------------------------------- -- ID: 4485 -- Item: noble_lady -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 3 -- Mind -5 -- Charisma 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if(target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4485); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_MND, -5); target:addMod(MOD_CHR, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_MND, -5); target:delMod(MOD_CHR, 3); end;
gpl-3.0
kitala1/darkstar
scripts/globals/weaponskills/savage_blade.lua
30
1556
----------------------------------- -- Savage Blade -- Sword weapon skill -- Skill Level: 240 -- Delivers an aerial attack comprised of two hits. Damage varies with TP. -- In order to obtain Savage Blade, the quest Old Wounds must be completed. -- Will stack with Sneak Attack. -- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget -- Aligned with the Breeze Belt, Thunder Belt & Soil Belt. -- Element: None -- Modifiers: STR:50% ; MND:50% -- 100%TP 200%TP 300%TP -- 4.00 10.25 13.75 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 2; params.ftp100 = 1; params.ftp200 = 1.75; params.ftp300 = 3.5; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.5; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 4; params.ftp200 = 10.25; params.ftp300 = 13.75; params.str_wsc = 0.5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
redg3ar/meowrio
enemy.lua
1
2254
class = require("lib/30log/30log") vector = require("lib/hump/vector") object = require("object") enemy = object:extend("enemy") function enemy:init(file, loc) enemy.super.init(self, file) self.vel = vector(0, 0) self.gravity = vector(0, 64 * 16) self.friction = 0 self.spawn = loc:clone() self.loc = nil self.direction = -1 self.SPEED = 60 self.MAXVEL = 60 -- dont think about this plaease: self.SLIDE = 8 end function enemy:load() self.loc = self.spawn:clone() enemy.super.load(self) end function enemy:draw() love.graphics.draw( self.image, self.loc.x + self.image:getWidth() / 2, self.loc.y + self.image:getHeight() / 2, 0, self.scale.x, self.scale.y, self.image:getWidth() / 2, self.image:getHeight() / 2 ) end function enemy:update(dt) if not self:groundcollide() then self.vel = self.vel + (self.gravity * dt) else self.vel.y = 0 end if self:sidecollide() then self.direction = self.direction * -1 self.vel.x = self.direction * 20 end self.vel.x = self.vel.x + (self.SPEED * self.direction) self.vel.x = math.min(math.abs(self.vel.x), self.MAXVEL) * math.sign(self.vel.x) self.vel.x = self.vel.x - (self.friction * dt) * math.sign(self.vel.x) if math.abs(self.vel.x) <= 4 then self.vel.x = 0 end local goalX, goalY = (self.loc + self.vel * dt):unpack() self.loc.x, self.loc.y, cols, _ = world:move(self, goalX, goalY, self.collidefunc) for i = 1, #cols do if cols[i].other.name == "player" and player:groundcollide() then cols[i].other.gamestate = 2 end end end function enemy:groundcollide() local actualx, actualy = world:check(self, self.loc.x, self.loc.y + 1, self.collidefunc) if actualy ~= self.loc.y + 1 then return true end end function enemy:sidecollide() local actualx, actualy = world:check(self, self.loc.x + 1, self.loc.y, self.collidefunc) if actualx ~= self.loc.x + 1 then return true end actualx, actualy = world:check(self, self.loc.x - 1, self.loc.y, self.collidefunc) if actualx ~= self.loc.x - 1 then return true end end enemy.collidefunc = function(item, other) if other.name == "tile" then return "slide" else return "cross" end end return enemy
mit
kitala1/darkstar
scripts/zones/Upper_Delkfutts_Tower/npcs/_4e2.lua
17
1329
----------------------------------- -- Area: Upper Delkfutt's Tower -- NPC: Elevator -- @pos -294 -143 27 158 ----------------------------------- package.loaded["scripts/zones/Upper_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Upper_Delkfutts_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(549,1) and trade:getItemCount() == 1) then -- Trade Delkfutt Key player:startEvent(0x0006); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(DELKFUTT_KEY)) then player:startEvent(0x0006); else player:messageSpecial(THIS_ELEVATOR_GOES_DOWN); 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); end;
gpl-3.0
fqrouter/luci
applications/luci-statistics/luasrc/model/cbi/luci_statistics/df.lua
78
1628
--[[ Luci configuration model for statistics - collectd df 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("DF Plugin Configuration"), translate( "The df plugin collects statistics about the disk space " .. "usage on different devices, mount points or filesystem types." )) -- collectd_df config section s = m:section( NamedSection, "collectd_df", "luci_statistics" ) -- collectd_df.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_df.devices (Device) devices = s:option( Value, "Devices", translate("Monitor devices") ) devices.default = "/dev/mtdblock/4" devices.optional = true devices:depends( "enable", 1 ) -- collectd_df.mountpoints (MountPoint) mountpoints = s:option( Value, "MountPoints", translate("Monitor mount points") ) mountpoints.default = "/overlay" mountpoints.optional = true mountpoints:depends( "enable", 1 ) -- collectd_df.fstypes (FSType) fstypes = s:option( Value, "FSTypes", translate("Monitor filesystem types") ) fstypes.default = "tmpfs" fstypes.optional = true fstypes:depends( "enable", 1 ) -- collectd_df.ignoreselected (IgnoreSelected) ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") ) ignoreselected.default = 0 ignoreselected:depends( "enable", 1 ) return m
apache-2.0
kitala1/darkstar
scripts/globals/mobskills/Wanion.lua
7
1325
--------------------------------------------------- -- Wanion -- AoE of all status ailments it has. --------------------------------------------------- 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) -- list of effects to give in AoE local effects = {EFFECT_SLOW, EFFECT_DIA, EFFECT_BIO, EFFECT_WEIGHT, EFFECT_DEFENSE_DOWN, EFFECT_PARALYSIS, EFFECT_BLINDNESS, EFFECT_SILENCE, EFFECT_POISON} local lastEffect = 0; local effectCount = false; for i, effect in ipairs(effects) do if(mob:hasStatusEffect(effect) == true) then effectCount = true; local currentEffect = mob:getStatusEffect(effect); local msg = MobStatusEffectMove(mob, target, effect, currentEffect:getPower(), 3, 120); if(msg == MSG_ENFEEB_IS) then lastEffect = effect; end end end -- all resisted if(lastEffect == 0) then skill:setMsg(MSG_RESIST); end -- no effects present if(effectCount == false) then skill:setMsg(MSG_NO_EFFECT); end return lastEffect; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Apollyon/mobs/Jidra.lua
17
2157
----------------------------------- -- Area: Apollyon SW -- NPC: Jidra ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if(mobID ==16932882)then SpawnMob(16932889):updateEnmity(target); elseif(mobID ==16932883)then SpawnMob(16932890):updateEnmity(target); elseif(mobID ==16932884)then SpawnMob(16932891):updateEnmity(target); elseif(mobID ==16932885)then SpawnMob(16932892):updateEnmity(target); elseif(mobID ==16932886)then SpawnMob(16932893):updateEnmity(target); elseif(mobID ==16932887)then SpawnMob(16932894):updateEnmity(target); elseif(mobID ==16932888)then SpawnMob(16932895):updateEnmity(target); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if( IsMobDead(16932882)==true and IsMobDead(16932883)==true and IsMobDead(16932884)==true and IsMobDead(16932885)==true and IsMobDead(16932886)==true and IsMobDead(16932887)==true and IsMobDead(16932888)==true )then -- time GetNPCByID(16932864+70):setPos(mobX+3,mobY,mobZ); GetNPCByID(16932864+70):setStatus(STATUS_NORMAL); -- recover GetNPCByID(16932864+71):setPos(mobX+4,mobY,mobZ+4); GetNPCByID(16932864+71):setStatus(STATUS_NORMAL); -- item GetNPCByID(16932864+72):setPos(mobX,mobY,mobZ-3); GetNPCByID(16932864+72):setStatus(STATUS_NORMAL); end end;
gpl-3.0
kitala1/darkstar
scripts/zones/PsoXja/npcs/_i96.lua
17
1260
----------------------------------- -- Area: Pso'Xja -- NPC: _i96 (Stone Gate) -- Notes: Red Bracelet Door -- @pos -310.000 -1.925 -238.399 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local Z=player:getZPos(); if(Z >= -238)then if (player:hasKeyItem(596)==true) then -- Green Bracelet player:startEvent(0x003e); else player:messageSpecial(ARCH_GLOW_GREEN); end elseif(Z <= -239)then player:messageSpecial(CANNOT_OPEN_SIDE); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) end;
gpl-3.0
kitala1/darkstar
scripts/globals/porter_moogle_util.lua
27
27581
----------------------------------- -- Porter Moogle Utilities -- desc: Common functionality for Porter Moogles. ----------------------------------- require("scripts/globals/common"); -- Item IDs for all of the slips. local slipIds = { 29312, 29313, 29314, 29315, 29316, 29317, 29318, 29319, 29320, 29321, 29322, 29323, 29324, 29325, 29326, 29327, 29328, 29329, 29330, 29331, 29332 }; -- Item IDs for the items stored on each slip. Zero-based index in the table represents the bit indicating if the slip has the item stored. local slipItems = { [slipIds[1]] = { 16084, 14546, 14961, 15625, 15711, 16085, 14547, 14962, 15626, 15712, 16086, 14548, 14963, 15627, 15713, 16087, 14549, 14964, 15628, 15714, 16088, 14550, 14965, 15629, 15715, 16089, 14551, 14966, 15630, 15716, 16090, 14552, 14967, 15631, 15717, 16091, 14553, 14968, 15632, 15718, 16092, 14554, 14969, 15633, 15719, 16093, 14555, 14970, 15634, 15720, 16094, 14556, 14971, 15635, 15721, 16095, 14557, 14972, 15636, 15722, 16096, 14558, 14973, 15637, 15723, 16097, 14559, 14974, 15638, 15724, 16098, 14560, 14975, 15639, 15725, 16099, 14561, 14976, 15640, 15726, 16100, 14562, 14977, 15641, 15727, 16101, 14563, 14978, 15642, 15728, 16102, 14564, 14979, 15643, 15729, 16103, 14565, 14980, 15644, 15730, 16106, 14568, 14983, 15647, 15733, 16107, 14569, 14984, 15648, 15734, 16108, 14570, 14985, 15649, 15735, 16602, 17741, 18425, 18491, 18588, 18717, 18718, 18850, 18943, 16069, 14530, 14940, 15609, 15695, 16062, 14525, 14933, 15604, 15688, 16064, 14527, 14935, 15606, 15690, 18685, 18065, 17851, 18686, 18025, 18435, 18113, 17951, 17715, 18485, 18408, 18365, 18583, 18417, 18388, 16267, 16268, 16269, 16228, 16229, 15911, 15799, 15800, 15990, 17745, 18121, 16117, 14577, 17857 }, [slipIds[2]] = { 12421, 12549, 12677, 12805, 12933, 13911, 14370, 14061, 14283, 14163, 12429, 12557, 12685, 12813, 12941, 13924, 14371, 14816, 14296, 14175, 13934, 14387, 14821, 14303, 14184, 13935, 14388, 14822, 14304, 14185, 13876, 13787, 14006, 14247, 14123, 13877, 13788, 14007, 14248, 14124, 13908, 14367, 14058, 14280, 14160, 13909, 14368, 14059, 14281, 14161, 16113, 14573, 14995, 15655, 15740, 16115, 14575, 14997, 15657, 15742, 16114, 14574, 14996, 15656, 15741, 16116, 14576, 14998, 15658, 15743, 12818, 18198, 12946, 18043, 12690, 17659, 12296, 12434, 15471, 15472, 15473, 15508, 15509, 15510, 15511, 15512, 15513, 15514, 17710, 17595, 18397, 18360, 18222, 17948, 18100, 15475, 15476, 15477, 15488, 15961, 14815, 14812, 14813, 15244, 15240, 14488, 14905, 15576, 15661, 15241, 14489, 14906, 15577, 15662, 13927, 14378, 14076, 14308, 14180, 13928, 14379, 14077, 14309, 14181, 10438, 10276, 10320, 10326, 10367, 10439, 10277, 10321, 10327, 10368, 10440, 10278, 10322, 10328, 10369, 10441, 10279, 10323, 10329, 10370 }, [slipIds[3]] = { 16155, 11282, 15021, 16341, 11376, 16156, 11283, 15022, 16342, 11377, 16157, 11284, 15023, 16343, 11378, 16148, 14590, 15011, 16317, 15757, 16143, 14591, 15012, 16318, 15758, 16146, 14588, 15009, 16315, 15755, 16147, 14589, 15010, 16316, 15756, 15966, 15967, 19041, 17684, 17685, 11636, 15844, 15934, 16258, 18735, 18734, 16291, 16292, 19042, 15935, 16293, 16294, 15936, 18618, 11588, 11545, 16158, 16159, 16160, 16149, 14583, 15007, 16314, 15751, 16141, 14581, 15005, 16312, 15749, 16142, 14582, 15006, 16313, 15750, 10876, 10450, 10500, 11969, 10600, 10877, 10451, 10501, 11970, 10601, 10878, 10452, 10502, 11971, 10602, 19132, 18551, 11798, 11362, 11363, 11625, 15959, 16259 }, [slipIds[4]] = { 12511, 12638, 13961, 14214, 14089, 12512, 12639, 13962, 14215, 14090, 13855, 12640, 13963, 14216, 14091, 13856, 12641, 13964, 14217, 14092, 12513, 12642, 13965, 14218, 14093, 12514, 12643, 13966, 14219, 14094, 12515, 12644, 13967, 14220, 14095, 12516, 12645, 13968, 14221, 14096, 12517, 12646, 13969, 14222, 14097, 13857, 12647, 13970, 14223, 14098, 12518, 12648, 13971, 14099, 14224, 13868, 13781, 13972, 14225, 14100, 13869, 13782, 13973, 14226, 14101, 12519, 12649, 13974, 14227, 14102, 12520, 12650, 13975, 14228, 14103, 15265, 14521, 14928, 15600, 15684, 15266, 14522, 14929, 15601, 15685, 15267, 14523, 14930, 15602, 15686, 16138, 14578, 15002, 15659, 15746, 16139, 14579, 15003, 15660, 15747, 16140, 14580, 15004, 16311, 15748, 16678, 17478, 17422, 17423, 16829, 16764, 17643, 16798, 16680, 16766, 17188, 17812, 17771, 17772, 16887, 17532, 17717, 18702, 17858, 19203, 21461, 21124, 20776, 27786, 27926, 28066, 28206, 28346, 27787, 27927, 28067, 28207, 28347 }, [slipIds[5]] = { 15225, 14473, 14890, 15561, 15352, 15226, 14474, 14891, 15562, 15353, 15227, 14475, 14892, 15563, 15354, 15228, 14476, 14893, 15564, 15355, 15229, 14477, 14894, 15565, 15356, 15230, 14478, 14895, 15566, 15357, 15231, 14479, 14896, 15567, 15358, 15232, 14480, 14897, 15568, 15359, 15233, 14481, 14898, 15569, 15360, 15234, 14482, 14899, 15570, 15361, 15235, 14483, 14900, 15362, 15571, 15236, 14484, 14901, 15572, 15363, 15237, 14485, 14902, 15573, 15364, 15238, 14486, 14903, 15574, 15365, 15239, 14487, 14904, 15575, 15366, 11464, 11291, 15024, 16345, 11381, 11467, 11294, 15027, 16348, 11384, 11470, 11297, 15030, 16351, 11387, 11475, 11302, 15035, 16357, 11393, 11476, 11303, 15036, 16358, 11394, 11477, 11304, 15037, 16359, 11395 }, [slipIds[6]] = { 15072, 15087, 15102, 15117, 15132, 15871, 15073, 15088, 15103, 15118, 15133, 15478, 15074, 15089, 15104, 15119, 15134, 15872, 15075, 15090, 15105, 15120, 15135, 15874, 15076, 15091, 15106, 15121, 15136, 15873, 15077, 15092, 15107, 15122, 15137, 15480, 15078, 15093, 15108, 15123, 15138, 15481, 15079, 15094, 15109, 15124, 15139, 15479, 15080, 15095, 15110, 15125, 15140, 15875, 15081, 15096, 15111, 15126, 15141, 15482, 15082, 15097, 15112, 15127, 15142, 15876, 15083, 15098, 15113, 15128, 15143, 15879, 15084, 15099, 15114, 15129, 15144, 15877, 15085, 15100, 15115, 15130, 15145, 15878, 15086, 15101, 15116, 15131, 15146, 15484, 11465, 11292, 15025, 16346, 11382, 16244, 11468, 11295, 15028, 16349, 11385, 15920, 11471, 11298, 15031, 16352, 11388, 16245, 11478, 11305, 15038, 16360, 11396, 16248, 11480, 11307, 15040, 16362, 11398, 15925 }, [slipIds[7]] = { 15245, 14500, 14909, 15580, 15665, 15246, 14501, 14910, 15581, 15666, 15247, 14502, 14911, 15582, 15667, 15248, 14503, 14912, 15583, 15668, 15249, 14504, 14913, 15584, 15669, 15250, 14505, 14914, 15585, 15670, 15251, 14506, 14915, 15586, 15671, 15252, 14507, 14916, 15587, 15672, 15253, 14508, 14917, 15588, 15673, 15254, 14509, 14918, 15589, 15674, 15255, 14510, 14919, 15590, 15675, 15256, 14511, 14920, 15591, 15676, 15257, 14512, 14921, 15592, 15677, 15258, 14513, 14922, 15593, 15678, 15259, 14514, 14923, 15594, 15679, 11466, 11293, 15026, 16347, 11383, 11469, 11296, 15029, 16350, 11386, 11472, 11299, 15032, 16353, 11389, 11479, 11306, 15039, 16361, 11397, 11481, 11308, 15041, 16363, 11399 }, [slipIds[8]] = { 12008, 12028, 12048, 12068, 12088, 11591, 19253, 12009, 12029, 12049, 12069, 12089, 11592, 19254, 12010, 12030, 12050, 12070, 12090, 11615, 11554, 12011, 12031, 12051, 12071, 12091, 11593, 16203, 12012, 12032, 12052, 12072, 12092, 11594, 16204, 12013, 12033, 12053, 12073, 12093, 11736, 19260, 12014, 12034, 12054, 12074, 12094, 11595, 11750, 12015, 12035, 12055, 12075, 12095, 11616, 11737, 12016, 12036, 12056, 12076, 12096, 11617, 11555, 12017, 12037, 12057, 12077, 12097, 11618, 11738, 12018, 12038, 12058, 12078, 12098, 11596, 16205, 12019, 12039, 12059, 12079, 12099, 11597, 16206, 12020, 12040, 12060, 12080, 12100, 11598, 16207, 12021, 12041, 12061, 12081, 12101, 11599, 16208, 12022, 12042, 12062, 12082, 12102, 11619, 11739, 12023, 12043, 12063, 12083, 12103, 11600, 19255, 12024, 12044, 12064, 12084, 12104, 11601, 16209, 12025, 12045, 12065, 12085, 12105, 11602, 11751, 12026, 12046, 12066, 12086, 12106, 11603, 19256, 12027, 12047, 12067, 12087, 12107, 11620, 19247, 11703, 11704, 11705, 11706, 11707, 11708, 11709, 11710, 11711, 11712, 11713, 11714, 11715, 11716, 11717, 11718, 11719, 11720, 11721, 11722 }, [slipIds[9]] = { 11164, 11184, 11204, 11224, 11244, 11165, 11185, 11205, 11225, 11245, 11166, 11186, 11206, 11226, 11246, 11167, 11187, 11207, 11227, 11247, 11168, 11188, 11208, 11228, 11248, 11169, 11189, 11209, 11229, 11249, 11170, 11190, 11210, 11230, 11250, 11171, 11191, 11211, 11231, 11251, 11172, 11192, 11212, 11232, 11252, 11173, 11193, 11213, 11233, 11253, 11174, 11194, 11214, 11234, 11254, 11175, 11195, 11215, 11235, 11255, 11176, 11196, 11216, 11236, 11256, 11177, 11197, 11217, 11237, 11257, 11178, 11198, 11218, 11238, 11258, 11179, 11199, 11219, 11239, 11259, 11180, 11200, 11220, 11240, 11260, 11181, 11201, 11221, 11241, 11261, 11182, 11202, 11222, 11242, 11262, 11183, 11203, 11223, 11243, 11263 }, [slipIds[10]] = { 11064, 11084, 11104, 11124, 11144, 11065, 11085, 11105, 11125, 11145, 11066, 11086, 11106, 11126, 11146, 11067, 11087, 11107, 11127, 11147, 11068, 11088, 11108, 11128, 11148, 11069, 11089, 11109, 11129, 11149, 11070, 11090, 11110, 11130, 11150, 11071, 11091, 11111, 11131, 11151, 11072, 11092, 11112, 11132, 11152, 11073, 11093, 11113, 11133, 11153, 11074, 11094, 11114, 11134, 11154, 11075, 11095, 11115, 11135, 11155, 11076, 11096, 11116, 11136, 11156, 11077, 11097, 11117, 11137, 11157, 11078, 11098, 11118, 11138, 11158, 11079, 11099, 11119, 11139, 11159, 11080, 11100, 11120, 11140, 11160, 11081, 11101, 11121, 11141, 11161, 11082, 11102, 11122, 11142, 11162, 11083, 11103, 11123, 11143, 11163 }, [slipIds[11]] = { 15297, 15298, 15299, 15919, 15929, 15921, 18871, 16273, 18166, 18167, 18256, 13216, 13217, 13218, 15455, 15456, 181, 182, 183, 184, 129, 11499, 18502, 18855, 19274, 18763, 19110, 15008, 17764, 19101, 365, 366, 367, 15860, 272, 273, 274, 275, 276, 11853, 11956, 11854, 11957, 11811, 11812, 11861, 11862, 3676, 18879, 3647, 3648, 3649, 3677, 18880, 18863, 18864, 15178, 14519, 10382, 11965, 11967, 15752, 15179, 14520, 10383, 11966, 11968, 15753, 10875, 3619, 3620, 3621, 3650, 3652, 10430, 10251, 10593, 10431, 10252, 10594, 10432, 10253, 10595, 10433, 10254, 10596, 10429, 10250, 17031, 17032, 10807, 18881, 10256, 10330, 10257, 10331, 10258, 10332, 10259, 10333, 10260, 10334, 10261, 10335, 10262, 10336, 10263, 10337, 10264, 10338, 10265, 10339, 10266, 10340, 10267, 10341, 10268, 10342, 10269, 10343, 10270, 10344, 10271, 10345, 10446, 10447, 426, 10808, 3654, 265, 266, 267, 269, 270, 271, 18464, 18545, 18563, 18912, 18913, 10293, 10809, 10810, 10811, 10812, 27803, 28086, 27804, 28087, 27805, 28088, 27806, 28089, 27765, 27911, 27760, 27906, 27759, 28661, 286, 27757, 27758, 287, 27899, 28185, 28324, 27898, 28655, 27756, 28511, 21118, 27902, 100, 21117, 87, 20953, 21280, 28652, 28650, 27726, 28509, 28651, 27727, 28510, 27872, 21113, 27873, 21114, 20532, 20533, 27717, 27718 }, [slipIds[12]] = { 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2041, 2042, 2043, 2044, 2045, 2046, 2047, 2048, 2049, 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2077, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2096, 2097, 2098, 2099, 2100, 2101, 2102, 2103, 2104, 2105, 2106, 2107, 2662, 2663, 2664, 2665, 2666, 2667, 2668, 2669, 2670, 2671, 2672, 2673, 2674, 2675, 2676, 2718, 2719, 2720, 2721, 2722, 2723, 2724, 2725, 2726, 2727 }, [slipIds[13]] = { 10650, 10670, 10690, 10710, 10730, 10651, 10671, 10691, 10711, 10731, 10652, 10672, 10692, 10712, 10732, 10653, 10673, 10693, 10713, 10733, 10654, 10674, 10694, 10714, 10734, 10655, 10675, 10695, 10715, 10735, 10656, 10676, 10696, 10716, 10736, 10657, 10677, 10697, 10717, 10737, 10658, 10678, 10698, 10718, 10738, 10659, 10679, 10699, 10719, 10739, 10660, 10680, 10700, 10720, 10740, 10661, 10681, 10701, 10721, 10741, 10662, 10682, 10702, 10722, 10742, 10663, 10683, 10703, 10723, 10743, 10664, 10684, 10704, 10724, 10744, 10665, 10685, 10705, 10725, 10745, 10666, 10686, 10706, 10726, 10746, 10667, 10687, 10707, 10727, 10747, 10668, 10688, 10708, 10728, 10748, 10669, 10689, 10709, 10729, 10749 }, [slipIds[14]] = { 10901, 10474, 10523, 10554, 10620, 10906, 10479, 10528, 10559, 10625, 10911, 10484, 10533, 10564, 10630, 19799, 18916, 10442, 10280, 16084, 27788, 27928, 28071, 28208, 27649, 27789, 27929, 28072, 28209, 27650, 27790, 27930, 28073, 28210, 27651, 27791, 27931, 28074, 28211, 27652, 27792, 27932, 28075, 28212, 27653, 27793, 27933, 28076, 28213, 27654, 27794, 27934, 28077, 28214, 27655, 27795, 27935, 28078, 28215, 27656, 27796, 27936, 28079, 28216, 27657, 27797, 27937, 28080, 28217, 27658, 27798, 27938, 28081, 28218, 27659, 27799, 27939, 28082, 28219, 27660, 27800, 27940, 28083, 28220, 27661, 27801, 27941, 28084, 28221, 27662, 27802, 27942, 28085, 28222 }, [slipIds[15]] = { 27663, 27807, 27943, 28090, 28223, 27664, 27808, 27944, 28091, 28224, 27665, 27809, 27945, 28092, 28225, 27666, 27810, 27946, 28093, 28226, 27667, 27811, 27947, 28094, 28227, 27668, 27812, 27948, 28095, 28228, 27669, 27813, 27949, 28096, 28229, 27670, 27814, 27950, 28097, 28230, 27671, 27815, 27951, 28098, 28231, 27672, 27816, 27952, 28099, 28232, 27673, 27817, 27953, 28100, 28233, 27674, 27818, 27954, 28101, 28234, 27675, 27819, 27955, 28102, 28235, 27676, 27820, 27956, 28103, 28236, 27677, 27821, 27957, 28104, 28237, 27678, 27822, 27958, 28105, 28238, 27679, 27823, 27959, 28106, 28239, 27680, 27824, 27960, 28107, 28240, 27681, 27825, 27961, 28108, 28241, 27682, 27826, 27962, 28109, 28242, 27683, 27827, 27963, 28110, 28243 }, [slipIds[16]] = { 27684, 27828, 27964, 28111, 28244, 27685, 27829, 27965, 28112, 28245, 27686, 27830, 27966, 28113, 28246, 28246, 27831, 27967, 28114, 28247, 27688, 27832, 27968, 28115, 28248, 27689, 27833, 27969, 28116, 28249, 27690, 27834, 27970, 28117, 28250, 27691, 27835, 27971, 28118, 28251, 27692, 27836, 27972, 28119, 28252, 27693, 27837, 27973, 28120, 28253, 27694, 27838, 27974, 28121, 28254, 27695, 27839, 27975, 28122, 28255, 27696, 27840, 27976, 28123, 28256, 27697, 27841, 27977, 28124, 28257, 27698, 27842, 27978, 28125, 28258, 27699, 27843, 27979, 28126, 28259, 27700, 27844, 27980, 28127, 28260, 27701, 27845, 27981, 28128, 28261, 27702, 27846, 27982, 28129, 28262, 27703, 27847, 27983, 28130, 28263, 27704, 27848, 27984, 28131, 28264, 27705, 27849, 27985, 28132, 28265, 27706, 27850, 27986, 28133, 28266 }, [slipIds[17]] = { 26624, 26800, 26976, 27152, 27328, 26626, 26802, 26978, 27154, 27330, 26628, 26804, 26980, 27156, 27332, 26630, 26806, 26982, 27158, 27334, 26632, 26808, 26984, 27160, 27336, 26634, 26810, 26986, 27162, 27338, 26636, 26812, 26988, 27164, 27340, 26638, 26814, 26990, 27166, 27342, 26640, 26816, 26992, 27168, 27344, 26642, 26818, 26994, 27170, 27346, 26644, 26820, 26996, 27172, 27348, 26646, 26822, 26998, 27174, 27350, 26648, 26824, 27000, 27176, 27352, 26650, 26826, 27002, 27178, 27354, 26652, 26828, 27004, 27180, 27356, 26654, 26830, 27006, 27182, 27358, 26656, 26832, 27008, 27184, 27360, 26658, 26834, 27010, 27186, 27362, 26660, 26836, 27012, 27188, 27364, 26662, 26838, 27014, 27190, 27366, 26664, 26840, 27016, 27192, 27368, 26666, 26842, 27018, 27194, 27370 }, [slipIds[18]] = { 26625, 26801, 26977, 27153, 27329, 26627, 26803, 26979, 27155, 27331, 26629, 26805, 26981, 27157, 27333, 26631, 26807, 26983, 27159, 27335, 26633, 26809, 26985, 27161, 27337, 26635, 26811, 26987, 27163, 27339, 26637, 26813, 26989, 27165, 27341, 26639, 26815, 26991, 27167, 27343, 26641, 26817, 26993, 27169, 27345, 26643, 26819, 26995, 27171, 27347, 26645, 26821, 26997, 27173, 27349, 26647, 26823, 26999, 27175, 27351, 26649, 26825, 27001, 27177, 27353, 26651, 26827, 27003, 27179, 27355, 26653, 26829, 27005, 27181, 27357, 26655, 26831, 27007, 27183, 27358, 26657, 26833, 27009, 27185, 27361, 26659, 26835, 27011, 27187, 27363, 26661, 26837, 27013, 27189, 27365, 26663, 26839, 27015, 27191, 27367, 26665, 26841, 27017, 27193, 27369, 26667, 26843, 27019, 27195, 27371 }, [slipIds[19]] = { 27715, 27866, 27716, 27867, 278, 281, 284, 3680, 3681, 27859, 28149, 27860, 28150, 21107, 21108, 27625, 27626, 26693, 26694, 26707, 26708, 27631, 27632, 26705, 26706, 27854, 27855, 26703, 26704, 3682, 3683, 3684, 3685, 3686, 3687, 3688, 3689, 3690, 3691, 3692, 3693, 3694, 3695, 21097, 21098, 26717, 26718, 26728,26719,26720,26889,26890, 21095, 21096, 26738, 26739, 26729, 26730, 26788, 26946, 27281, 27455, 26789 }, [slipIds[20]] = { 26740, 26898, 27052, 27237, 27411, 26742, 26900, 27054, 27239, 27413, 26744, 26902, 27056, 27241, 27415, 26746, 26904, 27058, 27243, 27417, 26748, 26906, 27060, 27245, 27419, 26750, 26908, 27062, 27247, 27421, 26752, 26910, 27064, 27249, 27423, 26754, 26912, 27066, 27251, 27425, 26756, 26914, 27068, 27253, 27427, 26758, 26916, 27070, 27255, 27429, 26760, 26918, 27072, 27257, 27431, 26762, 26920, 27074, 27259, 27433, 26764, 26922, 27076, 27261, 27435, 26766, 26924, 27078, 27263, 27437, 26768, 26926, 27080, 27265, 27439, 26770, 26928, 27082, 27267, 27441, 26772, 26930, 27084, 27269, 27443, 26774, 26932, 27086, 27271, 27445, 26776, 26934, 27088, 27273, 27447, 26778, 26936, 27090, 27275, 27449, 26780, 26938, 27092, 27277, 27451, 26782, 26940, 27094, 27279, 27453 }, [slipIds[21]] = { 26741, 26899, 27053, 27238, 27412, 26743, 26901, 27055, 27240, 27414, 26745, 26903, 27057, 27242, 27416, 26747, 26905, 27059, 27244, 27418, 26749, 26907, 27061, 27246, 27420, 26751, 26909, 27063, 27248, 27422, 26753, 26911, 27065, 27250, 27424, 26755, 26913, 27067, 27252, 27426, 26757, 26915, 27069, 27254, 27428, 26759, 26917, 27071, 27256, 27430, 26761, 26919, 27073, 27258, 27432, 26763, 26921, 27075, 27260, 27434, 26765, 26923, 27077, 27262, 27436, 26767, 26925, 27079, 27264, 27438, 26769, 26927, 27081, 27266, 27440, 26771, 26929, 27083, 27268, 27442, 26773, 26931, 27085, 27270, 27444, 26775, 26933, 27087, 27272, 27446, 26777, 26935, 27089, 27274, 27448, 26779, 26937, 27091, 27276, 27450, 26781, 26939, 27093, 27278, 27452, 26783, 26941, 27095, 27280, 27454 } }; ---------------------------------------------------------------------- -- desc : Checks if the supplied item is a Moogle Storage Slip. ---------------------------------------------------------------------- local function isSlip(itemId) return (slipItems[itemId] ~= nil); end ---------------------------------------------------------------------- -- desc : Checks if the supplied slip can store the supplied item. ---------------------------------------------------------------------- local function isStorableOn(slipId, itemId) for _, id in ipairs(slipItems[slipId]) do if (id == itemId) then return true; end end printf('Item %s is not storable on %s', itemId, slipId); return false; end ---------------------------------------------------------------------- -- desc : Gets IDs of retrievable items from the extra data on a slip. ---------------------------------------------------------------------- local function getItemsOnSlip(extra, slipId) local slip = slipItems[slipId]; local itemsOnSlip = {}; local x = 1; for k,v in ipairs(slip) do local byte = extra[math.floor((k - 1) / 8) + 1]; if byte < 0 then byte = byte + 256; end if (bit.band(bit.rshift(byte, (k - 1) % 8), 1) ~= 0) then itemsOnSlip[x] = v; x = x + 1; end end return itemsOnSlip; end ---------------------------------------------------------------------- -- desc : Finds the key in table t where the value equals i. ---------------------------------------------------------------------- local function find(t, i) for k, v in ipairs(t) do if v == i then return k end end return nil end ---------------------------------------------------------------------- -- desc : Converts the 8 bit extra data into 32 bit params for events. ---------------------------------------------------------------------- local function int8ToInt32(extra) local params = {}; local int32 = ''; for k,v in ipairs(extra) do int32 = string.format('%02x%s', v, int32); if (k % 4 == 0) then params[#params + 1] = tonumber(int32, 16); int32 = ''; end end if (int32 ~= '') then params[#params + 1] = tonumber(int32, 16); end return params; end ---------------------------------------------------------------------- -- desc : Gets Storage Slip ID from the trade window (does nothing -- if there are two or more Storage Slips in the trade and no -- storable items. ---------------------------------------------------------------------- local function getSlipId(trade) local slipId = 0; local slips = 0; for _, itemId in ipairs(slipIds) do if (trade:hasItemQty(itemId, 1)) then slips = slips + 1; if (slipId == 0) then slipId = itemId; end end end if (slips == trade:getItemCount() and slips > 1) then slipId = 0; end return slipId, slips; end ---------------------------------------------------------------------- -- desc : Gets all items in the trade window that are storable on the -- slip in the trade window. ---------------------------------------------------------------------- local function getStorableItems(player, trade, slipId) local storableItemIds = { }; for i = 0, 7 do local slotItemId = trade:getItem(i); if (slotItemId ~= 0 and isSlip(slotItemId) ~= true and player:hasItem(slotItemId)) then if (isStorableOn(slipId, slotItemId)) then storableItemIds[#storableItemIds+1] = slotItemId; end end end return storableItemIds; end ---------------------------------------------------------------------- -- desc : Stores the items on the Storage Slip extra data and starts -- the event indicating that the storage was successful. ---------------------------------------------------------------------- local function storeItems(player, storableItemIds, slipId, e) if (#storableItemIds > 0) then local param0 = 0x0; local param1 = 0x0; if (#storableItemIds == 1) then param0 = storableItemIds[1]; param1 = 0x00; else param0 = #storableItemIds; param1 = 0x01; end -- idk local extra = { }; for i = 0, 23 do extra[i] = 0; end for k, v in ipairs(slipItems[slipId]) do if find(storableItemIds, v) ~= nil then local bitmask = extra[math.floor((k - 1) / 8)]; if bitmask < 0 then bitmask = bitmask + 256; end extra[math.floor((k - 1) / 8)] = bit.bor(bitmask, bit.lshift(1, (k - 1) % 8)); end end local result = player:storeWithPorterMoogle(slipId, extra, storableItemIds); if (result == 0) then player:startEvent(e.STORE_EVENT_ID, param0, param1); elseif (result == 1) then player:startEvent(e.ALREADY_STORED_ID); elseif (result == 2) then player:startEvent(e.MAGIAN_TRIAL_ID); end end end ---------------------------------------------------------------------- -- desc : Returns a zero-based identifier for the slip (Storage Slip 1 -- is index 0, Storage Slip 2 is index 1, etc). ---------------------------------------------------------------------- local function getSlipIndex(slipId) return find(slipIds, slipId) - 1; end ---------------------------------------------------------------------- -- desc : Gets the extra data from the traded slip and starts the -- retrieval event. ---------------------------------------------------------------------- local function startRetrieveProcess(player, eventId, slipId) local extra = player:getRetrievableItemsForSlip(slipId); local params = int8ToInt32(extra); local slipIndex = getSlipIndex(slipId); player:setLocalVar('slipId', slipId); player:startEvent(eventId, params[1], params[2], params[3], params[4], params[5], params[6], nil, slipIndex); end ---------------------------------------------------------------------- -- desc : Begins the storage or retrieval process based on the items -- supplied in the trade. ---------------------------------------------------------------------- function porterMoogleTrade(player, trade, e) local slipId, slipCount = getSlipId(trade); if (slipId == 0 or slipCount > 1) then return; end; local storableItemIds = getStorableItems(player, trade, slipId); if (#storableItemIds > 0) then storeItems(player, storableItemIds, slipId, e); else startRetrieveProcess(player, e.RETRIEVE_EVENT_ID, slipId); end end ---------------------------------------------------------------------- -- desc : Retrieves the selected item from storage, removes it from -- the slip's extra data, displays a message to the user, and -- updates the user's event data. ---------------------------------------------------------------------- function porterEventUpdate(player, csid, option, RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED) local slipId = player:getLocalVar('slipId'); if (csid == RETRIEVE_EVENT_ID and slipId ~= 0 and slipId ~= nil) then local extra = player:getRetrievableItemsForSlip(slipId); local itemsOnSlip = getItemsOnSlip(extra, slipId); local retrievedItemId = itemsOnSlip[option + 1]; if (player:hasItem(retrievedItemId) or player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, retrievedItemId); else local k = find(slipItems[slipId], retrievedItemId); local extraId = math.floor((k - 1) / 8); local bitmask = extra[extraId + 1]; if bitmask < 0 then bitmask = bitmask + 256; end bitmask = bit.band(bitmask, bit.bnot(bit.lshift(1, (k - 1) % 8))); extra[extraId + 1] = bitmask; player:retrieveItemFromSlip(slipId, retrievedItemId, extraId, bitmask); player:messageSpecial(RETRIEVE_DIALOG_ID, retrievedItemId, nil, nil, retrievedItemId, false); end local params = int8ToInt32(extra); player:updateEvent(params[1], params[2], params[3], params[4], params[5], params[6], slipId); end end ---------------------------------------------------------------------- -- desc : Completes the event. ---------------------------------------------------------------------- function porterEventFinish(player, csid, option, TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL) if (csid == TALK_EVENT_ID and option < 1000) then -- This is just because hilarious. option = math.floor(option / 16) + (option % 16); local hasItem = player:hasItem(slipIds[option]); if (hasItem or player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, slipIds[option]); return; end if (player:delGil(1000)) then player:addItem(slipIds[option]); player:messageSpecial(ITEM_OBTAINED, slipIds[option]); else player:messageSpecial(NOT_HAVE_ENOUGH_GIL, slipIds[option]); return; end else player:setLocalVar('slipId', 0); end end
gpl-3.0
kitala1/darkstar
scripts/globals/mobskills/Dread_Dive.lua
25
1043
--------------------------------------------- -- Dread Dive -- -- Description: Dives into a single target. Additional effect: Knockback + Stun -- Type: Physical -- Utsusemi/Blink absorb: 1 shadow -- Range: Melee -- Notes: Used instead of Gliding Spike by certain notorious monsters. --------------------------------------------- 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,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local typeEffect = EFFECT_STUN; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4); target:delHP(dmg); return dmg; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Spire_of_Holla/npcs/_0h1.lua
36
1319
----------------------------------- -- Area: Spire_of_Holla -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Holla/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Holla/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(TradeBCNM(player,player:getZoneID(),trade,npc))then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(EventTriggerBCNM(player,npc))then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if(EventUpdateBCNM(player,csid,option))then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if(EventFinishBCNM(player,csid,option))then return; end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Spire_of_Holla/npcs/_0h3.lua
36
1319
----------------------------------- -- Area: Spire_of_Holla -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Holla/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Holla/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(TradeBCNM(player,player:getZoneID(),trade,npc))then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(EventTriggerBCNM(player,npc))then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if(EventUpdateBCNM(player,csid,option))then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if(EventFinishBCNM(player,csid,option))then return; end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Chateau_dOraguille/npcs/_6h1.lua
17
2271
----------------------------------- -- Area: Chateau d'Oraguille -- Door: Prince Regent's Rm -- Starts and Finishes Quest: Prelude of Black and White (Start), Pieuje's Decision (Start) -- @pos -37 -3 31 233 ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Chateau_dOraguille/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) messengerFromBeyond = player:getQuestStatus(SANDORIA,MESSENGER_FROM_BEYOND); preludeOfBandW = player:getQuestStatus(SANDORIA,PRELUDE_OF_BLACK_AND_WHITE); pieujesDecision = player:getQuestStatus(SANDORIA,PIEUJE_S_DECISION); if(player:getMainJob() == 3 and player:getMainLvl() >= AF2_QUEST_LEVEL) then if(messengerFromBeyond == QUEST_COMPLETED and preludeOfBandW == QUEST_AVAILABLE) then player:startEvent(0x0227); -- Start Quest "Prelude of Black and White" elseif(preludeOfBandW == QUEST_COMPLETED and pieujesDecision == QUEST_AVAILABLE) then player:startEvent(0x0228); -- Start Quest "Pieuje's Decision" end elseif(player:hasCompletedMission(SANDORIA,LIGHTBRINGER) and player:getRank() == 9 and player:getVar("Cutscenes_8-2") == 1) then player:startEvent(0x004A); else player:startEvent(0x020b); 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 == 0x0227) then player:addQuest(SANDORIA,PRELUDE_OF_BLACK_AND_WHITE); elseif(csid == 0x0228) then player:addQuest(SANDORIA,PIEUJE_S_DECISION); elseif(csid == 0x004A) then player:setVar("Cutscenes_8-2",2); end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Den_of_Rancor/npcs/HomePoint#2.lua
12
1193
----------------------------------- -- Area: Den_of_Rancor -- NPC: HomePoint#2 -- @pos 182 34 -62 160 ----------------------------------- package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Den_of_Rancor/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 93); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Dynamis-Beaucedine/mobs/Vanguard_Eye.lua
16
3228
----------------------------------- -- Area: Dynamis Beaucedine -- NPC: Vznguard_Eye -- Map Position: http://images1.wikia.nocookie.net/__cb20090312005233/ffxi/images/thumb/b/b6/Bea.jpg/375px-Bea.jpg ----------------------------------- package.loaded["scripts/zones/Dynamis-Beaucedine/TextIDs"] = nil; ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Beaucedine/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local X = mob:getXPos(); local Y = mob:getYPos(); local Z = mob:getZPos(); local spawnList = beaucedineHydraList; if(mob:getStatPoppedMobs() == false) then mob:setStatPoppedMobs(true); for nb = 1, table.getn(spawnList), 2 do if(mob:getID() == spawnList[nb]) then for nbi = 1, table.getn(spawnList[nb + 1]), 1 do if((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end local mobNBR = spawnList[nb + 1][nbi]; if(mobNBR <= 20) then local DynaMob = getDynaMob(target,mobNBR,5); if(DynaMob ~= nil) then -- Spawn Mob SpawnMob(DynaMob):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetMobByID(DynaMob):setPos(X,Y,Z); GetMobByID(DynaMob):setSpawn(X,Y,Z); -- Spawn Pet for BST, DRG, and SMN if(mobNBR == 9 or mobNBR == 14 or mobNBR == 15) then SpawnMob(DynaMob+1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetMobByID(DynaMob+1):setPos(X,Y,Z); GetMobByID(DynaMob+1):setSpawn(X,Y,Z); end end elseif(mobNBR > 20) then --spawn blm's as eye's are in the hydra's id range GetMobByID(mobNBR):setSpawn(X,Y,Z); SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetMobByID(mobNBR):setPos(X,Y,Z); end end end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- Time Bonus: 120 147 if(mobID == 17326553 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(15); mob:addInBattlefieldList(); elseif(mobID == 17326706 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(15); mob:addInBattlefieldList(); -- 117 spawn 148 when defeated elseif(mobID == 17326721) then SpawnMob(17326553); -- 138 139 140: Spawn 147 when defeated elseif(mobID == 17326661 and GetMobAction(17326668) == 0 and GetMobAction(17326673) == 0 or mobID == 17326668 and GetMobAction(17326661) == 0 and GetMobAction(17326673) == 0 or mobID == 17326673 and GetMobAction(17326661) == 0 and GetMobAction(17326668) == 0) then SpawnMob(17326706); -- 157 spawn 158-162 when defeated elseif(mobID == 17326790) then SpawnMob(17326086); SpawnMob(17326087); SpawnMob(17326088); SpawnMob(17326089); SpawnMob(17326090); end end;
gpl-3.0
kitala1/darkstar
scripts/globals/abilities/wind_maneuver.lua
35
1604
----------------------------------- -- Ability: Wind Maneuver -- Enhances the effect of wind 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"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getWeaponSubSkillType(SLOT_RANGED) == 10 and not player:hasStatusEffect(EFFECT_OVERLOAD)) then return 0,0; else return 71,0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) local burden = 15; if (target:getStat(MOD_AGI) < target:getPet():getStat(MOD_AGI)) then burden = 20; end local overload = target:addBurden(ELE_WIND-1, burden); if (overload ~= 0) then target:removeAllManeuvers(); target:addStatusEffect(EFFECT_OVERLOAD, 0, 0, overload); else local level; if (target:getMainJob() == JOB_PUP) then level = target:getMainLvl() else level = target:getSubLvl() end local bonus = 1 + (level/15) + target:getMod(MOD_MANEUVER_BONUS); if (target:getActiveManeuvers() == 3) then target:removeOldestManeuver(); end target:addStatusEffect(EFFECT_WIND_MANEUVER, bonus, 0, 60); end return EFFECT_WIND_MANEUVER; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Lower_Delkfutts_Tower/npcs/Cermet_Door.lua
17
1160
----------------------------------- -- Area: Lower Delkfutt's Tower -- NPC: Cermet Door -- Notes: Leads to Upper Delkfutt's Tower. -- @pos 524 16 20 184 ----------------------------------- require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0014); -- missing walk-through animation, but it's the best I could find. return 1; end; ----------------------------------- -- onEventUpdate Action ----------------------------------- function onEventUpdate(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); if(csid == 0x0014 and option == 1) then player:setPos(313, 16, 20, 128, 0x9E); -- to Upper Delkfutt's Tower end end;
gpl-3.0
tetoali605/THETETOO_A7A
plugins/redis.lua
5
1102
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY tetoo ▀▄ ▄▀ ▀▄ ▄▀ BY nmore (@l_l_lo) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY l_l_ll ▀▄ ▄▀ ▀▄ ▄▀ broadcast : ريـــدس ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do function run(msg, matches) if matches[1] == "رست" and is_sudo(msg) then return os.execute("./launch.sh"):read('*all') elseif matches[1] == "حدث" and is_sudo(msg) then return io.popen("git pull"):read('*all') elseif matches[1] == "ريديس" and is_sudo(msg) then return io.popen("redis-server"):read('*all') end end return { patterns = { "^(رست)", "^(حدث)", "^(ريديس)" }, run = run } end
gpl-2.0
kitala1/darkstar
scripts/globals/spells/bluemagic/exuviation.lua
9
1850
----------------------------------------- -- Spell: Exuviation -- Restores HP and removes one detrimental magic effect -- Spell cost: 40 MP -- Monster Type: Vermin -- Spell Type: Magical (Fire) -- Blue Magic Points: 4 -- Stat Bonus: HP+5 MP+5 CHR+1 -- Level: 75 -- Casting Time: 3 seconds -- Recast Time: 60 seconds -- -- Combos: Resist Sleep ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local minCure = 60; local effect = target:eraseStatusEffect(); local divisor = 0.6666; local constant = -45; local power = getCurePowerOld(caster); if(power > 459) then divisor = 1.5; constant = 144.6666; elseif(power > 219) then divisor = 2; constant = 65; end local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,true); final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); if(target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then --Applying server mods.... final = final * CURE_POWER; end local diff = (target:getMaxHP() - target:getHP()); if(final > diff) then final = diff; end target:addHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); spell:setMsg(7); return final; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Southern_San_dOria/npcs/Esmallegue.lua
36
1515
----------------------------------- -- Area: Southern San d'Oria -- NPC: Esmallegue -- General Info NPC -- @zone 230 -- @pos 0 2 -83 ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- player:startEvent(0x37e);-- cavernous maw player:startEvent(0x0375) 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
TeamInAura/TeamInAura
trunk/tbc/bin/lua_scripts/masterscript.lua
8
1057
-- -- -- This is the Eluna for MaNGOS MasterScript -- -- print("\n") print("_______________$$$$") print("______________$$$$$$$") print("______________$$$$$$$$_____$_$_$") print("_______________$$$$$$$____$$$$$$") print("________________$$$$$$$____$$$") print("________$__$_$____$$$$$$$$$$$") print("_________$$$$$$___$$$$$$$$$$") print("__________$$$_$$$$$$$$$$$$$$$$") print("___________________$$$$$$$$$$$$") print("___________________$$$$$$$$$$$$") print("__Eluna LuaEngine___$$$$$$$$$$$$$$$$") print("____for_MaNGOS___$$$$$$$$$$$$$$___$$$") print("_________________$$$$___$$$$$______$$$$") print("_________________$$$_____$$$$$____$_$_$") print("_______________$$$$_______$$$$") print("________________$_$_$_____$$$$") print("__________________________$$$$") print("_____________$$$$$$_______$$$$") print("___________$$______$$_____$$$$") print("__________$$$______$$_____$$$") print("___________$$_____$______$$$") print("____________$$__________$$$") print("______________$$$___$$$$$") print("________________$$$$$") print("\n")
gpl-2.0
kitala1/darkstar
scripts/zones/Behemoths_Dominion/npcs/qm1.lua
8
1433
----------------------------------- -- Area: Behemoth's Dominion -- NPC: ??? -- Involved In Quest: The Talekeeper's Gift -- @pos 211 4 -79 127 ----------------------------------- package.loaded["scripts/zones/Behemoths_Dominion/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Behemoths_Dominion/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getVar("theTalekeeperGiftCS") == 3 and player:getVar("theTalekeepersGiftKilledNM") < 3) then player:messageSpecial(SENSE_OF_FOREBODING); SpawnMob(17297446,180):updateClaim(player); SpawnMob(17297447,180):updateClaim(player); SpawnMob(17297448,180):updateClaim(player); 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); end;
gpl-3.0
kitala1/darkstar
scripts/zones/QuBia_Arena/mobs/Rojgnoj_s_Left_Hand.lua
10
1232
----------------------------------- -- Area: QuBia_Arena -- Mission 9-2 SANDO ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/missions"); require("scripts/zones/QuBia_Arena/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("2HGO",math.random(40,80)); end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) if(mob:getLocalVar("2HOUR") == 0)then if(mob:getHPP() < mob:getLocalVar("2HGO"))then mob:setLocalVar("2HOUR",1); mob:useMobAbility(435); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) mob:setLocalVar("2HOUR",0); mob:setLocalVar("2HGO",0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) printf("finishCSID: %u",csid); printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Horlais_Peak/bcnms/contaminated_colosseum.lua
13
1776
----------------------------------- -- Area: Horlias peak -- Name: contaminated_colosseum -- KSNM30 ----------------------------------- package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Horlais_Peak/TextIDs"); ----------------------------------- -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); elseif(leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Northern_San_dOria/npcs/Morjean.lua
21
1691
----------------------------------- -- Area: Northern San d'Oria -- NPC: Morjean -- Involved in Quest: A Squire's Test II (Optional), The Holy Crest -- @pos 99 0 116 231 ------------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TheHolyCrest = player:getVar("TheHolyCrest_Event"); if(TheHolyCrest == 2) then player:startEvent(0x0041); elseif((TheHolyCrest == 3 and player:hasItem(1159)) or TheHolyCrest == 4) then -- Wyvern Egg player:startEvent(0x003e); elseif(player:getQuestStatus(SANDORIA,A_SQUIRE_S_TEST_II) == QUEST_ACCEPTED) then player:startEvent(0x25a); else player:startEvent(0x259); 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 == 0x0041) then player:addQuest(SANDORIA,THE_HOLY_CREST); player:setVar("TheHolyCrest_Event",3); elseif(csid == 0x003e and option == 0) then player:setVar("TheHolyCrest_Event",4); end end;
gpl-3.0
ZenityRTS/Zenity
LuaUI/Widgets/s11n_widget_load.lua
2
1467
---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -- Copy this file to the luaui/widgets folder -- Set this line to the s11n installation folder S11N_FOLDER = "libs/s11n" LCS_FOLDER = "libs/lcs" -- Do NOT modify the following lines function widget:GetInfo() return { name = "s11n widget", desc = "Spring serialization library", author = "gajop", license = "GPLv2", layer = -10000, enabled = true, handler = true, api = true, hidden = true, } end local _s11n function widget:Initialize() LCS = loadstring(VFS.LoadFile(LCS_FOLDER .. "/LCS.lua")) LCS = LCS() VFS.Include(S11N_FOLDER .. "/s11n.lua", nil, VFS.DEF_MODE) -- Export Widget Globals _s11n = s11n() WG.s11n = _s11n for _, objectID in pairs(Spring.GetAllUnits()) do self:UnitCreated(objectID) end for _, objectID in pairs(Spring.GetAllFeatures()) do self:FeatureCreated(objectID) end end function widget:UnitCreated(unitID, unitDefID, unitTeam, builderID) _s11n:GetUnitBridge():_ObjectCreated(unitID) end function widget:FeatureCreated(featureID, allyTeamID) _s11n:GetFeatureBridge():_ObjectCreated(featureID) end function widget:GameFrame() _s11n:GetFeatureBridge():_GameFrame() _s11n:GetUnitBridge():_GameFrame() end
gpl-2.0
Roblox/Core-Scripts
CoreScriptsRoot/Modules/AvatarContextMenu/ContextMenuUtil.lua
1
8122
--[[ // FileName: ContextMenuUtil.lua // Written by: TheGamer101 // Description: Module for utility funcitons of the avatar context menu. ]] --[[ // FileName: ContextMenuGui.lua // Written by: TheGamer101 // Description: Module for creating the context GUI. ]] --- CONSTANTS local STOP_MOVEMENT_ACTION_NAME = "AvatarContextMenuStopInput" local MAX_THUMBNAIL_WAIT_TIME = 2 local MAX_THUMBNAIL_RETRIES = 4 --- SERVICES local CoreGuiService = game:GetService("CoreGui") local PlayersService = game:GetService("Players") local ContextActionService = game:GetService("ContextActionService") local GuiService = game:GetService("GuiService") local UserInputService = game:GetService("UserInputService") --- VARIABLES local RobloxGui = CoreGuiService:WaitForChild("RobloxGui") local LocalPlayer = PlayersService.LocalPlayer while not LocalPlayer do PlayersService.PlayerAdded:wait() LocalPlayer = PlayersService.LocalPlayer end local ContextMenuUtil = {} ContextMenuUtil.__index = ContextMenuUtil -- PUBLIC METHODS function ContextMenuUtil:GetHeadshotForPlayer(player) if self.HeadShotUrlCache[player] ~= nil and self.HeadShotUrlCache[player] ~= "" then return self.HeadShotUrlCache[player] end if self.HeadShotUrlCache[player] == nil then -- Mark that we are getting a headshot for this player. self.HeadShotUrlCache[player] = "" end local startTime = tick() local headshotUrl, isFinal = PlayersService:GetUserThumbnailAsync(player.UserId, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size180x180) if not isFinal then for i = 0, MAX_THUMBNAIL_RETRIES do headshotUrl, isFinal = PlayersService:GetUserThumbnailAsync(player.UserId, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size180x180) if isFinal then break end wait(i ^ 2) end end self.HeadShotUrlCache[player] = headshotUrl return headshotUrl end function ContextMenuUtil:HasOrGettingHeadShot(player) return self.HeadShotUrlCache[player] ~= nil end function ContextMenuUtil:FindPlayerFromPart(part) if part and part.Parent then local possibleCharacter = part while possibleCharacter and not possibleCharacter:IsA("Model") do possibleCharacter = possibleCharacter.Parent end if possibleCharacter then return PlayersService:GetPlayerFromCharacter(possibleCharacter) end end return nil end function ContextMenuUtil:GetPlayerPosition(player) if player.Character then local hrp = player.Character:FindFirstChild("HumanoidRootPart") if hrp then return hrp.Position end end return nil end local playerMovementEnabled = true function ContextMenuUtil:DisablePlayerMovement() if not playerMovementEnabled then return end playerMovementEnabled = false local noOpFunc = function(actionName, actionState) if actionState == Enum.UserInputState.End then return Enum.ContextActionResult.Pass end return Enum.ContextActionResult.Sink end ContextActionService:BindCoreAction(STOP_MOVEMENT_ACTION_NAME, noOpFunc, false, Enum.PlayerActions.CharacterForward, Enum.PlayerActions.CharacterBackward, Enum.PlayerActions.CharacterLeft, Enum.PlayerActions.CharacterRight, Enum.PlayerActions.CharacterJump, Enum.UserInputType.Gamepad1, Enum.UserInputType.Gamepad2, Enum.UserInputType.Gamepad3, Enum.UserInputType.Gamepad4 ) end function ContextMenuUtil:EnablePlayerMovement() if playerMovementEnabled then return end playerMovementEnabled = true ContextActionService:UnbindCoreAction(STOP_MOVEMENT_ACTION_NAME) end function ContextMenuUtil:GetFriendStatus(player) local success, result = pcall(function() -- NOTE: Core script only return LocalPlayer:GetFriendStatus(player) end) if success then return result else return Enum.FriendStatus.NotFriend end end local SelectionOverrideObject = Instance.new("ImageLabel") SelectionOverrideObject.Image = "" SelectionOverrideObject.BackgroundTransparency = 1 local function MakeDefaultButton(name, size, clickFunc) local button = Instance.new("ImageButton") button.Name = name .. "Button" button.Image = "" button.ScaleType = Enum.ScaleType.Slice button.SliceCenter = Rect.new(8,6,46,44) button.AutoButtonColor = false button.BackgroundTransparency = 1 button.Size = size button.ZIndex = 2 button.SelectionImageObject = SelectionOverrideObject button.BorderSizePixel = 0 local underline = Instance.new("Frame") underline.Name = "Underline" underline.BackgroundColor3 = Color3.fromRGB(137,137,137) underline.AnchorPoint = Vector2.new(0.5,1) underline.BorderSizePixel = 0 underline.Position = UDim2.new(0.5,0,1,0) underline.Size = UDim2.new(0.95,0,0,1) underline.Parent = button if clickFunc then button.MouseButton1Click:Connect(function() clickFunc(UserInputService:GetLastInputType()) end) end local function isPointerInput(inputObject) return inputObject.UserInputType == Enum.UserInputType.MouseMovement or inputObject.UserInputType == Enum.UserInputType.Touch end local function selectButton() button.BackgroundTransparency = 0.5 end local function deselectButton() button.BackgroundTransparency = 1 end button.InputBegan:Connect(function(inputObject) if button.Selectable and isPointerInput(inputObject) then selectButton() inputObject:GetPropertyChangedSignal("UserInputState"):connect(function() if inputObject.UserInputState == Enum.UserInputState.End then deselectButton() end end) end end) button.InputEnded:Connect(function(inputObject) if button.Selectable and GuiService.SelectedCoreObject ~= button and isPointerInput(inputObject) then deselectButton() end end) button.SelectionGained:Connect(function() selectButton() end) button.SelectionLost:Connect(function() deselectButton() end) local guiServiceCon = GuiService.Changed:Connect(function(prop) if prop ~= "SelectedCoreObject" then return end if GuiService.SelectedCoreObject == nil or GuiService.SelectedCoreObject ~= button then deselectButton() return end if button.Selectable then selectButton() end end) return button end local function getViewportSize() while not workspace.CurrentCamera do workspace.Changed:wait() end -- ViewportSize is initally set to 1, 1 in Camera.cpp constructor. -- Also check against 0, 0 incase this is changed in the future. while workspace.CurrentCamera.ViewportSize == Vector2.new(0,0) or workspace.CurrentCamera.ViewportSize == Vector2.new(1,1) do workspace.CurrentCamera.Changed:wait() end return workspace.CurrentCamera.ViewportSize end local function isSmallTouchScreen() local viewportSize = getViewportSize() return UserInputService.TouchEnabled and (viewportSize.Y < 500 or viewportSize.X < 700) end function ContextMenuUtil:MakeStyledButton(name, text, size, clickFunc) local button = MakeDefaultButton(name, size, clickFunc) local textLabel = Instance.new("TextLabel") textLabel.Name = name .. "TextLabel" textLabel.BackgroundTransparency = 1 textLabel.BorderSizePixel = 0 textLabel.Size = UDim2.new(1, 0, 1, -8) textLabel.Position = UDim2.new(0,0,0,0) textLabel.TextColor3 = Color3.fromRGB(255,255,255) textLabel.TextYAlignment = Enum.TextYAlignment.Center textLabel.Font = Enum.Font.SourceSansLight textLabel.TextSize = 24 textLabel.Text = text textLabel.TextScaled = true textLabel.TextWrapped = true textLabel.ZIndex = 2 textLabel.Parent = button local constraint = Instance.new("UITextSizeConstraint",textLabel) if isSmallTouchScreen() then textLabel.TextSize = 18 elseif GuiService:IsTenFootInterface() then textLabel.TextSize = 36 end constraint.MaxTextSize = textLabel.TextSize return button, textLabel end function ContextMenuUtil.new() local obj = setmetatable({}, ContextMenuUtil) obj.HeadShotUrlCache = {} return obj end return ContextMenuUtil.new()
apache-2.0
kitala1/darkstar
scripts/zones/South_Gustaberg/npcs/Stone_Monument.lua
32
1291
----------------------------------- -- Area: South Gustaberg -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos 520.064 -5.881 -738.356 107 ----------------------------------- package.loaded["scripts/zones/South_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/zones/South_Gustaberg/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x00040); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/The_Shrouded_Maw/mobs/Diabolos.lua
8
8357
----------------------------------- -- Area: The Shrouded Maw -- MOB: Diabolos ----------------------------------- -- TODO: CoP Diabolos -- 1) Make the diremites in the pit all aggro said player that falls into region. Should have a respawn time of 10 seconds. -- 2) Diremites also shouldnt follow you back to the fight area if you make it there. Should despawn and respawn instantly if all players -- make it back to the Diabolos floor area. -- 3) ANIMATION Packet ids for instance 2 and 3 are wrong (needs guesswork). Sounds working. -- TODO: Diabolos Prime -- Note: Diabolos Prime fight drops all tiles at once. ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local DiabolosID = 16818177; local DiabolosHPP = ((mob:getHP()/mob:getMaxHP())*100); if (mob:getID() == DiabolosID) then local TileOffset = 16818243; if(DiabolosHPP < 10 and GetNPCByID(TileOffset):getAnimation() == 9)then GetNPCByID(TileOffset):setAnimation(8); -- Floor opens SendEntityVisualPacket(TileOffset, "byc1"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 20 and GetNPCByID(TileOffset+1):getAnimation() == 9)then GetNPCByID(TileOffset+1):setAnimation(8); SendEntityVisualPacket(TileOffset+1, "byc2"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+1, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 30 and GetNPCByID(TileOffset+2):getAnimation() == 9)then GetNPCByID(TileOffset+2):setAnimation(8); SendEntityVisualPacket(TileOffset+2, "byc3"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+2, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 40 and GetNPCByID(TileOffset+3):getAnimation() == 9)then GetNPCByID(TileOffset+3):setAnimation(8); SendEntityVisualPacket(TileOffset+3, "byc4"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+3, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 50 and GetNPCByID(TileOffset+4):getAnimation() == 9)then GetNPCByID(TileOffset+4):setAnimation(8); SendEntityVisualPacket(TileOffset+4, "byc5"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+4, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 65 and GetNPCByID(TileOffset+5):getAnimation() == 9)then GetNPCByID(TileOffset+5):setAnimation(8); SendEntityVisualPacket(TileOffset+5, "byc6"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+5, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 75 and GetNPCByID(TileOffset+6):getAnimation() == 9)then GetNPCByID(TileOffset+6):setAnimation(8); SendEntityVisualPacket(TileOffset+6, "byc7"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+6, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 90 and GetNPCByID(TileOffset+7):getAnimation() == 9)then GetNPCByID(TileOffset+7):setAnimation(8); SendEntityVisualPacket(TileOffset+7, "byc8"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+7, "s123"); -- Tile dropping sound end elseif (mob:getID() == DiabolosID+7) then local TileOffset = 16818251; if(DiabolosHPP < 10 and GetNPCByID(TileOffset):getAnimation() == 9)then GetNPCByID(TileOffset):setAnimation(8); SendEntityVisualPacket(TileOffset, "bya1"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 20 and GetNPCByID(TileOffset+1):getAnimation() == 9)then GetNPCByID(TileOffset+1):setAnimation(8); SendEntityVisualPacket(TileOffset+1, "bya2"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+1, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 30 and GetNPCByID(TileOffset+2):getAnimation() == 9)then GetNPCByID(TileOffset+2):setAnimation(8); SendEntityVisualPacket(TileOffset+2, "bya3"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+2, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 40 and GetNPCByID(TileOffset+3):getAnimation() == 9)then GetNPCByID(TileOffset+3):setAnimation(8); SendEntityVisualPacket(TileOffset+3, "bya4"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+3, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 50 and GetNPCByID(TileOffset+4):getAnimation() == 9)then GetNPCByID(TileOffset+4):setAnimation(8); SendEntityVisualPacket(TileOffset+4, "bya5"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+4, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 65 and GetNPCByID(TileOffset+5):getAnimation() == 9)then GetNPCByID(TileOffset+5):setAnimation(8); SendEntityVisualPacket(TileOffset+5, "bya6"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+5, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 75 and GetNPCByID(TileOffset+6):getAnimation() == 9)then GetNPCByID(TileOffset+6):setAnimation(8); SendEntityVisualPacket(TileOffset+6, "bya7"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+6, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 90 and GetNPCByID(TileOffset+7):getAnimation() == 9)then GetNPCByID(TileOffset+7):setAnimation(8); SendEntityVisualPacket(TileOffset+7, "bya8"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+7, "s123"); -- Tile dropping sound end elseif (mob:getID() == DiabolosID+14) then local TileOffset = 16818259; if(DiabolosHPP < 10 and GetNPCByID(TileOffset):getAnimation() == 9)then GetNPCByID(TileOffset):setAnimation(8); SendEntityVisualPacket(TileOffset, "byY1"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 20 and GetNPCByID(TileOffset+1):getAnimation() == 9)then GetNPCByID(TileOffset+1):setAnimation(8); SendEntityVisualPacket(TileOffset+1, "byY2"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+1, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 30 and GetNPCByID(TileOffset+2):getAnimation() == 9)then GetNPCByID(TileOffset+2):setAnimation(8); SendEntityVisualPacket(TileOffset+2, "byY3"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+2, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 40 and GetNPCByID(TileOffset+3):getAnimation() == 9)then GetNPCByID(TileOffset+3):setAnimation(8); SendEntityVisualPacket(TileOffset+3, "byY4"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+3, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 50 and GetNPCByID(TileOffset+4):getAnimation() == 9)then GetNPCByID(TileOffset+4):setAnimation(8); SendEntityVisualPacket(TileOffset+4, "byY5"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+4, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 65 and GetNPCByID(TileOffset+5):getAnimation() == 9)then GetNPCByID(TileOffset+5):setAnimation(8); SendEntityVisualPacket(TileOffset+5, "byY6"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+5, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 75 and GetNPCByID(TileOffset+6):getAnimation() == 9)then GetNPCByID(TileOffset+6):setAnimation(8); SendEntityVisualPacket(TileOffset+6, "byY7"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+6, "s123"); -- Tile dropping sound elseif (DiabolosHPP < 90 and GetNPCByID(TileOffset+7):getAnimation() == 9)then GetNPCByID(TileOffset+7):setAnimation(8); SendEntityVisualPacket(TileOffset+7, "byY8"); -- Animation for floor dropping SendEntityVisualPacket(TileOffset+7, "s123"); -- Tile dropping sound end end end;
gpl-3.0
ZenityRTS/Zenity
lups/ParticleClasses/JitterParticles.lua
2
12346
-- $Id: JitterParticles.lua 3171 2008-11-06 09:06:29Z det $ ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local JitterParticles = {} JitterParticles.__index = JitterParticles local billShader,sizeUniform,frameUniform,timeUniform,movCoeffUniform ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function JitterParticles.GetInfo() return { name = "JitterParticles", backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.) desc = "", layer = 0, --// extreme simply z-ordering :x --// gfx requirement fbo = false, shader = true, distortion= true, rtt = false, ctt = false, } end JitterParticles.Default = { dlist = 0, emitVector = {0,1,0}, pos = {0,0,0}, --// start pos of the effect partpos = "0,0,0", --// particle relative start pos (can contain lua code!) layer = 0, force = {0,0,0}, --// global effect force airdrag = 1, speed = 0, speedSpread = 0, life = 0, lifeSpread = 0, emitRot = 0, emitRotSpread = 0, size = 0, sizeSpread = 0, sizeGrowth = 0, texture = 'bitmaps/GPL/Lups/mynoise.png', count = 1, jitterStrength = 1, repeatEffect = false, --can be a number,too genmipmap = true, --FIXME } ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- --// speed ups local abs = math.abs local sqrt = math.sqrt local rand = math.random local twopi= 2*math.pi local cos = math.cos local sin = math.sin local min = math.min local degreeToPI = math.pi/180 local spGetUnitViewPosition = Spring.GetUnitViewPosition local spGetPositionLosState = Spring.GetPositionLosState local spGetUnitLosState = Spring.GetUnitLosState local spIsSphereInView = Spring.IsSphereInView local spGetUnitRadius = Spring.GetUnitRadius local spGetProjectilePosition = Spring.GetProjectilePosition local glTexture = gl.Texture local glBlending = gl.Blending local glUniform = gl.Uniform local glUniformInt = gl.UniformInt local glPushMatrix = gl.PushMatrix local glPopMatrix = gl.PopMatrix local glTranslate = gl.Translate local glCreateList = gl.CreateList local glCallList = gl.CallList local glRotate = gl.Rotate local glColor = gl.Color local glUseShader = gl.UseShader local GL_QUADS = GL.QUADS local glBeginEnd = gl.BeginEnd local glMultiTexCoord= gl.MultiTexCoord local glVertex = gl.Vertex local ProcessParamCode = ProcessParamCode local ParseParamString = ParseParamString local Vmul = Vmul local Vlength = Vlength ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function JitterParticles:CreateParticleAttributes(up, right, forward,partpos,n) local life, pos, speed, size; local az = rand()*twopi; local ay = (self.emitRot + rand() * self.emitRotSpread) * degreeToPI; local a,b,c = cos(ay), cos(az)*sin(ay), sin(az)*sin(ay) speed = { up[1]*a - right[1]*b + forward[1]*c, up[2]*a - right[2]*b + forward[2]*c, up[3]*a - right[3]*b + forward[3]*c} speed = Vmul( speed, self.speed + rand() * self.speedSpread ) size = self.size + rand()*self.sizeSpread life = self.life + rand()*self.lifeSpread local part = {speed=Vlength(speed),size=size,life=life,i=n} pos = { ProcessParamCode(partpos, part) } return life, size, pos[1],pos[2],pos[3], speed[1],speed[2],speed[3]; end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function JitterParticles:BeginDrawDistortion() glUseShader(billShader) glUniform(timeUniform, Spring.GetGameFrame()*0.01) end function JitterParticles:EndDrawDistortion() glTexture(false) glUseShader(0) end function JitterParticles:DrawDistortion() glTexture(self.texture) glUniform(sizeUniform, self.usize) glUniform(frameUniform, self.frame) glUniform(movCoeffUniform, self.uMovCoeff) local pos = self.pos local force = self.uforce local emit = self.emitVector glPushMatrix() glTranslate(pos[1],pos[2],pos[3]) glTranslate(force[1],force[2],force[3]) glRotate(90,emit[1],emit[2],emit[3]) glCallList(self.dlist) glPopMatrix() end local function DrawParticleForDList(size,life,jitterStrength,x,y,z,dx,dy,dz) glMultiTexCoord(0,x,y,z,life) glMultiTexCoord(1,dx,dy,dz) glVertex(0,0,size,jitterStrength) glVertex(1,0,size,jitterStrength) glVertex(1,1,size,jitterStrength) glVertex(0,1,size,jitterStrength) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function JitterParticles:Initialize() billShader = gl.CreateShader({ vertex = [[ uniform float size; uniform float frame; uniform float time; uniform float movCoeff; varying float distStrength; varying vec4 texCoords; void main() { //gl.MultiTexCoord(0,x,y,z,life) //gl.MultiTexCoord(1,dx,dy,dz) //gl.Vertex(s,t,size) float psize = size+gl_Vertex.z; float life = frame / gl_MultiTexCoord0.w; if (life>1.0 || psize<=0.0) { // paste dead particles offscreen, this way we don't dump the fragment shader with it gl_Position = vec4(-2000.0,-2000.0,-2000.0,-2000.0); }else{ // calc vertex position vec4 pos = vec4( gl_MultiTexCoord0.xyz + movCoeff * gl_MultiTexCoord1.xyz ,1.0); gl_Position = gl_ModelViewMatrix * pos; gl_Position.xy += (gl_Vertex.xy-0.5) * psize; gl_Position = gl_ProjectionMatrix * gl_Position; texCoords.st = gl_Vertex.yz*gl_Vertex.zx*0.2+time; texCoords.t += life+gl_Vertex.z; texCoords.st *= vec2(0.1); distStrength = (1.0 - life) * 0.075 * gl_Vertex.w; texCoords.pq = (gl_Vertex.xy - 0.5) * 2.0; } } ]], fragment = [[ uniform sampler2D noiseMap; varying float distStrength; varying vec4 texCoords; void main() { vec2 noiseVec; vec4 noise = texture2D(noiseMap, texCoords.st); noiseVec = (noise.xy - 0.50) * distStrength; //if (texCoords.z<0.625) { // noiseVec *= texCoords.z * 1.6; //} noiseVec *= smoothstep(1.0, 0.0, dot(texCoords.pq,texCoords.pq) ); gl_FragColor = vec4(noiseVec,0.0,gl_FragCoord.z); } ]], uniform = { noiseMap = 0, size = 0, frame = 0, movCoeff = 0, }, }) if (billShader==nil) then print(PRIO_MAJOR,"LUPS->JitterParticles: Critical Shader Error: " ..gl.GetShaderLog()) return false end sizeUniform = gl.GetUniformLocation(billShader,"size") frameUniform = gl.GetUniformLocation(billShader,"frame") timeUniform = gl.GetUniformLocation(billShader,"time") movCoeffUniform = gl.GetUniformLocation(billShader,"movCoeff") end function JitterParticles:Finalize() gl.DeleteShader(billShader) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function JitterParticles:Update(n) self.frame = self.frame + n if (n==1) then --// in the case of 1 frame we can use much faster equations self.uMovCoeff = self.airdrag^self.frame + self.uMovCoeff; else local rotBoost = 0 for i=1,n do self.uMovCoeff = self.airdrag^(self.frame+i) + self.uMovCoeff; end end self.usize = self.usize + n*self.sizeGrowth local force,frame = self.force,self.frame self.uforce[1],self.uforce[2],self.uforce[3] = force[1]*frame,force[2]*frame,force[3]*frame end -- used if repeatEffect=true; function JitterParticles:ReInitialize() self.frame = 0 self.usize = 0 self.uMovCoeff = 1 self.dieGameFrame = self.dieGameFrame + self.life + self.lifeSpread self.uforce[1],self.uforce[2],self.uforce[3] = 0,0,0 end local function InitializeParticles(self) -- calc base of the emitvector system local up = self.emitVector; local right = Vcross( up, {up[2],up[3],-up[1]} ); local forward = Vcross( up, right ); local partposCode = ParseParamString(self.partpos) self.maxSpawnRadius = 0 for i=1,self.count do local life,size,x,y,z,dx,dy,dz = self:CreateParticleAttributes(up,right,forward, partposCode,i-1) glBeginEnd(GL_QUADS,DrawParticleForDList, size,life, self.jitterStrength, x,y,z, -- relative start pos dx,dy,dz) -- speed vector local spawnDist = x*x + y*y + z*z if (spawnDist>self.maxSpawnRadius) then self.maxSpawnRadius=spawnDist end end self.maxSpawnRadius = sqrt(self.maxSpawnRadius) end function JitterParticles:CreateParticle() self.dlist = glCreateList(InitializeParticles,self) self.frame = 0 self.firstGameFrame = thisGameFrame self.dieGameFrame = self.firstGameFrame + self.life + self.lifeSpread self.usize = 0 self.uMovCoeff = 1 self.uforce = {0,0,0} --// visibility check vars self.radius = self.size + self.sizeSpread + self.maxSpawnRadius + 100 self.maxSpeed = self.speed+ abs(self.speedSpread) self.forceStrength = Vlength(self.force) self.sphereGrowth = self.forceStrength+self.sizeGrowth end function JitterParticles:Destroy() gl.DeleteList(self.dlist) --gl.DeleteTexture(self.texture) end function JitterParticles:Visible() local radius = self.radius + self.uMovCoeff*self.maxSpeed + self.frame*(self.sphereGrowth) --FIXME: frame is only updated on Update() local posX,posY,posZ = self.pos[1],self.pos[2],self.pos[3] local losState if (self.unit and not self.worldspace) then local ux,uy,uz = spGetUnitViewPosition(self.unit) posX,posY,posZ = posX+ux,posY+uy,posZ+uz radius = radius + spGetUnitRadius(self.unit) losState = spGetUnitLosState(self.unit, LocalAllyTeamID) elseif (self.projectile and not self.worldspace) then local px,py,pz = spGetProjectilePosition(self.projectile) posX,posY,posZ = posX+px,posY+py,posZ+pz end if (losState==nil) then if (self.radar) then losState = IsPosInRadar(posX,posY,posZ, LocalAllyTeamID) end if ((not losState) and self.airLos) then losState = IsPosInAirLos(posX,posY,posZ, LocalAllyTeamID) end if ((not losState) and self.los) then losState = IsPosInLos(posX,posY,posZ, LocalAllyTeamID) end end return (losState)and(spIsSphereInView(posX,posY,posZ,radius)) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local MergeTable = MergeTable local setmetatable = setmetatable function JitterParticles.Create(Options) local newObject = MergeTable(Options, JitterParticles.Default) setmetatable(newObject,JitterParticles) --// make handle lookup newObject:CreateParticle() return newObject end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- return JitterParticles
gpl-2.0
TeleDALAD/2DALAD2
plugins/owners.lua
1467
12478
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
kitala1/darkstar
scripts/globals/spells/bluemagic/wild_oats.lua
9
1959
----------------------------------------- -- Spell: Wild Oats -- Additional effect: Vitality Down. Duration of effect varies on TP -- Spell cost: 9 MP -- Monster Type: Plantoids -- Spell Type: Physical (Piercing) -- Blue Magic Points: 3 -- Stat Bonus: CHR+1, HP+10 -- Level: 4 -- Casting Time: 0.5 seconds -- Recast Time: 7.25 seconds -- Skillchain Element(s): Light (can open Compression, Reverberation, or Distortion; can close Transfixion) -- Combos: Beast Killer ----------------------------------------- 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_DURATION; params.dmgtype = DMGTYPE_PIERCE; params.scattr = SC_TRANSFIXION; params.numhits = 1; params.multiplier = 1.84; params.tp150 = 1.84; params.tp300 = 1.84; params.azuretp = 1.84; params.duppercap = 11; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if(target:hasStatusEffect(EFFECT_VIT_DOWN)) then spell:setMsg(75); -- no effect else target:addStatusEffect(EFFECT_VIT_DOWN,15,0,20); end return damage; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Kazham/npcs/Khifo_Ryuhkowa.lua
37
1500
----------------------------------- -- Area: Kazham -- NPC: Khifo Ryuhkowa -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,KHIFORYUHKOWA_SHOP_DIALOG); stock = {0x4059,5713, -- Kukri 0x40D3,153014, -- Ram-Dao 0x41C1,809, -- Bronze Spear 0x41C3,16228, -- Spear 0x41C7,75541, -- Partisan 0x4281,1600, -- Chestnut Club 0x4282,4945, -- Bone Cudgel 0x429C,5255, -- Chestnut Wand 0x42C4,29752, -- Mahogany Staff 0x42CB,99176, -- Mahogany Pole 0x430B,39744, -- Battle Bow 0x439C,55, -- Hawkeye 0x4380,1610, -- Boomerang 0x43A6,3} -- Woden Arrow showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
zhaoluxyz/Hugula
Client/Assets/Lua/core/unity3d.lua
3
3266
------------------------------------------------ -- Copyright © 2013-2014 Hugula: Arpg game Engine -- -- author pu ------------------------------------------------ -- luanet.load_assembly("UnityEngine.UI") import "UnityEngine" delay = PLua.Delay stopDelay = PLua.StopDelay if unpack==nil then unpack=table.unpack end --print =function(...) --end function tojson(tbl,indent) assert(tal==nil) if not indent then indent = 0 end local tab=string.rep(" ",indent) local havetable=false local str="{" local sp="" if tbl then for k, v in pairs(tbl) do if type(v) == "table" then havetable=true if(indenct==0) then str=str..sp.."\r\n "..tostring(k)..":"..tojson(v,indent+1) else str=str..sp.."\r\n"..tab..tostring(k)..":"..tojson(v,indent+1) end else str=str..sp..tostring(k)..":"..tostring(v) end sp=";" end end if(havetable) then str=str.."\r\n"..tab.."}" else str=str.."}" end return str end function getAngle(posFrom,posTo) local tmpx=posTo.x - posFrom.x local tmpy=posTo.y - posFrom.y local angle= math.atan2(tmpy,tmpx)*(180/math.pi) return angle end function printTable(tbl) print(tojson(tbl)) end function string:split(s, delimiter) result = {}; for match in (s..delimiter):gmatch("(.-)"..delimiter) do table.insert(result, match) end return result end function split(s, delimiter) result = {}; for match in (s..delimiter):gmatch("(.-)"..delimiter) do table.insert(result, match) end return result end function class(base, _ctor) local c = {} -- a new class instance if not _ctor and type(base) == 'function' then _ctor = base base = nil elseif type(base) == 'table' then -- our new class is a shallow copy of the base class! for i,v in pairs(base) do c[i] = v end c._base = base end -- the class will be the metatable for all its objects, -- and they will look up their methods in it. c.__index = c -- expose a constructor which can be called by <classname>(<args>) local mt = {} mt.__call = function(class_tbl, ...) local obj = {} setmetatable(obj,c) if _ctor then _ctor(obj,...) end return obj end c._ctor = _ctor c.is_a = function(self, klass) local m = getmetatable(self) while m do if m == klass then return true end m = m._base end return false end setmetatable(c, mt) return c end function luaGC() -- local c=collectgarbage("count") -- print("begin gc ="..tostring(c).." ") collectgarbage("collect") c=collectgarbage("count") print(" gc end ="..tostring(c).." ") end function make_array (tp,tbl) local arr = tp[#tbl] for i,v in ipairs(tbl) do arr:SetValue(v,i-1) end return arr end --value type -- require("core.Math") -- require("core.Vector3") -- require("core.Vector2") -- require("core.Quaternion") -- require("core.Vector4") -- require("core.Raycast") -- require("core.Color") -- require("core.Touch") -- require("core.Ray")
mit
fastmailops/prosody
plugins/mod_s2s/s2sout.lib.lua
1
12224
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- --- Module containing all the logic for connecting to a remote server local portmanager = require "core.portmanager"; local wrapclient = require "net.server".wrapclient; local initialize_filters = require "util.filters".initialize; local idna_to_ascii = require "util.encodings".idna.to_ascii; local new_ip = require "util.ip".new_ip; local rfc6724_dest = require "util.rfc6724".destination; local socket = require "socket"; local adns = require "net.adns"; local dns = require "net.dns"; local t_insert, t_sort, ipairs = table.insert, table.sort, ipairs; local local_addresses = require "util.net".local_addresses; local s2s_destroy_session = require "core.s2smanager".destroy_session; local log = module._log; local sources = {}; local has_ipv4, has_ipv6; local dns_timeout = module:get_option_number("dns_timeout", 15); dns.settimeout(dns_timeout); local max_dns_depth = module:get_option_number("dns_max_depth", 3); local s2sout = {}; local s2s_listener; function s2sout.set_listener(listener) s2s_listener = listener; end local function compare_srv_priorities(a,b) return a.priority < b.priority or (a.priority == b.priority and a.weight > b.weight); end function s2sout.initiate_connection(host_session) initialize_filters(host_session); host_session.version = 1; -- Kick the connection attempting machine into life if not s2sout.attempt_connection(host_session) then -- Intentionally not returning here, the -- session is needed, connected or not s2s_destroy_session(host_session); end if not host_session.sends2s then -- A sends2s which buffers data (until the stream is opened) -- note that data in this buffer will be sent before the stream is authed -- and will not be ack'd in any way, successful or otherwise local buffer; function host_session.sends2s(data) if not buffer then buffer = {}; host_session.send_buffer = buffer; end log("debug", "Buffering data on unconnected s2sout to %s", tostring(host_session.to_host)); buffer[#buffer+1] = data; log("debug", "Buffered item %d: %s", #buffer, tostring(data)); end end end function s2sout.attempt_connection(host_session, err) local to_host = host_session.to_host; local connect_host, connect_port = to_host and idna_to_ascii(to_host), 5269; if not connect_host then return false; end if not err then -- This is our first attempt log("debug", "First attempt to connect to %s, starting with SRV lookup...", to_host); host_session.connecting = true; local handle; handle = adns.lookup(function (answer) handle = nil; host_session.connecting = nil; if answer and #answer > 0 then log("debug", "%s has SRV records, handling...", to_host); local srv_hosts = { answer = answer }; host_session.srv_hosts = srv_hosts; for _, record in ipairs(answer) do t_insert(srv_hosts, record.srv); end if #srv_hosts == 1 and srv_hosts[1].target == "." then log("debug", "%s does not provide a XMPP service", to_host); s2s_destroy_session(host_session, err); -- Nothing to see here return; end t_sort(srv_hosts, compare_srv_priorities); local srv_choice = srv_hosts[1]; host_session.srv_choice = 1; if srv_choice then connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port; log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port); end else log("debug", "%s has no SRV records, falling back to A/AAAA", to_host); end -- Try with SRV, or just the plain hostname if no SRV local ok, err = s2sout.try_connect(host_session, connect_host, connect_port); if not ok then if not s2sout.attempt_connection(host_session, err) then -- No more attempts will be made s2s_destroy_session(host_session, err); end end end, "_xmpp-server._tcp."..connect_host..".", "SRV"); return true; -- Attempt in progress elseif host_session.ip_hosts then return s2sout.try_connect(host_session, connect_host, connect_port, err); elseif host_session.srv_hosts and #host_session.srv_hosts > host_session.srv_choice then -- Not our first attempt, and we also have SRV host_session.srv_choice = host_session.srv_choice + 1; local srv_choice = host_session.srv_hosts[host_session.srv_choice]; connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port; host_session.log("info", "Connection failed (%s). Attempt #%d: This time to %s:%d", tostring(err), host_session.srv_choice, connect_host, connect_port); else host_session.log("info", "Out of connection options, can't connect to %s", tostring(host_session.to_host)); -- We're out of options return false; end if not (connect_host and connect_port) then -- Likely we couldn't resolve DNS log("warn", "Hmm, we're without a host (%s) and port (%s) to connect to for %s, giving up :(", tostring(connect_host), tostring(connect_port), tostring(to_host)); return false; end return s2sout.try_connect(host_session, connect_host, connect_port); end function s2sout.try_next_ip(host_session) host_session.connecting = nil; host_session.ip_choice = host_session.ip_choice + 1; local ip = host_session.ip_hosts[host_session.ip_choice]; local ok, err= s2sout.make_connect(host_session, ip.ip, ip.port); if not ok then if not s2sout.attempt_connection(host_session, err or "closed") then err = err and (": "..err) or ""; s2s_destroy_session(host_session, "Connection failed"..err); end end end function s2sout.try_connect(host_session, connect_host, connect_port, err) host_session.connecting = true; if not err then local IPs = {}; host_session.ip_hosts = IPs; local handle4, handle6; local have_other_result = not(has_ipv4) or not(has_ipv6) or false; if has_ipv4 then handle4 = adns.lookup(function (reply, err) handle4 = nil; -- COMPAT: This is a compromise for all you CNAME-(ab)users :) if not (reply and reply[#reply] and reply[#reply].a) then local count = max_dns_depth; reply = dns.peek(connect_host, "CNAME", "IN"); while count > 0 and reply and reply[#reply] and not reply[#reply].a and reply[#reply].cname do log("debug", "Looking up %s (DNS depth is %d)", tostring(reply[#reply].cname), count); reply = dns.peek(reply[#reply].cname, "A", "IN") or dns.peek(reply[#reply].cname, "CNAME", "IN"); count = count - 1; end end -- end of CNAME resolving if reply and reply[#reply] and reply[#reply].a then for _, ip in ipairs(reply) do log("debug", "DNS reply for %s gives us %s", connect_host, ip.a); IPs[#IPs+1] = new_ip(ip.a, "IPv4"); end end if have_other_result then if #IPs > 0 then rfc6724_dest(host_session.ip_hosts, sources); for i = 1, #IPs do IPs[i] = {ip = IPs[i], port = connect_port}; end host_session.ip_choice = 0; s2sout.try_next_ip(host_session); else log("debug", "DNS lookup failed to get a response for %s", connect_host); host_session.ip_hosts = nil; if not s2sout.attempt_connection(host_session, "name resolution failed") then -- Retry if we can log("debug", "No other records to try for %s - destroying", host_session.to_host); err = err and (": "..err) or ""; s2s_destroy_session(host_session, "DNS resolution failed"..err); -- End of the line, we can't end end else have_other_result = true; end end, connect_host, "A", "IN"); else have_other_result = true; end if has_ipv6 then handle6 = adns.lookup(function (reply, err) handle6 = nil; if reply and reply[#reply] and reply[#reply].aaaa then for _, ip in ipairs(reply) do log("debug", "DNS reply for %s gives us %s", connect_host, ip.aaaa); IPs[#IPs+1] = new_ip(ip.aaaa, "IPv6"); end end if have_other_result then if #IPs > 0 then rfc6724_dest(host_session.ip_hosts, sources); for i = 1, #IPs do IPs[i] = {ip = IPs[i], port = connect_port}; end host_session.ip_choice = 0; s2sout.try_next_ip(host_session); else log("debug", "DNS lookup failed to get a response for %s", connect_host); host_session.ip_hosts = nil; if not s2sout.attempt_connection(host_session, "name resolution failed") then -- Retry if we can log("debug", "No other records to try for %s - destroying", host_session.to_host); err = err and (": "..err) or ""; s2s_destroy_session(host_session, "DNS resolution failed"..err); -- End of the line, we can't end end else have_other_result = true; end end, connect_host, "AAAA", "IN"); else have_other_result = true; end return true; elseif host_session.ip_hosts and #host_session.ip_hosts > host_session.ip_choice then -- Not our first attempt, and we also have IPs left to try s2sout.try_next_ip(host_session); else host_session.ip_hosts = nil; if not s2sout.attempt_connection(host_session, "out of IP addresses") then -- Retry if we can log("debug", "No other records to try for %s - destroying", host_session.to_host); err = err and (": "..err) or ""; s2s_destroy_session(host_session, "Connecting failed"..err); -- End of the line, we can't return false; end end return true; end function s2sout.make_connect(host_session, connect_host, connect_port) (host_session.log or log)("info", "Beginning new connection attempt to %s ([%s]:%d)", host_session.to_host, connect_host.addr, connect_port); -- Reset secure flag in case this is another -- connection attempt after a failed STARTTLS host_session.secure = nil; local conn, handler; local proto = connect_host.proto; if proto == "IPv4" then conn, handler = socket.tcp(); elseif proto == "IPv6" and socket.tcp6 then conn, handler = socket.tcp6(); else handler = "Unsupported protocol: "..tostring(proto); end if not conn then log("warn", "Failed to create outgoing connection, system error: %s", handler); return false, handler; end conn:settimeout(0); local success, err = conn:connect(connect_host.addr, connect_port); if not success and err ~= "timeout" then log("warn", "s2s connect() to %s (%s:%d) failed: %s", host_session.to_host, connect_host.addr, connect_port, err); return false, err; end conn = wrapclient(conn, connect_host.addr, connect_port, s2s_listener, "*a"); host_session.conn = conn; local filter = initialize_filters(host_session); local w, log = conn.write, host_session.log; host_session.sends2s = function (t) log("debug", "sending: %s", (t.top_tag and t:top_tag()) or t:match("^[^>]*>?")); if t.name then t = filter("stanzas/out", t); end if t then t = filter("bytes/out", tostring(t)); if t then return w(conn, tostring(t)); end end end -- Register this outgoing connection so that xmppserver_listener knows about it -- otherwise it will assume it is a new incoming connection s2s_listener.register_outgoing(conn, host_session); log("debug", "Connection attempt in progress..."); return true; end module:hook_global("service-added", function (event) if event.name ~= "s2s" then return end local s2s_sources = portmanager.get_active_services():get("s2s"); if not s2s_sources then module:log("warn", "s2s not listening on any ports, outgoing connections may fail"); return; end for source, _ in pairs(s2s_sources) do if source == "*" or source == "0.0.0.0" then for _, addr in ipairs(local_addresses("ipv4", true)) do sources[#sources + 1] = new_ip(addr, "IPv4"); end elseif source == "::" then for _, addr in ipairs(local_addresses("ipv6", true)) do sources[#sources + 1] = new_ip(addr, "IPv6"); end else sources[#sources + 1] = new_ip(source, (source:find(":") and "IPv6") or "IPv4"); end end for i = 1,#sources do if sources[i].proto == "IPv6" then has_ipv6 = true; elseif sources[i].proto == "IPv4" then has_ipv4 = true; end end end); return s2sout;
mit
Pulse-Eight/drivers
Control4/cec_source_pulse-eight/common/c4_notify.lua
9
1689
--[[============================================================================= Notification Functions Copyright 2015 Control4 Corporation. All Rights Reserved. ===============================================================================]] require "common.p8declares" --[[============================================================================= SendNotify(notifyText, tParams, bindingID) Description Forwards a notification to the proxy with a list of parameters Parameters notifyText(string) - The function identifier for the proxy tParams(table) - Table of key value pairs that hold the the parameters and their values used in the proxy function bindingID(int) - The requests binding id Returns Nothing ===============================================================================]] function SendNotify(notifyText, tParams, bindingID) C4:SendToProxy(bindingID, notifyText, tParams, "NOTIFY") end --[[============================================================================= SendSimpleNotify(notifyText, ...) Description Forwards a notification to the proxy with no parameters Parameters notifyText(string) - The function identifier for the proxy bindingID(int) - Optional parameter containing the requests binding id, if not specified then the DEFAULT_PROXY_ID is given. Returns Nothing ===============================================================================]] function SendSimpleNotify(notifyText, ...) bindingID = select(1, ...) or DEFAULT_PROXY_BINDINGID C4:SendToProxy(bindingID, notifyText, {}, "NOTIFY") end
apache-2.0
kitala1/darkstar
scripts/zones/Phomiuna_Aqueducts/npcs/_0rn.lua
17
1624
----------------------------------- -- Area: Phomiuna_Aqueducts -- NPC: _0rn (Oil lamp) -- @pos -60 -23 60 27 ----------------------------------- package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Phomiuna_Aqueducts/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorOffset = npc:getID(); player:messageSpecial(LAMP_OFFSET+2); -- water lamp npc:openDoor(7); -- lamp animation local element = VanadielDayElement(); --printf("element: %u",element); if(element == 2)then -- waterday if(GetNPCByID(DoorOffset+7):getAnimation() == 8)then -- lamp fire open? GetNPCByID(DoorOffset-2):openDoor(15); -- Open Door _0rk end elseif(element == 5)then -- lighningday if(GetNPCByID(DoorOffset+2):getAnimation() == 8)then -- lamp lightning open? GetNPCByID(DoorOffset-2):openDoor(15); -- Open Door _0rk end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
NiFiLocal/nifi-minifi-cpp
thirdparty/civetweb-1.10/test/page4.lua
9
6832
-- This test checks the Lua functions: -- get_var, get_cookie, md5, url_encode now = os.time() cookie_name = "civetweb-test-page4" if mg.request_info.http_headers.Cookie then cookie_value = tonumber(mg.get_cookie(mg.request_info.http_headers.Cookie, cookie_name)) end mg.write("HTTP/1.0 200 OK\r\n") mg.write("Connection: close\r\n") mg.write("Content-Type: text/html; charset=utf-8\r\n") mg.write("Cache-Control: max-age=0, must-revalidate\r\n") if not cookie_value then mg.write("Set-Cookie: " .. cookie_name .. "=" .. tostring(now) .. "\r\n") end mg.write("\r\n") mg.write("<html>\r\n<head><title>Civetweb Lua script test page 4</title></head>\r\n<body>\r\n") mg.write("<p>Test of Civetweb Lua Functions:</p>\r\n"); mg.write("<pre>\r\n"); -- get_var of query_string mg.write("get_var test (check query string):\r\n") if not mg.request_info.query_string then mg.write(" No query string. You may try <a href='?a=a1&amp;junk&amp;b=b2&amp;cc=cNotSet&amp;d=a, b and d should be set&amp;z=z'>this example</a>.\r\n") else for _,var in ipairs({'a','b','c','d'}) do value = mg.get_var(mg.request_info.query_string, var); if value then mg.write(" Variable " .. var .. ": value " .. value .. "\r\n"); else mg.write(" Variable " .. var .. " not set\r\n"); end end end mg.write("\r\n") -- md5 mg.write("MD5 test:\r\n") test_string = "abcd\0efgh" mg.write(" String with embedded 0, length " .. string.len(test_string)) test_md5 = mg.md5(test_string) mg.write(", MD5 " .. test_md5 .. "\r\n") if mg.md5("") == "d41d8cd98f00b204e9800998ecf8427e" then mg.write(" MD5 of empty string OK\r\n") else mg.write(" Error: MD5 of empty string NOT OK\r\n") end if mg.md5("The quick brown fox jumps over the lazy dog.") == "e4d909c290d0fb1ca068ffaddf22cbd0" then mg.write(" MD5 of test string OK\r\n") else mg.write(" Error: MD5 of test string NOT OK\r\n") end mg.write("\r\n") -- get_cookie mg.write("Cookie test:\r\n") if not cookie_value then mg.write(" Cookie not set yet. Please reload the page.\r\n") else mg.write(" Cookie set to " .. cookie_value .. "\r\n") mg.write(" You visited this page " .. os.difftime(now, cookie_value) .. " seconds before.\r\n") end mg.write("\r\n") -- test 'require' of other Lua scripts mg.write("require test\r\n") script_path = mg.script_name:match("(.*)page%d*.lua") if type(script_path)=='string' then package.path = script_path .. "?.lua;" .. package.path mg.write(" Lua search path: " .. package.path .. "\r\n") require "html_esc" require "require_test" if htmlEscape then for i=0,15 do mg.write(" ") for j=0,15 do mg.write(tostring(htmlEscape[16*i+j])) end mg.write("\r\n") end else mg.write(" 'require' test failed (htmlEscape)\r\n") end if HugeText then mg.write("\r\n") local ht = HugeText(os.date("%a %b. %d")) for i=1,#ht do mg.write(" " .. ht[i] .. "\r\n") end else mg.write(" 'require' test failed (HugeText)\r\n") end else mg.write(" name match failed\r\n") end mg.write("\r\n") -- test get_response_code_text mg.write("HTTP helper methods test:\r\n") if (htmlEscape("<a b & c d>") == "&lt;a b &amp; c d&gt;") then mg.write(" htmlEscape test OK\r\n") else mg.write(" Error: htmlEscape test NOT OK\r\n") end if (mg.get_response_code_text(200) == "OK") then mg.write(" get_response_code_text test OK\r\n") else mg.write(" Error: get_response_code_text test NOT OK\r\n") end mg.write("\r\n") -- url_encode mg.write("URL encode/decode test:\r\n") if mg.url_encode("") == "" then mg.write(" url_encode of empty string OK\r\n") else mg.write(" Error: url_encode of empty string NOT OK\r\n") end raw_string = [[ !"#$%&'()*+,-./0123456789:;<=>?@]] mg.write(" original string: " .. htmlEscape(raw_string) .. "\r\n") mg_string = mg.url_encode(raw_string):upper() ref_string = "%20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40" -- from http://www.w3schools.com/tags/ref_urlencode.asp mg.write(" mg-url: " .. htmlEscape(mg_string) .. "\r\n") mg.write(" reference url: " .. htmlEscape(ref_string) .. "\r\n") dec_mg_string = mg.url_decode(mg_string) dec_ref_string = mg.url_decode(ref_string) mg.write(" decoded mg-url: " .. htmlEscape(dec_mg_string) .. "\r\n") mg.write(" decoded reference url: " .. htmlEscape(dec_ref_string) .. "\r\n") dec_mg_string = mg.url_decode(mg_string, false) dec_ref_string = mg.url_decode(ref_string, false) mg.write(" decoded mg-url: " .. htmlEscape(dec_mg_string) .. "\r\n") mg.write(" decoded reference url: " .. htmlEscape(dec_ref_string) .. "\r\n") dec_mg_string = mg.url_decode(mg_string, true) dec_ref_string = mg.url_decode(ref_string, true) mg.write(" decoded mg-url: " .. htmlEscape(dec_mg_string) .. "\r\n") mg.write(" decoded reference url: " .. htmlEscape(dec_ref_string) .. "\r\n") mg.write("\r\n") -- base64_encode mg.write("BASE64 encode/decode test:\r\n") raw_string = [[ !"#$%&'()*+,-./0123456789:;<=>?@]] mg.write(" original string: " .. htmlEscape(raw_string) .. "\r\n") mg_string = mg.base64_encode(raw_string) ref_string = "ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9A" -- from http://www.base64encode.org/ mg.write(" mg-base64: " .. htmlEscape(mg_string) .. "\r\n") mg.write(" reference base64: " .. htmlEscape(ref_string) .. "\r\n") dec_mg_string = mg.base64_decode(mg_string) dec_ref_string = mg.base64_decode(ref_string) mg.write(" decoded mg-base64: " .. htmlEscape(dec_mg_string) .. "\r\n") mg.write(" decoded reference base64: " .. htmlEscape(dec_ref_string) .. "\r\n") mg.write("\r\n") raw_string = [[<?> -?-]] mg.write(" original string: " .. htmlEscape(raw_string) .. "\r\n") mg_string = mg.base64_encode(raw_string) ref_string = "PD8+IC0/LQ==" -- from http://www.base64encode.org/ mg.write(" mg-base64: " .. htmlEscape(mg_string) .. "\r\n") mg.write(" reference base64: " .. htmlEscape(ref_string) .. "\r\n") dec_mg_string = mg.base64_decode(mg_string) dec_ref_string = mg.base64_decode(ref_string) mg.write(" decoded mg-base64: " .. htmlEscape(dec_mg_string) .. "\r\n") mg.write(" decoded reference base64: " .. htmlEscape(dec_ref_string) .. "\r\n") mg.write("\r\n") -- random mg.write("Random numbers:\r\n") for i=1,10 do mg.write(string.format("%18u\r\n", mg.random())) end mg.write("\r\n") -- uuid if mg.uuid then mg.write("UUIDs:\r\n") for i=1,10 do mg.write(string.format("%40s\r\n", mg.uuid())) end mg.write("\r\n") end -- end of page mg.write("</pre>\r\n</body>\r\n</html>\r\n")
apache-2.0
crabman77/minetest-minetestforfun-server
mods/snow/src/aliases.lua
9
6741
-- Some aliases for compatibility switches and some to make "/give" commands -- a little easier minetest.register_alias("snow:needles", "default:pine_needles") minetest.register_alias("snow:snow", "default:snow") minetest.register_alias("default_snow", "default:snow") minetest.register_alias("snow:snowball", "default:snow") minetest.register_alias("snowball", "default:snow") minetest.register_alias("snowballs", "default:snow") minetest.register_alias("snow_ball", "default:snow") minetest.register_alias("snow:ice", "default:ice") minetest.register_alias("ice", "default:ice") minetest.register_alias("default_ice", "default:ice") minetest.register_alias("snow:dirt_with_snow", "default:dirt_with_snow") minetest.register_alias("dirtwithsnow", "default:dirt_with_snow") minetest.register_alias("snowdirt", "default:dirt_with_snow") minetest.register_alias("snowydirt", "default:dirt_with_snow") minetest.register_alias("snow:snow_block", "default:snowblock") minetest.register_alias("default:snow_block", "default:snowblock") minetest.register_alias("snowblocks", "default:snowblock") minetest.register_alias("snowbrick", "snow:snow_brick") minetest.register_alias("bricksnow", "snow:snow_brick") minetest.register_alias("snowbricks", "snow:snow_brick") minetest.register_alias("snowybricks", "snow:snow_brick") minetest.register_alias("icysnow", "snow:snow_cobble") minetest.register_alias("snowcobble", "snow:snow_cobble") minetest.register_alias("snowycobble", "snow:snow_cobble") minetest.register_alias("cobblesnow", "snow:snow_cobble") minetest.register_alias("snow:leaves", "default:pine_needles") minetest.register_alias("snow:sapling_pine", "default:pine_sapling") -- To clean up my first stairsplus attempt. -- Stair minetest.register_alias(":default:stair_snowblock", "moreblocks:stair_snowblock") minetest.register_alias(":default:stair_snowblock_half", "moreblocks:stair_snowblock_half") minetest.register_alias(":default:stair_snowblock_right_half", "moreblocks:stair_snowblock_right_half") minetest.register_alias(":default:stair_snowblock_inner", "moreblocks:stair_snowblock_inner") minetest.register_alias(":default:stair_snowblock_outer", "moreblocks:stair_snowblock_outer") minetest.register_alias(":default:stair_snowblock_alt", "moreblocks:stair_snowblock_alt") minetest.register_alias(":default:stair_snowblock_alt_1", "moreblocks:stair_snowblock_alt_1") minetest.register_alias(":default:stair_snowblock_alt_2", "moreblocks:stair_snowblock_2") minetest.register_alias(":default:stair_snowblock_alt_4", "moreblocks:stair_snowblock_alt_4") minetest.register_alias(":default:stair_ice", "moreblocks:stair_ice") minetest.register_alias(":default:stair_ice_half", "moreblocks:stair_ice_half") minetest.register_alias(":default:stair_ice_right_half", "moreblocks:stair_ice_right_half") minetest.register_alias(":default:stair_ice_inner", "moreblocks:stair_ice_inner") minetest.register_alias(":default:stair_ice_outer", "moreblocks:stair_ice_outer") minetest.register_alias(":default:stair_ice_alt", "moreblocks:stair_ice_alt") minetest.register_alias(":default:stair_ice_alt_1", "moreblocks:stair_ice_alt_1") minetest.register_alias(":default:stair_ice_alt_2", "moreblocks:stair_ice_2") minetest.register_alias(":default:stair_ice_alt_4", "moreblocks:stair_ice_alt_4") -- Slab minetest.register_alias(":default:slab_snowblock", "moreblocks:slab_snowblock") minetest.register_alias(":default:slab_snowblock_quarter", "moreblocks:slab_snowblock_quarter") minetest.register_alias(":default:slab_snowblock_three_quarter", "moreblocks:slab_snowblock_three_quarter") minetest.register_alias(":default:slab_snowblock_1", "moreblocks:slab_snowblock_1") minetest.register_alias(":default:slab_snowblock_2", "moreblocks:slab_snowblock_2") minetest.register_alias(":default:slab_snowblock_14", "moreblocks:slab_snowblock_14") minetest.register_alias(":default:slab_snowblock_15", "moreblocks:slab_snowblock_15") minetest.register_alias(":default:slab_ice", "moreblocks:slab_ice") minetest.register_alias(":default:slab_ice_quarter", "moreblocks:slab_ice_quarter") minetest.register_alias(":default:slab_ice_three_quarter", "moreblocks:slab_ice_three_quarter") minetest.register_alias(":default:slab_ice_1", "moreblocks:slab_ice_1") minetest.register_alias(":default:slab_ice_2", "moreblocks:slab_ice_2") minetest.register_alias(":default:slab_ice_14", "moreblocks:slab_ice_14") minetest.register_alias(":default:slab_ice_15", "moreblocks:slab_ice_15") -- Panel minetest.register_alias(":default:panel_snowblock", "moreblocks:panel_snowblock") minetest.register_alias(":default:panel_snowblock_1", "moreblocks:panel_snowblock_1") minetest.register_alias(":default:panel_snowblock_2", "moreblocks:panel_snowblock_2") minetest.register_alias(":default:panel_snowblock_4", "moreblocks:panel_snowblock_4") minetest.register_alias(":default:panel_snowblock_12", "moreblocks:panel_snowblock_12") minetest.register_alias(":default:panel_snowblock_14", "moreblocks:panel_snowblock_14") minetest.register_alias(":default:panel_snowblock_15", "moreblocks:panel_snowblock_15") minetest.register_alias(":default:panel_ice", "moreblocks:panel_ice") minetest.register_alias(":default:panel_ice_1", "moreblocks:panel_ice_1") minetest.register_alias(":default:panel_ice_2", "moreblocks:panel_ice_2") minetest.register_alias(":default:panel_ice_4", "moreblocks:panel_ice_4") minetest.register_alias(":default:panel_ice_12", "moreblocks:panel_ice_12") minetest.register_alias(":default:panel_ice_14", "moreblocks:panel_ice_14") minetest.register_alias(":default:panel_ice_15", "moreblocks:panel_ice_15") -- Micro minetest.register_alias(":default:micro_snowblock", "moreblocks:micro_snowblock") minetest.register_alias(":default:micro_snowblock_1", "moreblocks:micro_snowblock_1") minetest.register_alias(":default:micro_snowblock_2", "moreblocks:micro_snowblock_2") minetest.register_alias(":default:micro_snowblock_4", "moreblocks:micro_snowblock_4") minetest.register_alias(":default:micro_snowblock_12", "moreblocks:micro_snowblock_12") minetest.register_alias(":default:micro_snowblock_14", "moreblocks:micro_snowblock_14") minetest.register_alias(":default:micro_snowblock_15", "moreblocks:micro_snowblock_15") minetest.register_alias(":default:micro_ice", "moreblocks:micro_ice") minetest.register_alias(":default:micro_ice_1", "moreblocks:micro_ice_1") minetest.register_alias(":default:micro_ice_2", "moreblocks:micro_ice_2") minetest.register_alias(":default:micro_ice_4", "moreblocks:micro_ice_4") minetest.register_alias(":default:micro_ice_12", "moreblocks:micro_ice_12") minetest.register_alias(":default:micro_ice_14", "moreblocks:micro_ice_14") minetest.register_alias(":default:micro_ice_15", "moreblocks:micro_ice_15")
unlicense
Roblox/Core-Scripts
PlayerScripts/StarterPlayerScripts_NewStructure/RobloxPlayerScript/ControlScript/VehicleController.lua
1
3759
--[[ // FileName: VehicleControl // Version 1.0 // Written by: jmargh // Description: Implements in-game vehicle controls for all input devices // NOTE: This works for basic vehicles (single vehicle seat). If you use custom VehicleSeat code, // multiple VehicleSeats or your own implementation of a VehicleSeat this will not work. --]] local ContextActionService = game:GetService("ContextActionService") local Players = game:GetService("Players") local RunService = game:GetService("RunService") --[[ Constants ]]-- -- Set this to true if you want to instead use the triggers for the throttle local useTriggersForThrottle = true -- Also set this to true if you want the thumbstick to not affect throttle, only triggers when a gamepad is conected local onlyTriggersForThrottle = false local ZERO_VECTOR3 = Vector3.new(0,0,0) -- Note that VehicleController does not derive from BaseCharacterController, it is a special case local VehicleController = {} VehicleController.__index = VehicleController function VehicleController.new() local self = setmetatable({}, VehicleController) self.enabled = false self.vehicleSeat = nil self.throttle = 0 self.steer = 0 self.acceleration = 0 self.decceleration = 0 self.turningRight = 0 self.turningLeft = 0 self.vehicleMoveVector = ZERO_VECTOR3 return self end function VehicleController:Enable(enable, vehicleSeat) if enable == self.enabled and vehicleSeat == self.vehicleSeat then return end if enable then if vehicleSeat then self.vehicleSeat = vehicleSeat if useTriggersForThrottle then ContextActionService:BindAction("throttleAccel", (function() self:OnThrottleAccel() end), false, Enum.KeyCode.ButtonR2) ContextActionService:BindAction("throttleDeccel", (function() self:OnThrottleDeccel() end), false, Enum.KeyCode.ButtonL2) end ContextActionService:BindAction("arrowSteerRight", (function() self:OnSteerRight() end), false, Enum.KeyCode.Right) ContextActionService:BindAction("arrowSteerLeft", (function() self:OnSteerLeft() end), false, Enum.KeyCode.Left) end else if useTriggersForThrottle then ContextActionService:UnbindAction("throttleAccel") ContextActionService:UnbindAction("throttleDeccel") end ContextActionService:UnbindAction("arrowSteerRight") ContextActionService:UnbindAction("arrowSteerLeft") self.vehicleSeat = nil end end function VehicleController:OnThrottleAccel(actionName, inputState, inputObject) self.acceleration = (inputState ~= Enum.UserInputState.End) and -1 or 0 self.throttle = self.acceleration + self.decceleration end function VehicleController:OnThrottleDeccel(actionName, inputState, inputObject) self.decceleration = (inputState ~= Enum.UserInputState.End) and 1 or 0 self.throttle = self.acceleration + self.decceleration end function VehicleController:OnSteerRight(actionName, inputState, inputObject) self.turningRight = (inputState ~= Enum.UserInputState.End) and 1 or 0 self.steer = self.turningRight + self.turningLeft end function VehicleController:OnSteerLeft(actionName, inputState, inputObject) self.turningLeft = (inputState ~= Enum.UserInputState.End) and -1 or 0 self.steer = self.turningRight + self.turningLeft end -- Call this from a function bound to Renderstep with Input Priority function VehicleController:Update(moveVector, usingGamepad) if self.vehicleSeat then moveVector = moveVector + Vector3.new(self.steer, 0, self.throttle) if usingGamepad and onlyTriggersForThrottle and useTriggersForThrottle then self.vehicleSeat.ThrottleFloat = -self.throttle else self.vehicleSeat.ThrottleFloat = -moveVector.Z end self.vehicleSeat.SteerFloat = moveVector.X return moveVector, true end return moveVector, false end return VehicleController
apache-2.0
kitala1/darkstar
scripts/zones/Rabao/npcs/HomePoint#2.lua
12
1172
----------------------------------- -- Area: Rabao -- NPC: HomePoint#2 -- @pos -21 8.13 110 247 ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Rabao/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 105); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Baya_Hiramayuh.lua
24
1486
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Baya Hiramayuh -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Based on scripts/zones/Mhaura/Dieh_Yamilsiah.lua local timer = 1152 - ((os.time() - 1009811376)%1152); local direction = 0; -- Arrive, 1 for depart local waiting = 195; -- Offset for Mhaura if (timer <= waiting) then direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart" else timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival end player:startEvent(232,timer,direction); 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
kitala1/darkstar
scripts/globals/weaponskills/full_swing.lua
30
1260
----------------------------------- -- Full Swing -- Staff weapon skill -- Skill Level: 200 -- Delivers a single-hit attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Flame Gorget & Thunder Gorget. -- Aligned with the Flame Belt & Thunder Belt. -- Element: None -- Modifiers: STR:50% -- 100%TP 200%TP 300%TP -- 1.00 3.00 5.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 3; params.ftp300 = 5; params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
fastmailops/prosody
util/events.lua
1
2006
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local pairs = pairs; local t_insert = table.insert; local t_sort = table.sort; local setmetatable = setmetatable; local next = next; module "events" function new() local handlers = {}; local event_map = {}; local function _rebuild_index(handlers, event) local _handlers = event_map[event]; if not _handlers or next(_handlers) == nil then return; end local index = {}; for handler in pairs(_handlers) do t_insert(index, handler); end t_sort(index, function(a, b) return _handlers[a] > _handlers[b]; end); handlers[event] = index; return index; end; setmetatable(handlers, { __index = _rebuild_index }); local function add_handler(event, handler, priority) local map = event_map[event]; if map then map[handler] = priority or 0; else map = {[handler] = priority or 0}; event_map[event] = map; end handlers[event] = nil; end; local function remove_handler(event, handler) local map = event_map[event]; if map then map[handler] = nil; handlers[event] = nil; if next(map) == nil then event_map[event] = nil; end end end; local function add_handlers(handlers) for event, handler in pairs(handlers) do add_handler(event, handler); end end; local function remove_handlers(handlers) for event, handler in pairs(handlers) do remove_handler(event, handler); end end; local function fire_event(event_name, event_data) local h = handlers[event_name]; if h then for i=1,#h do local ret = h[i](event_data); if ret ~= nil then return ret; end end end end; return { add_handler = add_handler; remove_handler = remove_handler; add_handlers = add_handlers; remove_handlers = remove_handlers; fire_event = fire_event; _handlers = handlers; _event_map = event_map; }; end return _M;
mit
sirxkilller/BolScripts-1
KarthusMechanics.lua
2
18675
--[[ _____ _____ __ .__ / \_______ / _ \________/ |_|__| ____ __ __ ____ ____ / \ / \_ __ \ / /_\ \_ __ \ __\ |/ ___\| | \/ \ / _ \ / Y \ | \/ / | \ | \/| | | \ \___| | / | ( <_> ) \____|__ /__| \____|__ /__| |__| |__|\___ >____/|___| /\____/ \/ \/ \/ \/ ]] if myHero.charName ~= "Karthus" then return end local version = 0.3 local AUTOUPDATE = true local SCRIPT_NAME = "KarthusMechanics" local SOURCELIB_URL = "https://raw.github.com/TheRealSource/public/master/common/SourceLib.lua" local SOURCELIB_PATH = LIB_PATH.."SourceLib.lua" if FileExist(SOURCELIB_PATH) then require("SourceLib") else DOWNLOADING_SOURCELIB = true DownloadFile(SOURCELIB_URL, SOURCELIB_PATH, function() print("Required libraries downloaded successfully, please reload") end) end if DOWNLOADING_SOURCELIB then print("Downloading required libraries, please wait...") return end if AUTOUPDATE then SourceUpdater(SCRIPT_NAME, version, "raw.github.com", "/gmlyra/BolScripts/master/"..SCRIPT_NAME..".lua", SCRIPT_PATH .. GetCurrentEnv().FILE_NAME, "/gmlyra/BolScripts/VersionFiles/master/"..SCRIPT_NAME..".version"):CheckUpdate() end local RequireI = Require("SourceLib") RequireI:Add("vPrediction", "https://raw.github.com/Hellsing/BoL/master/common/VPrediction.lua") RequireI:Add("SOW", "https://raw.github.com/Hellsing/BoL/master/common/SOW.lua") --RequireI:Add("mrLib", "https://raw.githubusercontent.com/gmlyra/BolScripts/master/common/mrLib.lua") if VIP_USER then RequireI:Add("Prodiction", "https://bitbucket.org/Klokje/public-klokjes-bol-scripts/raw/ec830facccefb3b52212dba5696c08697c3c2854/Test/Prodiction/Prodiction.lua") end RequireI:Check() if RequireI.downloadNeeded == true then return end require 'VPrediction' require 'SOW' -- Constants -- local QREADY, WREADY, EREADY, RREADY = false, false, false, false local ignite, igniteReady = nil, nil local ts = nil local VP = nil local eActive = false local qOff, wOff, eOff, rOff = 0,0,0,0 local abilitySequence = {3, 1, 1, 2, 1, 4, 1, 3, 1, 3, 4, 3, 3, 2, 2, 4, 2, 2} local Ranges = { Q = 875, W = 1000, E = 425, R = 900000 , AA = 450} local skills = { skillQ = {spellName = "Lay Waste", range = 875, speed = 1700, delay = .5, width = 200}, skillW = {spellName = "Wall of Pain", range = 1000, speed = 1600, delay = .5, width = 80}, skillE = {spellName = "Defile", range = 425, speed = 1000, delay = .5, width = 425}, skillR = {spellName = "Requiem", range = 900000, speed = 200, delay = 3.0, width = 400}, } local AnimationCancel = { [1]=function() myHero:MoveTo(mousePos.x,mousePos.z) end, --"Move" [2]=function() SendChat('/l') end, --"Laugh" [3]=function() SendChat('/d') end, --"Dance" [4]=function() SendChat('/t') end, --"Taunt" [5]=function() SendChat('/j') end, --"joke" [6]=function() end, } local QREADY, WREADY, EREADY, RREADY= false, false, false, false local BRKSlot, DFGSlot, HXGSlot, BWCSlot, TMTSlot, RAHSlot, RNDSlot, YGBSlot = nil, nil, nil, nil, nil, nil, nil, nil local BRKREADY, DFGREADY, HXGREADY, BWCREADY, TMTREADY, RAHREADY, RNDREADY, YGBREADY = false, false, false, false, false, false, false, false --[[Auto Attacks]]-- local lastBasicAttack = 0 local swingDelay = 0.25 local swing = false function OnLoad() initComponents() end function initComponents() -- VPrediction Start VP = VPrediction() -- SOW Declare Orbwalker = SOW(VP) if VIP_USER then require 'Prodiction' Prod = ProdictManager.GetInstance() ProdQ = Prod:AddProdictionObject(_Q, skills.skillQ.range, skills.skillQ.speed, skills.skillQ.delay, skills.skillQ.width) ProdW = Prod:AddProdictionObject(_W, skills.skillW.range, skills.skillW.speed, skills.skillW.delay, skills.skillW.width) end -- Target Selector ts = TargetSelector(TARGET_NEAR_MOUSE, 900) Menu = scriptConfig("Karthus Mechanics by Mr Articuno", "KarthusMA") Menu:addSubMenu("["..myHero.charName.." - Orbwalker]", "SOWorb") Orbwalker:LoadToMenu(Menu.SOWorb) Menu:addSubMenu("["..myHero.charName.." - Combo]", "KarthusCombo") Menu.KarthusCombo:addParam("combo", "Combo mode", SCRIPT_PARAM_ONKEYDOWN, false, 32) -- Menu.KarthusCombo:addParam("useF", "Use Flash in Combo ", SCRIPT_PARAM_ONOFF, false) Menu.KarthusCombo:addSubMenu("Q Settings", "qSet") Menu.KarthusCombo.qSet:addParam("useQ", "Use Q in combo", SCRIPT_PARAM_ONOFF, true) Menu.KarthusCombo:addSubMenu("W Settings", "wSet") Menu.KarthusCombo.wSet:addParam("useW", "Use W in combo", SCRIPT_PARAM_ONOFF, true) Menu.KarthusCombo:addSubMenu("E Settings", "eSet") Menu.KarthusCombo.eSet:addParam("useE", "Use E in combo", SCRIPT_PARAM_ONOFF, true) Menu:addSubMenu("["..myHero.charName.." - Harass]", "Harass") Menu.Harass:addParam("harass", "Harass", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("G")) Menu.Harass:addParam("useQ", "Use Q in Harass", SCRIPT_PARAM_ONOFF, true) Menu.Harass:addParam("useW", "Use W in Harass", SCRIPT_PARAM_ONOFF, true) Menu.Harass:addParam("useE", "Use E in Harass", SCRIPT_PARAM_ONOFF, true) Menu:addSubMenu("["..myHero.charName.." - Laneclear]", "Laneclear") Menu.Laneclear:addParam("lclr", "Laneclear Key", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("V")) Menu.Laneclear:addParam("useClearQ", "Use Q in Laneclear", SCRIPT_PARAM_ONOFF, true) Menu.Laneclear:addParam("useClearW", "Use W in Laneclear", SCRIPT_PARAM_ONOFF, true) Menu.Laneclear:addParam("useClearE", "Use E in Laneclear", SCRIPT_PARAM_ONOFF, true) Menu:addSubMenu("["..myHero.charName.." - Jungleclear]", "Jungleclear") Menu.Jungleclear:addParam("jclr", "Jungleclear Key", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("V")) Menu.Jungleclear:addParam("useClearQ", "Use Q in Jungleclear", SCRIPT_PARAM_ONOFF, true) Menu.Jungleclear:addParam("useClearW", "Use W in Jungleclear", SCRIPT_PARAM_ONOFF, true) Menu.Jungleclear:addParam("useClearE", "Use E in Jungleclear", SCRIPT_PARAM_ONOFF, true) Menu:addSubMenu("["..myHero.charName.." - Additionals]", "Ads") Menu.Ads:addSubMenu("Ultimate Settings", "rSet") Menu.Ads.rSet:addParam("useR", "Auto Use Ultimate", SCRIPT_PARAM_ONOFF, true) Menu.Ads.rSet:addParam("nEnemy", "Quantity of Enemies Killable", SCRIPT_PARAM_SLICE, 1, 0, 5, 0) Menu.Ads:addParam("cancel", "Animation Cancel", SCRIPT_PARAM_LIST, 1, { "Move","Laugh","Dance","Taunt","joke","Nothing" }) AddProcessSpellCallback(function(unit, spell) if unit.isMe then if spell.name == 'KarthusDefile' then eActive = not eActive elseif spell.name == 'KarthusDefileSoundDummy2' then eActive = true end lastBasicAttack = os.clock() end end) Menu.Ads:addParam("autoLevel", "Auto-Level Spells", SCRIPT_PARAM_ONOFF, false) Menu.Ads:addSubMenu("Killsteal", "KS") Menu.Ads.KS:addParam("ignite", "Use Ignite", SCRIPT_PARAM_ONOFF, false) Menu.Ads.KS:addParam("igniteRange", "Minimum range to cast Ignite", SCRIPT_PARAM_SLICE, 470, 0, 600, 0) Menu.Ads:addSubMenu("VIP", "VIP") Menu.Ads.VIP:addParam("spellCast", "Spell by Packet", SCRIPT_PARAM_ONOFF, true) Menu.Ads.VIP:addParam("useProdiction", "Use Prodction", SCRIPT_PARAM_ONOFF, true) Menu.Ads.VIP:addParam("skin", "Use custom skin (Requires Reload)", SCRIPT_PARAM_ONOFF, false) Menu.Ads.VIP:addParam("skin1", "Skin changer", SCRIPT_PARAM_SLICE, 1, 1, 6) Menu:addSubMenu("["..myHero.charName.." - Target Selector]", "targetSelector") Menu.targetSelector:addTS(ts) ts.name = "Focus" Menu:addSubMenu("["..myHero.charName.." - Drawings]", "drawings") local DManager = DrawManager() DManager:CreateCircle(myHero, Ranges.AA, 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"AA range", true, true, true) DManager:CreateCircle(myHero, skills.skillQ.range, 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"Q range", true, true, true) DManager:CreateCircle(myHero, skills.skillW.range, 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"W range", true, true, true) DManager:CreateCircle(myHero, skills.skillE.range, 1, {255, 0, 255, 0}):AddToMenu(Menu.drawings,"E range", true, true, true) enemyMinions = minionManager(MINION_ENEMY, 360, myHero, MINION_SORT_MAXHEALTH_DEC) allyMinions = minionManager(MINION_ALLY, 360, myHero, MINION_SORT_MAXHEALTH_DEC) jungleMinions = minionManager(MINION_JUNGLE, 360, myHero, MINION_SORT_MAXHEALTH_DEC) if Menu.Ads.VIP.skin and VIP_USER then GenModelPacket("Karthus", Menu.Ads.VIP.skin1) end PrintChat("<font color = \"#33CCCC\">Karthus Mechanics by</font> <font color = \"#fff8e7\">Mr Articuno</font>") end function OnTick() ts:update() enemyMinions:update() allyMinions:update() jungleMinions:update() CDHandler() KillSteal() DFGSlot, HXGSlot, BWCSlot, SheenSlot, TrinitySlot, LichBaneSlot, BRKSlot, TMTSlot, RAHSlot, RNDSlot, STDSlot = GetInventorySlotItem(3128), GetInventorySlotItem(3146), GetInventorySlotItem(3144), GetInventorySlotItem(3057), GetInventorySlotItem(3078), GetInventorySlotItem(3100), GetInventorySlotItem(3153), GetInventorySlotItem(3077), GetInventorySlotItem(3074), GetInventorySlotItem(3143), GetInventorySlotItem(3131) QREADY = (myHero:CanUseSpell(_Q) == READY) WREADY = (myHero:CanUseSpell(_W) == READY) EREADY = (myHero:CanUseSpell(_E) == READY) RREADY = (myHero:CanUseSpell(_R) == READY) DFGREADY = (DFGSlot ~= nil and myHero:CanUseSpell(DFGSlot) == READY) HXGREADY = (HXGSlot ~= nil and myHero:CanUseSpell(HXGSlot) == READY) BWCREADY = (BWCSlot ~= nil and myHero:CanUseSpell(BWCSlot) == READY) BRKREADY = (BRKSlot ~= nil and myHero:CanUseSpell(BRKSlot) == READY) TMTREADY = (TMTSlot ~= nil and myHero:CanUseSpell(TMTSlot) == READY) RAHREADY = (RAHSlot ~= nil and myHero:CanUseSpell(RAHSlot) == READY) RNDREADY = (RNDSlot ~= nil and myHero:CanUseSpell(RNDSlot) == READY) STDREADY = (STDSlot ~= nil and myHero:CanUseSpell(STDSlot) == READY) IREADY = (ignite ~= nil and myHero:CanUseSpell(ignite) == READY) if swing and os.clock() > lastBasicAttack + 0.625 then --swing = false end if Menu.Ads.autoLevel then AutoLevel() elseif Menu.KarthusCombo.combo then Combo() elseif Menu.Harass.harass then Harass() elseif Menu.Laneclear.lclr then LaneClear() elseif Menu.Jungleclear.jclr then JungleClear() end end function CDHandler() -- Spells QREADY = (myHero:CanUseSpell(_Q) == READY) WREADY = (myHero:CanUseSpell(_W) == READY) EREADY = (myHero:CanUseSpell(_E) == READY) RREADY = (myHero:CanUseSpell(_R) == READY) -- Items tiamatSlot = GetInventorySlotItem(3077) hydraSlot = GetInventorySlotItem(3074) youmuuSlot = GetInventorySlotItem(3142) bilgeSlot = GetInventorySlotItem(3144) bladeSlot = GetInventorySlotItem(3153) tiamatReady = (tiamatSlot ~= nil and myHero:CanUseSpell(tiamatSlot) == READY) hydraReady = (hydraSlot ~= nil and myHero:CanUseSpell(hydraSlot) == READY) youmuuReady = (youmuuSlot ~= nil and myHero:CanUseSpell(youmuuSlot) == READY) bilgeReady = (bilgeSlot ~= nil and myHero:CanUseSpell(bilgeSlot) == READY) bladeReady = (bladeSlot ~= nil and myHero:CanUseSpell(bladeSlot) == READY) -- Summoners if myHero:GetSpellData(SUMMONER_1).name:find("SummonerDot") then ignite = SUMMONER_1 elseif myHero:GetSpellData(SUMMONER_2).name:find("SummonerDot") then ignite = SUMMONER_2 end igniteReady = (ignite ~= nil and myHero:CanUseSpell(ignite) == READY) end -- Harass -- function Harass() local target = ts.target if target ~= nil and ValidTarget(target) then if Menu.Harass.useE and ValidTarget(target, skills.skillE.range) and EREADY and not eActive then CastSpell(_E) end if VIP_USER and Menu.Ads.VIP.useProdiction then if WREADY and Menu.Harass.useW and ValidTarget(target, skills.skillW.range) then local pos, info = Prodiction.GetPrediction(target, skills.skillW.range, skills.skillW.speed, skills.skillW.delay, skills.skillW.width) if pos then CastSpell(_W, pos.x, pos.z) end end if QREADY and Menu.Harass.useQ and ValidTarget(target, skills.skillQ.range) then local pos, info = Prodiction.GetPrediction(target, skills.skillQ.range, skills.skillQ.speed, skills.skillQ.delay, skills.skillQ.width) if pos then CastSpell(_Q, pos.x, pos.z) end end else if WREADY and Menu.Harass.useW and ValidTarget(target, skills.skillW.range) then local wPosition, wChance = VP:GetLineCastPosition(target, skills.skillW.delay, skills.skillW.width, skills.skillW.range, skills.skillW.speed, myHero, false) if wPosition ~= nil and wChance >= 2 then CastSpell(_W, wPosition.x, wPosition.z) end end if QREADY and Menu.Harass.useQ and ValidTarget(target, skills.skillQ.range) then local qPosition, qChance = VP:GetCircularCastPosition(target, skills.skillQ.delay, skills.skillQ.width, skills.skillQ.range, skills.skillQ.speed, myHero, false) if qPosition ~= nil and qChance >= 2 then CastSpell(_Q, qPosition.x, qPosition.z) end end end end end -- End Harass -- -- Combo Selector -- function Combo() local typeCombo = 0 if ts.target ~= nil then AllInCombo(ts.target, 0) end end -- Combo Selector -- -- All In Combo -- function AllInCombo(target, typeCombo) if target ~= nil and typeCombo == 0 then if Menu.KarthusCombo.eSet.useE and ValidTarget(target, skills.skillE.range) and EREADY and not eActive then CastSpell(_E) end if VIP_USER and Menu.Ads.VIP.useProdiction then if WREADY and Menu.KarthusCombo.wSet.useW and ValidTarget(target, skills.skillW.range) then local pos, info = Prodiction.GetPrediction(target, skills.skillW.range, skills.skillW.speed, skills.skillW.delay, skills.skillW.width) if pos then CastSpell(_W, pos.x, pos.z) end end if QREADY and Menu.KarthusCombo.qSet.useQ and ValidTarget(target, skills.skillQ.range) then local pos, info = Prodiction.GetPrediction(target, skills.skillQ.range, skills.skillQ.speed, skills.skillQ.delay, skills.skillQ.width) if pos then CastSpell(_Q, pos.x, pos.z) end end else if WREADY and Menu.KarthusCombo.wSet.useW and ValidTarget(target, skills.skillW.range) then local wPosition, wChance = VP:GetLineCastPosition(target, skills.skillW.delay, skills.skillW.width, skills.skillW.range, skills.skillW.speed, myHero, false) if wPosition ~= nil and wChance >= 2 then CastSpell(_W, wPosition.x, wPosition.z) end end if QREADY and Menu.KarthusCombo.qSet.useQ and ValidTarget(target, skills.skillQ.range) then local qPosition, qChance = VP:GetCircularCastPosition(target, skills.skillQ.delay, skills.skillQ.width, skills.skillQ.range, skills.skillQ.speed, myHero, false) if qPosition ~= nil and qChance >= 2 then CastSpell(_Q, qPosition.x, qPosition.z) end end end end end -- All In Combo -- function LaneClear() for i, enemyMinion in pairs(enemyMinions.objects) do if Menu.Laneclear.useClearE and ValidTarget(enemyMinion, skills.skillE.range) and EREADY and not eActive then CastSpell(_E) end if QREADY and Menu.Laneclear.useClearQ and ValidTarget(enemyMinion, skills.skillQ.range) then local qPosition, qChance = VP:GetCircularCastPosition(enemyMinion, skills.skillQ.delay, skills.skillQ.width, skills.skillQ.range, skills.skillQ.speed, myHero, false) if qPosition ~= nil and qChance >= 2 then CastSpell(_Q, qPosition.x, qPosition.z) end end end end function JungleClear() for i, jungleMinion in pairs(jungleMinions.objects) do if jungleMinion ~= nil then if Menu.JungleClear.useClearE and ValidTarget(jungleMinion, skills.skillE.range) and EREADY and not eActive then CastSpell(_E) end if QREADY and Menu.JungleClear.useClearQ and ValidTarget(jungleMinion, skills.skillQ.range) then local qPosition, qChance = VP:GetCircularCastPosition(jungleMinion, skills.skillQ.delay, skills.skillQ.width, skills.skillQ.range, skills.skillQ.speed, myHero, false) if qPosition ~= nil and qChance >= 2 then CastSpell(_Q, qPosition.x, qPosition.z) end end end end end function AutoLevel() local qL, wL, eL, rL = player:GetSpellData(_Q).level + qOff, player:GetSpellData(_W).level + wOff, player:GetSpellData(_E).level + eOff, player:GetSpellData(_R).level + rOff if qL + wL + eL + rL < player.level then local spellSlot = { SPELL_1, SPELL_2, SPELL_3, SPELL_4, } local level = { 0, 0, 0, 0 } for i = 1, player.level, 1 do level[abilitySequence[i]] = level[abilitySequence[i]] + 1 end for i, v in ipairs({ qL, wL, eL, rL }) do if v < level[i] then LevelSpell(spellSlot[i]) end end end end function KillSteal() if Menu.Ads.rSet.useR then KSR() end if Menu.Ads.KS.ignite then IgniteKS() end end -- Use Ultimate -- function KSR() local numberKillable = 0 for i, enemy in ipairs(GetEnemyHeroes()) do rDmg = getDmg("R", enemy, myHero) if enemy ~= nil and enemy.health < rDmg then numberKillable = numberKillable + 1 end end if enemy ~= nil and numberKillable >= Menu.Ads.rSet.nEnemy and Menu.Ads.rSet.useR then CastSpell(_R) end end -- Use Ultimate -- -- Auto Ignite get the maximum range to avoid over kill -- function IgniteKS() if igniteReady then local Enemies = GetEnemyHeroes() for i, val in ipairs(Enemies) do if ValidTarget(val, 600) then if getDmg("IGNITE", val, myHero) > val.health and RReady ~= true and GetDistance(val) >= Menu.Ads.KS.igniteRange then CastSpell(ignite, val) end end end end end -- Auto Ignite -- function HealthCheck(unit, HealthValue) if unit.health > (unit.maxHealth * (HealthValue/100)) then return true else return false end end function animationCancel(unit, spell) if not unit.isMe then return end end function ItemUsage(target) if DFGREADY then CastSpell(DFGSlot, target) end if HXGREADY then CastSpell(HXGSlot, target) end if BWCREADY then CastSpell(BWCSlot, target) end if BRKREADY then CastSpell(BRKSlot, target) end if TMTREADY and GetDistance(target) < 275 then CastSpell(TMTSlot) end if RAHREADY and GetDistance(target) < 275 then CastSpell(RAHSlot) end if RNDREADY and GetDistance(target) < 275 then CastSpell(RNDSlot) end end -- Change skin function, made by Shalzuth function GenModelPacket(champ, skinId) p = CLoLPacket(0x97) p:EncodeF(myHero.networkID) p.pos = 1 t1 = p:Decode1() t2 = p:Decode1() t3 = p:Decode1() t4 = p:Decode1() p:Encode1(t1) p:Encode1(t2) p:Encode1(t3) p:Encode1(bit32.band(t4,0xB)) p:Encode1(1)--hardcode 1 bitfield p:Encode4(skinId) for i = 1, #champ do p:Encode1(string.byte(champ:sub(i,i))) end for i = #champ + 1, 64 do p:Encode1(0) end p:Hide() RecvPacket(p) end function OnDraw() end
gpl-2.0
omideblisss/omid
plugins/inrealm.lua
92
25223
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end --Copyright and edit; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
amirkingred/nod2
plugins/inrealm.lua
92
25223
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end --Copyright and edit; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
chucksellick/factorio-portal-research
src/modules/radio.lua
1
7731
local inspect = require("lib.inspect") local Radio = {} -- TODO: Implement copy/paste local radio_update_frequency = 60 -- TODO: Read from prototype local max_radio_combinator_slots = 10 local wire_colours = {defines.wire_type.red,defines.wire_type.green} function Radio.initForce(forceData) forceData.radio = { channels = {} } end local function getChannels(force) local data = getForceData(force) if not data.radio then Radio.initForce(data) end return data.radio.channels end function Radio.initializeMast(entityData) -- Defaults to receiver entityData.is_transmitter = false entityData.channel = 1 entityData.next_update_tick = Ticks.after(radio_update_frequency, "radio.update_entity", {entity=entityData}) end function Radio.initializeLogisticsCombinator(entityData) entityData.next_update_tick = Ticks.after(radio_update_frequency, "radio.update_entity", {entity=entityData}) end function Radio.updateEntity(data) if data.entity.entity.name == "radio-mast" or data.entity.entity.name == "radio-mast-transmitter" then if data.entity.is_transmitter then Radio.readMastInput(data.entity) else Radio.setMastOutput(data.entity) end elseif data.entity.entity.name == "orbital-logistics-combinator" then Radio.setLogisticsCombinatorOutput(data.entity) end data.entity.next_update_tick = Ticks.after(radio_update_frequency, "radio.update_entity", {entity=data.entity}) end Ticks.registerHandler("radio.update_entity", Radio.updateEntity) -- Note: Power consumption is a bit hard here. Clearly the transmitter masts should consume -- power and this can be reasonably simulated by increasing the time to next transmit if not -- enough power was available. But it's slightly less clear what to do for receivers; don't want -- every single radio receiver to receive at slightly different times (for UPS reasons) although -- doing this would allow a more accurate simulation of distances between the receivers at asteroids. -- For now I'm completely ignoring power because the more I think about it the more weird corner cases there are. local function switchEntities(source, new_entity_name) local new_entity = source.entity.surface.create_entity{ name = new_entity_name, position = source.entity.position, force = source.entity.force } -- Copy wire connections to the new entity for i,wire in pairs(wire_colours) do local entities = source.entity.circuit_connected_entities[wire] if entities then for e,entity in pairs(entities) do new_entity.connect_neighbour{wire=wire,target_entity=entity} end end end -- Manually update the global registry rather than letting normal cleanup do its work global.entities[source.id] = nil source.id = new_entity.unit_number global.entities[source.id] = source -- Destroy the old entity source.entity.destroy() -- Switcheroo complete source.entity = new_entity end function Radio.setTransmit(mast, transmit) if mast.is_transmitter ~= transmit then if transmit then Radio.switchToTransmitter(mast) else Radio.switchToReceiver(mast) end end end function Radio.switchToTransmitter(entityData) switchEntities(entityData, "radio-mast-transmitter") entityData.is_transmitter = true -- Make sure "lamp" is always on, and connected to circuits entityData.entity.get_or_create_control_behavior().connect_to_logistic_network = false entityData.entity.get_control_behavior().circuit_condition = { condition = { comparator = ">", first_signal = {type = "virtual", name = "signal-everything"}, constant = 0 } } end function Radio.switchToReceiver(entityData) switchEntities(entityData, "radio-mast") entityData.is_transmitter = false end function Radio.changeMastChannel(entityData, channel) -- TODO: Clearing channel immediately, should lag a bit? if entityData.channel == channel then return end local channels = getChannels(entityData.force) channels[entityData.channel] = nil entityData.channel = channel end function Radio.readMastInput(entityData) -- Merge red and green network counts together local signals = {} local parameters = {} local signal_index = 1 -- TODO: This might be a bit slow if we wanted to reduce radio ping. Might be a fast way to do things -- avoiding all the object creation and string concatenation. Investigate and maybe borrow some code from somewhere :) for i,wire in pairs(wire_colours) do local network = entityData.entity.get_circuit_network(wire) if network and network.signals then for index,signal in pairs(network.signals) do local temp_name = signal.signal.type.."."..signal.signal.name if signals[temp_name] then signals[temp_name].count = signals[temp_name].count + signal.count elseif signal_index <= max_radio_combinator_slots then signals[temp_name] = { signal = signal.signal, index = signal_index, count = signal.count } signal_index = signal_index + 1 table.insert(parameters, signals[temp_name]) end end end end -- TODO: Store a list of the receivers local channels = getChannels(entityData.force) channels[entityData.channel] = channels[entityData.channel] or {} channels[entityData.channel].parameters = {parameters = parameters} -- That's correct. end function Radio.setMastOutput(entityData) -- TODO: Consume power local control_behavior = entityData.entity.get_or_create_control_behavior() if not control_behavior.enabled then return end local channels = getChannels(entityData.force) if channels[entityData.channel] then control_behavior.parameters = channels[entityData.channel].parameters else control_behavior.parameters = nil end end function Radio.setLogisticsCombinatorOutput(entityData) local control_behavior = entityData.entity.get_or_create_control_behavior() if not control_behavior.enabled then return end -- TODO: On radio mast using a different method of -- setting control_behavior.parameters in one go. Need to test and verify which method is -- faster. Since only setting a couple here it doesn't matter but could make -- more difference for radio. -- Clear existing params control_behavior.parameters = nil local counts = Orbitals.getCounts() local index = 1 for name,count in pairs(counts) do control_behavior.set_signal(index, {signal = {type = "item", name = name}, count = count}) index = index + 1 end -- TODO: Consume power (?), reduce update frequency end function Radio.openMastGui(playerData, gui, data, window_options) local row1 = gui.add{type="flow",direction="horizontal"} Gui.createButton(playerData.player, row1, { name="radio-mast-receive-" .. data.id, caption={"portal-research.radio-mast-receive-button-caption"}, action={name="radio-mast-set-transmit",mast=data,transmit=false} }) Gui.createButton(playerData.player, row1, { name="radio-mast-transmit-" .. data.id, caption={"portal-research.radio-mast-transmit-button-caption"}, action={name="radio-mast-set-transmit",mast=data,transmit=true} }) local row2 = gui.add{type="flow",direction="horizontal"} row2.add{ type="label", caption={"portal-research.radio-mast-"..(data.is_transmitter and "transmitting" or "receiving").."-caption"} } row2.add{ type="textfield", name="radio-mast-channel-number-textfield", text=data.channel } -- TODO: Slider for channel # ... if they ever provide one ... could fudge with scrollbar? -- TODO: List receivers or at least receiver counts. Update when channel changed. end return Radio
mit
kitala1/darkstar
scripts/globals/spells/bluemagic/enervation.lua
7
1549
----------------------------------------- -- Spell: Enervation -- Lowers the defense and magical defense of enemies within range -- Spell cost: 48 MP -- Monster Type: Beastmen -- Spell Type: Magical (Dark) -- Blue Magic Points: 5 -- Stat Bonus: HP-5, MP+5 -- Level: 67 -- Casting Time: 6 seconds -- Recast Time: 60 seconds -- Magic Bursts on: Compression, Gravitation, and Darkness -- Combos: Counter ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0); if(damage > 0 and resist > 0) then local typeEffect = EFFECT_DEFENSE_DOWN; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,10,0,getBlueEffectDuration(caster,resist,typeEffect)); end if(damage > 0 and resist > 0) then local typeEffect = EFFECT_MAGIC_DEF_DOWN; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,8,0,getBlueEffectDuration(caster,resist,typeEffect)); end return EFFECT_DEFENSE_DOWN; end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/temple_truffle.lua
36
1159
----------------------------------------- -- ID: 5916 -- Item: Temple Truffle -- Food Effect: 3 Min, All Races ----------------------------------------- -- Strength 1 -- Speed 12.5% ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) 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,180,5916); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 1); target:addMod(MOD_MOVE, 13); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 1); target:delMod(MOD_MOVE, 13); end;
gpl-3.0
JacobFischer/Joueur.lua
games/chess/gameObject.lua
9
2227
-- GameObject: An object in the game. The most basic class that all game classes should inherit from automatically. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local BaseGameObject = require("joueur.baseGameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- An object in the game. The most basic class that all game classes should inherit from automatically. -- @classmod GameObject local GameObject = class(BaseGameObject) -- initializes a GameObject with basic logic as provided by the Creer code generator function GameObject:init(...) BaseGameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. self.gameObjectName = "" --- A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. self.id = "" --- Any strings logged will be stored here. Intended for debugging. self.logs = Table() end --- Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @tparam string message A string to add to this GameObject's log. Intended for debugging. function GameObject:log(message) return (self:_runOnServer("log", { message = message, })) end -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return GameObject
mit
crabman77/minetest-minetestforfun-server
mods/pipeworks/devices.lua
8
15833
-- List of devices that should participate in the autoplace algorithm local pipereceptor_on = nil local pipereceptor_off = nil if minetest.get_modpath("mesecons") then pipereceptor_on = { receptor = { state = mesecon.state.on, rules = pipeworks.mesecons_rules } } pipereceptor_off = { receptor = { state = mesecon.state.off, rules = pipeworks.mesecons_rules } } end local pipes_devicelist = { "pump", "valve", "storage_tank_0", "storage_tank_1", "storage_tank_2", "storage_tank_3", "storage_tank_4", "storage_tank_5", "storage_tank_6", "storage_tank_7", "storage_tank_8", "storage_tank_9", "storage_tank_10" } local rules = pipeworks.mesecons_rules -- Enough with the undefined global variable // MFF (Mg|01/07/2016 for #68) -- Now define the nodes. local states = { "on", "off" } local dgroups = "" for s in ipairs(states) do if states[s] == "off" then dgroups = {snappy=3, pipe=1} else dgroups = {snappy=3, pipe=1, not_in_creative_inventory=1} end minetest.register_node("pipeworks:pump_"..states[s], { description = "Pump/Intake Module", drawtype = "mesh", mesh = "pipeworks_pump.obj", tiles = { "pipeworks_pump_"..states[s]..".png" }, paramtype = "light", paramtype2 = "facedir", groups = dgroups, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, drop = "pipeworks:pump_off", mesecons = {effector = { action_on = function (pos, node) minetest.add_node(pos,{name="pipeworks:pump_on", param2 = node.param2}) end, action_off = function (pos, node) minetest.add_node(pos,{name="pipeworks:pump_off", param2 = node.param2}) end }}, on_punch = function(pos, node, puncher) local fdir = minetest.get_node(pos).param2 minetest.add_node(pos, { name = "pipeworks:pump_"..states[3-s], param2 = fdir }) end }) minetest.register_node("pipeworks:valve_"..states[s].."_empty", { description = "Valve", drawtype = "mesh", mesh = "pipeworks_valve_"..states[s]..".obj", tiles = { "pipeworks_valve.png" }, sunlight_propagates = true, paramtype = "light", paramtype2 = "facedir", selection_box = { type = "fixed", fixed = { -8/16, -4/16, -5/16, 8/16, 5/16, 5/16 } }, collision_box = { type = "fixed", fixed = { -8/16, -4/16, -5/16, 8/16, 5/16, 5/16 } }, groups = dgroups, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, drop = "pipeworks:valve_off_empty", mesecons = {effector = { action_on = function (pos, node) minetest.add_node(pos,{name="pipeworks:valve_on_empty", param2 = node.param2}) end, action_off = function (pos, node) minetest.add_node(pos,{name="pipeworks:valve_off_empty", param2 = node.param2}) end }}, on_punch = function(pos, node, puncher) local fdir = minetest.get_node(pos).param2 minetest.add_node(pos, { name = "pipeworks:valve_"..states[3-s].."_empty", param2 = fdir }) end }) end minetest.register_node("pipeworks:valve_on_loaded", { description = "Valve", drawtype = "mesh", mesh = "pipeworks_valve_on.obj", tiles = { "pipeworks_valve.png" }, sunlight_propagates = true, paramtype = "light", paramtype2 = "facedir", selection_box = { type = "fixed", fixed = { -8/16, -4/16, -5/16, 8/16, 5/16, 5/16 } }, collision_box = { type = "fixed", fixed = { -8/16, -4/16, -5/16, 8/16, 5/16, 5/16 } }, groups = {snappy=3, pipe=1, not_in_creative_inventory=1}, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, drop = "pipeworks:valve_off_empty", mesecons = {effector = { action_on = function (pos, node) minetest.add_node(pos,{name="pipeworks:valve_on_empty", param2 = node.param2}) end, action_off = function (pos, node) minetest.add_node(pos,{name="pipeworks:valve_off_empty", param2 = node.param2}) end }}, on_punch = function(pos, node, puncher) local fdir = minetest.get_node(pos).param2 minetest.add_node(pos, { name = "pipeworks:valve_off_empty", param2 = fdir }) end }) -- grating minetest.register_node("pipeworks:grating", { description = "Decorative grating", tiles = { "pipeworks_grating_top.png", "pipeworks_grating_sides.png", "pipeworks_grating_sides.png", "pipeworks_grating_sides.png", "pipeworks_grating_sides.png", "pipeworks_grating_sides.png" }, sunlight_propagates = true, paramtype = "light", groups = {snappy=3, pipe=1}, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, }) -- outlet spigot minetest.register_node("pipeworks:spigot", { description = "Spigot outlet", drawtype = "mesh", mesh = "pipeworks_spigot.obj", tiles = { "pipeworks_spigot.png" }, sunlight_propagates = true, paramtype = "light", paramtype2 = "facedir", groups = {snappy=3, pipe=1}, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, selection_box = { type = "fixed", fixed = { -2/16, -6/16, -2/16, 2/16, 2/16, 8/16 } }, collision_box = { type = "fixed", fixed = { -2/16, -6/16, -2/16, 2/16, 2/16, 8/16 } } }) minetest.register_node("pipeworks:spigot_pouring", { description = "Spigot outlet", drawtype = "mesh", mesh = "pipeworks_spigot_pouring.obj", tiles = { { name = "default_water_flowing_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.8, }, }, { name = "pipeworks_spigot.png" } }, sunlight_propagates = true, paramtype = "light", paramtype2 = "facedir", groups = {snappy=3, pipe=1, not_in_creative_inventory=1}, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, selection_box = { type = "fixed", fixed = { -2/16, -6/16, -2/16, 2/16, 2/16, 8/16 } }, collision_box = { type = "fixed", fixed = { -2/16, -6/16, -2/16, 2/16, 2/16, 8/16 } }, drop = "pipeworks:spigot", }) -- sealed pipe entry/exit (horizontal pipe passing through a metal -- wall, for use in places where walls should look like they're airtight) local panel_cbox = { type = "fixed", fixed = { { -2/16, -2/16, -8/16, 2/16, 2/16, 8/16 }, { -8/16, -8/16, -1/16, 8/16, 8/16, 1/16 } } } minetest.register_node("pipeworks:entry_panel_empty", { description = "Airtight Pipe entry/exit", drawtype = "mesh", mesh = "pipeworks_entry_panel.obj", tiles = { "pipeworks_entry_panel.png" }, paramtype = "light", paramtype2 = "facedir", groups = {snappy=3, pipe=1}, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, selection_box = panel_cbox, collision_box = panel_cbox, on_place = function(itemstack, placer, pointed_thing) local playername = placer:get_player_name() if not minetest.is_protected(pointed_thing.under, playername) and not minetest.is_protected(pointed_thing.above, playername) then local node = minetest.get_node(pointed_thing.under) if not minetest.registered_nodes[node.name] or not minetest.registered_nodes[node.name].on_rightclick then local pitch = placer:get_look_pitch() local above = pointed_thing.above local under = pointed_thing.under local fdir = minetest.dir_to_facedir(placer:get_look_dir()) local undernode = minetest.get_node(under) local abovenode = minetest.get_node(above) local uname = undernode.name local aname = abovenode.name local isabove = (above.x == under.x) and (above.z == under.z) and (pitch > 0) local pos1 = above if above.x == under.x and above.z == under.z and ( string.find(uname, "pipeworks:pipe_") or string.find(uname, "pipeworks:storage_") or string.find(uname, "pipeworks:expansion_") or ( string.find(uname, "pipeworks:grating") and not isabove ) or ( string.find(uname, "pipeworks:pump_") and not isabove ) or ( string.find(uname, "pipeworks:entry_panel") and undernode.param2 == 13 ) ) then fdir = 13 end if minetest.registered_nodes[uname]["buildable_to"] then pos1 = under end if not minetest.registered_nodes[minetest.get_node(pos1).name]["buildable_to"] then return end minetest.add_node(pos1, {name = "pipeworks:entry_panel_empty", param2 = fdir }) pipeworks.scan_for_pipe_objects(pos1) if not pipeworks.expect_infinite_stacks then itemstack:take_item() end else minetest.registered_nodes[node.name].on_rightclick(pointed_thing.under, node, placer, itemstack) end end return itemstack end }) minetest.register_node("pipeworks:entry_panel_loaded", { description = "Airtight Pipe entry/exit", drawtype = "mesh", mesh = "pipeworks_entry_panel.obj", tiles = { "pipeworks_entry_panel.png" }, paramtype = "light", paramtype2 = "facedir", groups = {snappy=3, pipe=1, not_in_creative_inventory=1}, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, selection_box = panel_cbox, collision_box = panel_cbox, drop = "pipeworks:entry_panel_empty" }) minetest.register_node("pipeworks:flow_sensor_empty", { description = "Flow Sensor", drawtype = "mesh", mesh = "pipeworks_flow_sensor.obj", tiles = { "pipeworks_flow_sensor_off.png" }, sunlight_propagates = true, paramtype = "light", paramtype2 = "facedir", groups = {snappy=3, pipe=1}, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, on_construct = function(pos) if mesecon then mesecon.receptor_off(pos, rules) end end, selection_box = { type = "fixed", fixed = { { -8/16, -2/16, -2/16, 8/16, 2/16, 2/16 }, { -4/16, -3/16, -3/16, 4/16, 3/16, 3/16 }, } }, collision_box = { type = "fixed", fixed = { { -8/16, -2/16, -2/16, 8/16, 2/16, 2/16 }, { -4/16, -3/16, -3/16, 4/16, 3/16, 3/16 }, } }, mesecons = pipereceptor_off }) minetest.register_node("pipeworks:flow_sensor_loaded", { description = "Flow sensor (on)", drawtype = "mesh", mesh = "pipeworks_flow_sensor.obj", tiles = { "pipeworks_flow_sensor_on.png" }, sunlight_propagates = true, paramtype = "light", paramtype2 = "facedir", groups = {snappy=3, pipe=1, not_in_creative_inventory=1}, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, on_construct = function(pos) if mesecon then mesecon.receptor_on(pos, rules) end end, selection_box = { type = "fixed", fixed = { { -8/16, -2/16, -2/16, 8/16, 2/16, 2/16 }, { -4/16, -3/16, -3/16, 4/16, 3/16, 3/16 }, } }, collision_box = { type = "fixed", fixed = { { -8/16, -2/16, -2/16, 8/16, 2/16, 2/16 }, { -4/16, -3/16, -3/16, 4/16, 3/16, 3/16 }, } }, drop = "pipeworks:flow_sensor_empty", mesecons = pipereceptor_on }) -- tanks for fill = 0, 10 do local filldesc="empty" local sgroups = {snappy=3, pipe=1, tankfill=fill+1} local image = nil if fill ~= 0 then filldesc=fill.."0% full" sgroups = {snappy=3, pipe=1, tankfill=fill+1, not_in_creative_inventory=1} image = "pipeworks_storage_tank_fittings.png" end minetest.register_node("pipeworks:expansion_tank_"..fill, { description = "Expansion Tank ("..filldesc..")... You hacker, you.", tiles = { "pipeworks_storage_tank_fittings.png", "pipeworks_storage_tank_fittings.png", "pipeworks_storage_tank_back.png", "pipeworks_storage_tank_back.png", "pipeworks_storage_tank_back.png", pipeworks.liquid_texture.."^pipeworks_storage_tank_front_"..fill..".png" }, inventory_image = image, paramtype = "light", paramtype2 = "facedir", groups = {snappy=3, pipe=1, tankfill=fill+1, not_in_creative_inventory=1}, sounds = default.node_sound_wood_defaults(), walkable = true, drop = "pipeworks:storage_tank_0", after_place_node = function(pos) pipeworks.look_for_stackable_tanks(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, }) minetest.register_node("pipeworks:storage_tank_"..fill, { description = "Fluid Storage Tank ("..filldesc..")", tiles = { "pipeworks_storage_tank_fittings.png", "pipeworks_storage_tank_fittings.png", "pipeworks_storage_tank_back.png", "pipeworks_storage_tank_back.png", "pipeworks_storage_tank_back.png", pipeworks.liquid_texture.."^pipeworks_storage_tank_front_"..fill..".png" }, inventory_image = image, paramtype = "light", paramtype2 = "facedir", groups = sgroups, sounds = default.node_sound_wood_defaults(), walkable = true, drop = "pipeworks:storage_tank_0", after_place_node = function(pos) pipeworks.look_for_stackable_tanks(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, }) end -- fountainhead minetest.register_node("pipeworks:fountainhead", { description = "Fountainhead", drawtype = "mesh", mesh = "pipeworks_fountainhead.obj", tiles = { "pipeworks_fountainhead.png" }, sunlight_propagates = true, paramtype = "light", groups = {snappy=3, pipe=1}, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, on_construct = function(pos) if mesecon then mesecon.receptor_on(pos, rules) end end, selection_box = { type = "fixed", fixed = { -2/16, -8/16, -2/16, 2/16, 8/16, 2/16 } }, collision_box = { type = "fixed", fixed = { -2/16, -8/16, -2/16, 2/16, 8/16, 2/16 } }, }) minetest.register_node("pipeworks:fountainhead_pouring", { description = "Fountainhead", drawtype = "mesh", mesh = "pipeworks_fountainhead.obj", tiles = { "pipeworks_fountainhead.png" }, sunlight_propagates = true, paramtype = "light", groups = {snappy=3, pipe=1, not_in_creative_inventory=1}, sounds = default.node_sound_wood_defaults(), walkable = true, after_place_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, after_dig_node = function(pos) pipeworks.scan_for_pipe_objects(pos) end, on_construct = function(pos) if mesecon then mesecon.receptor_on(pos, rules) end end, selection_box = { type = "fixed", fixed = { -2/16, -8/16, -2/16, 2/16, 8/16, 2/16 } }, collision_box = { type = "fixed", fixed = { -2/16, -8/16, -2/16, 2/16, 8/16, 2/16 } }, drop = "pipeworks:fountainhead" }) minetest.register_alias("pipeworks:valve_off_loaded", "pipeworks:valve_off_empty") minetest.register_alias("pipeworks:entry_panel", "pipeworks:entry_panel_empty")
unlicense
Taracque/epgp
modules/whisper.lua
1
4968
local mod = EPGP:NewModule("whisper", "AceEvent-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local senderMap = {} local senderBNMap = {} local SendChatMessage = _G.SendChatMessage if ChatThrottleLib then SendChatMessage = function(...) ChatThrottleLib:SendChatMessage("NORMAL", "EPGP", ...) end end function mod:CHAT_MSG_WHISPER(event_name, msg, sender) if not UnitInRaid("player") then return end if msg:sub(1, 12):lower() ~= 'epgp standby' then return end local member = msg:sub(13):match("([^ ]+)") if member then member = EPGP:FormatName(member) else member = sender end senderMap[member] = sender local eligible = EPGP:GetEPGP(member) if not eligible and not string.match(member,"-") then member = member .. "-" .. GetRealmName() eligible = EPGP:GetEPGP(member) end if not eligible then SendChatMessage(L["%s is not eligible for EP awards"]:format(member), "WHISPER", nil, sender) elseif EPGP:IsMemberInAwardList(member) then SendChatMessage(L["%s is already in the award list"]:format(member), "WHISPER", nil, sender) else EPGP:SelectMember(member) SendChatMessage(L["%s is added to the award list"]:format(member), "WHISPER", nil, sender) end end function mod:CHAT_MSG_BN_WHISPER(event_name, msg, sender,_,_,_,_,_,_,_,_,_,_,userID) if not UnitInRaid("player") then return end if msg:sub(1, 12):lower() ~= 'epgp standby' then return end local member = msg:sub(13):match("([^ ]+)") if member then member = EPGP:FormatName(member) else member = sender end senderBNMap[member] = userID local eligible = EPGP:GetEPGP(member) if not eligible and not string.match(member,"-") then member = member .. "-" .. GetRealmName() eligible = EPGP:GetEPGP(member) end if not eligible then BNSendWhisper(userID, L["%s is not eligible for EP awards"]:format(member)) elseif EPGP:IsMemberInAwardList(member) then BNSendWhisper(userID, L["%s is already in the award list"]:format(member)) else EPGP:SelectMember(member) BNSendWhisper(userID,L["%s is added to the award list"]:format(member)) end end local function AnnounceMedium() local medium = mod.db.profile.medium if medium ~= "NONE" then return medium end end local function SendNotifiesAndClearExtras( event_name, names, reason, amount, extras_awarded, extras_reason, extras_amount) local medium = AnnounceMedium() if medium then EPGP:GetModule("announce"):AnnounceTo( medium, L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"]) end if extras_awarded then for member,_ in pairs(extras_awarded) do local sender = senderMap[member] if sender then SendChatMessage(L["%+d EP (%s) to %s"]:format( extras_amount, extras_reason, member), "WHISPER", nil, sender) EPGP:DeSelectMember(member) SendChatMessage( L["%s is now removed from the award list"]:format(member), "WHISPER", nil, sender) end senderMap[member] = nil sender = senderBNMap[member] if sender then BNSendWhisper(sender,L["%+d EP (%s) to %s"]:format( extras_amount, extras_reason, member)) EPGP:DeSelectMember(member) BNSendWhisper( sender,L["%s is now removed from the award list"]:format(member)) end senderBNMap[member] = nil end end end mod.dbDefaults = { profile = { enabled = false, medium = "GUILD", } } function mod:OnInitialize() self.db = EPGP.db:RegisterNamespace("whisper", mod.dbDefaults) end mod.optionsName = L["Whisper"] mod.optionsDesc = L["Standby whispers in raid"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic handling of the standby list through whispers when in raid. When this is enabled, the standby list is cleared after each reward."], }, medium = { order = 10, type = "select", name = L["Announce medium"], desc = L["Sets the announce medium EPGP will use to announce EPGP actions."], values = { ["GUILD"] = CHAT_MSG_GUILD, ["CHANNEL"] = CUSTOM, ["NONE"] = NONE, }, }, } function mod:OnEnable() self:RegisterEvent("CHAT_MSG_WHISPER") self:RegisterEvent("CHAT_MSG_BN_WHISPER") EPGP.RegisterCallback(self, "MassEPAward", SendNotifiesAndClearExtras) EPGP.RegisterCallback(self, "StartRecurringAward", SendNotifiesAndClearExtras) end function mod:OnDisable() EPGP.UnregisterAllCallbacks(self) end
bsd-3-clause
kitala1/darkstar
scripts/zones/Buburimu_Peninsula/npcs/Stone_Monument.lua
32
1299
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos 320.755 -4.000 368.722 118 ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Buburimu_Peninsula/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x02000); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Wiladams/LJIT2libusb
USBDeviceReference.lua
1
3298
-- USBDeviceReference.lua --[[ The USBDeviceReference represents a reference to a USB device... That is, the device was attached to the system at some point, but whether or not is accessible at the moment is not assured. From the reference you can get some basic information, such as a description of the device. Most importantly, you can get a handle on something you can actually use to read and write from using: getActiveDevice() --]] local ffi = require("ffi") local usb = require("libusb") local usbvendordb = require("usbvendordb") local USBDevice = require("USBDevice") local USBDeviceReference = {} setmetatable(USBDeviceReference, { __call = function (self, ...) return self:new(...); end }) local USBDeviceReference_mt = { __index = USBDeviceReference; } function USBDeviceReference.init(self, devHandle) -- get the device descriptor local desc = ffi.new("struct libusb_device_descriptor"); local res = usb.libusb_get_device_descriptor(devHandle, desc); local configdesc = ffi.new("struct libusb_config_descriptor *[1]") local configres = usb.libusb_get_active_config_descriptor(devHandle, configdesc); if configres ~= 0 then return nil, "libusb_get_active_config_descriptor(), failed" end configdesc = configdesc[0]; ffi.gc(configdesc, usb.libusb_free_config_descriptor); local obj = { Handle = devHandle; -- Some raw data structures Description = desc; ActiveConfig = configdesc; -- Device class information Class = tonumber(desc.bDeviceClass); Subclass = tonumber(desc.bDeviceSubClass); Protocol = tonumber(desc.bDeviceProtocol); ClassDescription = usb.lookupClassDescriptor(desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol); } setmetatable(obj, USBDeviceReference_mt) obj.VendorId = tonumber(desc.idVendor); obj.ProductId = tonumber(desc.idProduct); obj.VendorName = usbvendordb[obj.VendorId].name; obj.ProductName = usbvendordb[obj.VendorId].products[tonumber(desc.idProduct)]; return obj; end function USBDeviceReference.new(self, devHandle) usb.libusb_ref_device(devHandle); ffi.gc(devHandle, usb.libusb_unref_device); return self:init(devHandle); end function USBDeviceReference.getActive(self) -- get handle local handle = ffi.new("libusb_device_handle*[1]") local res = usb.libusb_open(self.Handle, handle); if res ~= 0 then return nil, string.format("failed to open device: [%d]", res); end -- construct a USBDevice from the handle -- return that handle = handle[0]; ffi.gc(handle, usb.libusb_close) return USBDevice(handle) end function USBDeviceReference.getParent(self) local parentHandle = usb.libusb_get_parent(self.Handle); if parentHandle == nil then return nil; end return USBDeviceReference(parentHandle); end function USBDeviceReference.getAddress(self) local res = usb.libusb_get_device_address(self.Handle); return tonumber(res); end function USBDeviceReference.getBusNumber(self) local res = usb.libusb_get_bus_number(self.Handle); return tonumber(res); end function USBDeviceReference.getPortNumber(self) local res = usb.libusb_get_port_number(self.Handle); return res; end function USBDeviceReference.getNegotiatedSpeed(self) local res = usb.libusb_get_device_speed(self.Handle); return tonumber(res) end return USBDeviceReference;
mit
kitala1/darkstar
scripts/globals/spells/bluemagic/grand_slam.lua
27
1742
----------------------------------------- -- Spell: Grand Slam -- Delivers an area attack. Damage varies with TP -- Spell cost: 24 MP -- Monster Type: Beastmen -- Spell Type: Physical (Blunt) -- Blue Magic Points: 2 -- Stat Bonus: INT+1 -- Level: 30 -- Casting Time: 1 seconds -- Recast Time: 14.25 seconds -- Skillchain Element(s): Ice (can open Impaction, Compression, or Fragmentation; can close Induration) -- Combos: Defense Bonus ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ATTACK; params.dmgtype = DMGTYPE_BLUNT; params.scattr = SC_INDURATION; params.numhits = 1; params.multiplier = 1.0; params.tp150 = 1.0; params.tp300 = 1.0; params.azuretp = 1.0; params.duppercap = 133; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.3; params.agi_wsc = 0.0; params.int_wsc = 0.1; params.mnd_wsc = 0.1; params.chr_wsc = 0.1; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
Sean-Der/thrift
lib/lua/TServer.lua
74
3988
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- require 'Thrift' require 'TFramedTransport' require 'TBinaryProtocol' -- TServer TServer = __TObject:new{ __type = 'TServer' } -- 2 possible constructors -- 1. {processor, serverTransport} -- 2. {processor, serverTransport, transportFactory, protocolFactory} function TServer:new(args) if ttype(args) ~= 'table' then error('TServer must be initialized with a table') end if args.processor == nil then terror('You must provide ' .. ttype(self) .. ' with a processor') end if args.serverTransport == nil then terror('You must provide ' .. ttype(self) .. ' with a serverTransport') end -- Create the object local obj = __TObject.new(self, args) if obj.transportFactory then obj.inputTransportFactory = obj.transportFactory obj.outputTransportFactory = obj.transportFactory obj.transportFactory = nil else obj.inputTransportFactory = TFramedTransportFactory:new{} obj.outputTransportFactory = obj.inputTransportFactory end if obj.protocolFactory then obj.inputProtocolFactory = obj.protocolFactory obj.outputProtocolFactory = obj.protocolFactory obj.protocolFactory = nil else obj.inputProtocolFactory = TBinaryProtocolFactory:new{} obj.outputProtocolFactory = obj.inputProtocolFactory end -- Set the __server variable in the handler so we can stop the server obj.processor.handler.__server = self return obj end function TServer:setServerEventHandler(handler) self.serverEventHandler = handler end function TServer:_clientBegin(content, iprot, oprot) if self.serverEventHandler and type(self.serverEventHandler.clientBegin) == 'function' then self.serverEventHandler:clientBegin(iprot, oprot) end end function TServer:_preServe() if self.serverEventHandler and type(self.serverEventHandler.preServe) == 'function' then self.serverEventHandler:preServe(self.serverTransport:getSocketInfo()) end end function TServer:_handleException(err) if string.find(err, 'TTransportException') == nil then print(err) end end function TServer:serve() end function TServer:handle(client) local itrans, otrans, iprot, oprot, ret, err = self.inputTransportFactory:getTransport(client), self.outputTransportFactory:getTransport(client), self.inputProtocolFactory:getProtocol(client), self.outputProtocolFactory:getProtocol(client) self:_clientBegin(iprot, oprot) while true do ret, err = pcall(self.processor.process, self.processor, iprot, oprot) if ret == false and err then if not string.find(err, "TTransportException") then self:_handleException(err) end break end end itrans:close() otrans:close() end function TServer:close() self.serverTransport:close() end -- TSimpleServer -- Single threaded server that handles one transport (connection) TSimpleServer = __TObject:new(TServer, { __type = 'TSimpleServer', __stop = false }) function TSimpleServer:serve() self.serverTransport:listen() self:_preServe() while not self.__stop do client = self.serverTransport:accept() self:handle(client) end self:close() end function TSimpleServer:stop() self.__stop = true end
apache-2.0
crabman77/minetest-minetestforfun-server
mods/mobs/minotaur.lua
7
2618
-- Minotaur Monster by ??? mobs:register_mob("mobs:minotaur", { -- animal, monster, npc, barbarian type = "monster", -- aggressive, deals 11 damage to player when hit passive = false, attack_type = "dogfight", pathfinding = false, reach = 2, damage = 6, -- health & armor hp_min = 45, hp_max = 55, armor = 90, -- textures and model collisionbox = {-0.9,-0.01,-0.9, 0.9,2.5,0.9}, visual = "mesh", mesh = "mobs_minotaur.b3d", textures = { {"mobs_minotaur.png"}, }, visual_size = {x=1, y=1}, blood_texture = "mobs_blood.png", -- sounds makes_footstep_sound = true, -- sounds = { -- random = "mobs_zombie", -- damage = "mobs_zombie_hit", -- attack = "mobs_zombie_attack", -- death = "mobs_zombie_death", -- }, -- speed and jump walk_velocity = 1, run_velocity = 3, jump = true, floats = 1, view_range = 16, knock_back = 0.05, --this is a test -- drops desert_sand and coins when dead drops = { {name = "maptools:gold_coin", chance = 40, min = 1, max = 1,}, {name = "mobs:minotaur_eye", chance = 2, min = 1, max = 2,}, {name = "mobs:minotaur_horn", chance = 4, min = 1, max = 2,}, {name = "mobs:minotaur_fur", chance = 1, min = 1, max = 3,}, }, water_damage = 0, lava_damage = 5, light_damage = 0, -- model animation animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 19, walk_start = 20, walk_end = 39, run_start = 20, run_end = 39, punch_start = 40, punch_end = 50, }, }) -- spawns on desert sand between -1 and 20 light, 1 in 100000 chance, 1 Minotaur in area up to 31000 in height mobs:spawn_specific("mobs:minotaur", {"default:dirt_with_dry_grass"}, {"air"}, -1, 20, 30, 100000, 1, -31000, 31000, false) -- register spawn egg mobs:register_egg("mobs:minotaur", "Minotaur", "mobs_minotaur_inv.png", 1) minetest.register_craftitem("mobs:minotaur_eye", { description = "Minotaur Eye", inventory_image = "mobs_minotaur_eye.png", groups = {magic = 1}, }) minetest.register_craftitem("mobs:minotaur_horn", { description = "Minotaur Horn", inventory_image = "mobs_minotaur_horn.png", groups = {magic = 1}, }) minetest.register_craftitem("mobs:minotaur_fur", { description = "Minotaur Fur", inventory_image = "mobs_minotaur_fur.png", groups = {magic = 1}, }) minetest.register_craftitem("mobs:minotaur_lots_of_fur", { description = "Lot of Minotaur Fur", inventory_image = "mobs_minotaur_lots_of_fur.png", groups = {magic = 1}, }) minetest.register_craft({ output = "mobs:minotaur_lots_of_fur", recipe = {{"mobs:minotaur_fur", "mobs:minotaur_fur"}, {"mobs:minotaur_fur", "mobs:minotaur_fur"}, }, })
unlicense
d-o/LUA-LIB
C500Examples/external.lua
2
6339
#!/usr/bin/env lua ------------------------------------------------------------------------------- -- external -- -- Example of how to set up sockets for remote connections to this device -- To see things operating, telnet to port 1111 or 1112. ------------------------------------------------------------------------------- local rinApp = require "rinApp" -- load in the application framework local timers = require 'rinSystem.rinTimers' local sockets = require 'rinSystem.rinSockets' local dbg = require 'rinLibrary.rinDebug' --============================================================================= -- Connect to the instruments you want to control --============================================================================= local device = rinApp.addC500() -- make a connection to the instrument ------------------------------------------------------------------------------- -- Callback to handle PWR+ABORT key and end application device.setKeyCallback('pwr_cancel', rinApp.finish, 'long') ------------------------------------------------------------------------------- --============================================================================= -- Create a new socket on port 1111 that allows bidirection communications -- with an extenal device --============================================================================= ------------------------------------------------------------------------------- -- We need somewhere to keep the socket descriptor so we can send messages to it local bidirectionalSocket = nil -- Write to the bidirectional socket -- @param msg The message to write local function writeBidirectional(msg) if bidirectionalSocket ~= nil then sockets.writeSocket(bidirectionalSocket, msg) end end ------------------------------------------------------------------------------- -- Helper function to split the read string into separate lines. -- @param s The string to split -- @return Table of lines. Usually with a blank line at the end. local function split(s) local t = {} local function helper(line) table.insert(t, line) return "" end helper(s:gsub("(.-)\r?\n", helper)) return t end ------------------------------------------------------------------------------- -- Callback function for client connections on the bidirectional socket. -- @param sock Socket that has something ready to read. local function bidirectionalFromExternal(sock) local m, err = sockets.readSocket(sock) if err ~= nil then sockets.removeSocket(sock) bidirectionalSocket = nil else local lines = split(m) for i = 1, #lines do if lines[i] == "ping" then writeBidirectional("pong\r\n") end end end end ------------------------------------------------------------------------------- -- Three callback functions that are called when a new socket connection is -- established. These functions should add the socket to the sockets management -- module and set any required timouts local function socketBidirectionalAccept(sock, ip, port) if bidirectionalSocket ~= nil then dbg.info('second bidirectional connection from', ip, port) else bidirectionalSocket = sock sockets.addSocket(sock, bidirectionalFromExternal) sockets.setSocketTimeout(sock, 0.010) dbg.info('bidirectional connection from', ip, port) end end ------------------------------------------------------------------------------- -- Create the server socket sockets.createServerSocket(1111, socketBidirectionalAccept) --============================================================================= -- Create a new socket on port 1112 that allows unidirection communications -- to an extenal device --============================================================================= ------------------------------------------------------------------------------- -- Filter function on the outgoing data. -- @param sock The socket in question (you'll usually ignore this) -- @param msg The message to be filtered -- @return The message to be sent or nil for no message -- It is important to note that this function is called for things you -- write to the socket set as well as system messages. local function unidirectionFilter(sock, msg) -- We'll keep all messages that contain a capital G and discard the rest if string.find(msg, "G") ~= nil then return msg end -- Allow our own message but we change it to demonstrate message edit -- capabilities. if msg == "IDLE" then return " uni-idle " end return nil end ------------------------------------------------------------------------------- -- Callback when a new connection is incoming the unidirection data stream. -- @param sock The newly connected socket -- @param ip The source IP address of the socket -- @param port The source port of the socket local function socketUnidirectionalAccept(sock, ip, port) -- Set up so that all incoming traffic is ignored, this stream only -- does outgoings. Failure to do this will cause a build up of incoming -- data packets and blockage. sockets.addSocket(sock, sockets.flushReadSocket) -- Set a brief timeout to prevent things clogging up. sockets.setSocketTimeout(sock, 0.001) -- Add the socket to the unidirectional broadcast group. A message -- sent here is forwarded to all unidirectional sockets. -- We're using an inline filter function that just allows all traffic -- through, this function can return nil to prevent a message or something -- else to replace a message. sockets.addSocketSet("uni", sock, unidirectionFilter) -- Finally, log the fact that we've got a new connection dbg.info('unidirectional connection from', ip, port) end ------------------------------------------------------------------------------- -- Timer call back that injects extra information into the unidirection sockets local function unidirectionalTimedMessages() sockets.writeSet("uni", "IDLE") end ------------------------------------------------------------------------------- -- Create the server socket and timer timers.addTimer(1.324, 0.3, unidirectionalTimedMessages) sockets.createServerSocket(1112, socketUnidirectionalAccept) rinApp.run() -- run the application framework
gpl-3.0
lvdmaaten/nn
SpatialConvolutionMM.lua
27
3101
local SpatialConvolutionMM, parent = torch.class('nn.SpatialConvolutionMM', 'nn.Module') function SpatialConvolutionMM:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.padW = padW or 0 self.padH = padH or self.padW self.weight = torch.Tensor(nOutputPlane, nInputPlane*kH*kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane*kH*kW) self.gradBias = torch.Tensor(nOutputPlane) self.finput = torch.Tensor() self.fgradInput = torch.Tensor() self:reset() end function SpatialConvolutionMM:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end local function makeContiguous(self, input, gradOutput) if not input:isContiguous() then self._input = self._input or input.new() self._input:resizeAs(input):copy(input) input = self._input end if gradOutput then if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new() self._gradOutput:resizeAs(gradOutput):copy(gradOutput) gradOutput = self._gradOutput end end return input, gradOutput end function SpatialConvolutionMM:updateOutput(input) -- backward compatibility if self.padding then self.padW = self.padding self.padH = self.padding self.padding = nil end input = makeContiguous(self, input) return input.nn.SpatialConvolutionMM_updateOutput(self, input) end function SpatialConvolutionMM:updateGradInput(input, gradOutput) if self.gradInput then input, gradOutput = makeContiguous(self, input, gradOutput) return input.nn.SpatialConvolutionMM_updateGradInput(self, input, gradOutput) end end function SpatialConvolutionMM:accGradParameters(input, gradOutput, scale) input, gradOutput = makeContiguous(self, input, gradOutput) return input.nn.SpatialConvolutionMM_accGradParameters(self, input, gradOutput, scale) end function SpatialConvolutionMM:type(type) self.finput = torch.Tensor() self.fgradInput = torch.Tensor() return parent.type(self,type) end function SpatialConvolutionMM:__tostring__() local s = string.format('%s(%d -> %d, %dx%d', torch.type(self), self.nInputPlane, self.nOutputPlane, self.kW, self.kH) if self.dW ~= 1 or self.dH ~= 1 or self.padW ~= 0 or self.padH ~= 0 then s = s .. string.format(', %d,%d', self.dW, self.dH) end if (self.padW or self.padH) and (self.padW ~= 0 or self.padH ~= 0) then s = s .. ', ' .. self.padW .. ',' .. self.padH end return s .. ')' end
bsd-3-clause
kitala1/darkstar
scripts/zones/Wajaom_Woodlands/mobs/Hydra.lua
27
1283
----------------------------------- -- Area: Wajaom Woodlands -- NPC: Hydra -- @pos -282 -24 -1 51 ----------------------------------- require("scripts/globals/titles"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; function onMobFight(mob, target) local battletime = mob:getBattleTime(); local headgrow = mob:getLocalVar("headgrow"); local broken = mob:AnimationSub(); if (headgrow < battletime and broken > 0) then mob:AnimationSub(broken - 1); mob:setLocalVar("headgrow", battletime + 300); end end; function onCriticalHit(mob) local rand = math.random(); local battletime = mob:getBattleTime(); local headgrow = mob:getLocalVar("headgrow"); local headbreak = mob:getLocalVar("headbreak"); local broken = mob:AnimationSub(); if (rand <= 0.15 and battletime >= headbreak and broken < 2) then mob:AnimationSub(broken + 1); mob:setLocalVar("headgrow", battletime + math.random(120, 240)) mob:setLocalVar("headbreak", battletime + 300); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) killer:addTitle(HYDRA_HEADHUNTER); end;
gpl-3.0
fqrouter/luci
libs/web/luasrc/sauth.lua
78
2928
--[[ Session authentication (c) 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- --- LuCI session library. module("luci.sauth", package.seeall) require("luci.util") require("luci.sys") require("luci.config") local nixio = require "nixio", require "nixio.util" local fs = require "nixio.fs" luci.config.sauth = luci.config.sauth or {} sessionpath = luci.config.sauth.sessionpath sessiontime = tonumber(luci.config.sauth.sessiontime) or 15 * 60 --- Prepare session storage by creating the session directory. function prepare() fs.mkdir(sessionpath, 700) if not sane() then error("Security Exception: Session path is not sane!") end end local function _read(id) local blob = fs.readfile(sessionpath .. "/" .. id) return blob end local function _write(id, data) local f = nixio.open(sessionpath .. "/" .. id, "w", 600) f:writeall(data) f:close() end local function _checkid(id) return not not (id and #id == 32 and id:match("^[a-fA-F0-9]+$")) end --- Write session data to a session file. -- @param id Session identifier -- @param data Session data table function write(id, data) if not sane() then prepare() end assert(_checkid(id), "Security Exception: Session ID is invalid!") assert(type(data) == "table", "Security Exception: Session data invalid!") data.atime = luci.sys.uptime() _write(id, luci.util.get_bytecode(data)) end --- Read a session and return its content. -- @param id Session identifier -- @return Session data table or nil if the given id is not found function read(id) if not id or #id == 0 then return nil end assert(_checkid(id), "Security Exception: Session ID is invalid!") if not sane(sessionpath .. "/" .. id) then return nil end local blob = _read(id) local func = loadstring(blob) setfenv(func, {}) local sess = func() assert(type(sess) == "table", "Session data invalid!") if sess.atime and sess.atime + sessiontime < luci.sys.uptime() then kill(id) return nil end -- refresh atime in session write(id, sess) return sess end --- Check whether Session environment is sane. -- @return Boolean status function sane(file) return luci.sys.process.info("uid") == fs.stat(file or sessionpath, "uid") and fs.stat(file or sessionpath, "modestr") == (file and "rw-------" or "rwx------") end --- Kills a session -- @param id Session identifier function kill(id) assert(_checkid(id), "Security Exception: Session ID is invalid!") fs.unlink(sessionpath .. "/" .. id) end --- Remove all expired session data files function reap() if sane() then local id for id in nixio.fs.dir(sessionpath) do if _checkid(id) then -- reading the session will kill it if it is expired read(id) end end end end
apache-2.0
kitala1/darkstar
scripts/zones/Windurst_Woods/npcs/Mocchi_Katsartbih.lua
38
1048
----------------------------------- -- Area: Windurst Woods -- NPC: Mocchi Katsartbih -- Type: Standard NPC -- @zone: 241 -- @pos -13.225 -4.888 -164.108 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0108); 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
kitala1/darkstar
scripts/globals/abilities/altruism.lua
28
1176
----------------------------------- -- Ability: Altruism -- Increases the accuracy of your next White Magic spell. -- Obtained: Scholar Level 75 Tier 2 Merit Points -- Recast Time: Stratagem Charge -- Duration: 1 white magic spell or 60 seconds, whichever occurs first -- -- Level |Charges |Recharge Time per Charge -- ----- -------- --------------- -- 10 |1 |4:00 minutes -- 30 |2 |2:00 minutes -- 50 |3 |1:20 minutes -- 70 |4 |1:00 minute -- 90 |5 |48 seconds ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if player:hasStatusEffect(EFFECT_ALTRUISM) then return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0; end return 0,0; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) player:addStatusEffect(EFFECT_ALTRUISM,player:getMerit(MERIT_ALTRUISM),0,60); return EFFECT_ALTRUISM; end;
gpl-3.0
ZenityRTS/Zenity
libs/chiliui/luaui/chili/chili/controls/imagelistview.lua
3
7127
--//============================================================================= --- ImageListView module --- ImageListView fields. -- Inherits from LayoutPanel. -- @see layoutpanel.LayoutPanel -- @table ImageListView -- @string[opt=""] dir initial directory -- @tparam {func1,func2,...} OnDirChange table of function listeners for directory change (default {}) ImageListView = LayoutPanel:Inherit{ classname = "imagelistview", autosize = true, autoArrangeH = false, autoArrangeV = false, centerItems = false, iconX = 64, iconY = 64, itemMargin = {1, 1, 1, 1}, selectable = true, multiSelect = true, items = {}, dir = '', useRTT = false; OnDirChange = {}, } local this = ImageListView local inherited = this.inherited --//============================================================================= local image_exts = {'.jpg','.bmp','.png','.tga','.dds','.ico','.gif','.psd','.tif'} --'.psp' --//============================================================================= function ImageListView:New(obj) obj = inherited.New(self,obj) obj:SetDir(obj.dir) return obj end --//============================================================================= local function GetParentDir(dir) dir = dir:gsub("\\", "/") local lastChar = dir:sub(-1) if (lastChar == "/") then dir = dir:sub(1,-2) end local pos,b,e,match,init,n = 1,1,1,1,0,0 repeat pos,init,n = b,init+1,n+1 b,init,match = dir:find("/",init,true) until (not b) if (n==1) then return '' else return dir:sub(1,pos) end end local function ExtractFileName(filepath) filepath = filepath:gsub("\\", "/") local lastChar = filepath:sub(-1) if (lastChar == "/") then filepath = filepath:sub(1,-2) end local pos,b,e,match,init,n = 1,1,1,1,0,0 repeat pos,init,n = b,init+1,n+1 b,init,match = filepath:find("/",init,true) until (not b) if (n==1) then return filepath else return filepath:sub(pos+1) end end local function ExtractDir(filepath) filepath = filepath:gsub("\\", "/") local lastChar = filepath:sub(-1) if (lastChar == "/") then filepath = filepath:sub(1,-2) end local pos,b,e,match,init,n = 1,1,1,1,0,0 repeat pos,init,n = b,init+1,n+1 b,init,match = filepath:find("/",init,true) until (not b) if (n==1) then return filepath else return filepath:sub(1,pos) end end --//============================================================================= function ImageListView:_AddFile(name,imagefile) self:AddChild( LayoutPanel:New{ width = self.iconX+10, height = self.iconY+20, padding = {0,0,0,0}, itemPadding = {0,0,0,0}, itemMargin = {0,0,0,0}, rows = 2, columns = 1, useRTT = false; children = { Image:New{ width = self.iconX, height = self.iconY, passive = true, file = ':clr' .. self.iconX .. ',' .. self.iconY .. ':' .. imagefile, }, Label:New{ width = self.iconX+10, height = 20, align = 'center', autosize = false, caption = name, }, }, }) end function ImageListView:ScanDir() local files = VFS.DirList(self.dir) local dirs = VFS.SubDirs(self.dir) local imageFiles = {} for i=1,#files do local f = files[i] local ext = (f:GetExt() or ""):lower() if (table.ifind(image_exts,ext))then imageFiles[#imageFiles+1]=f end end self._dirsNum = #dirs self._dirList = dirs local n = 1 local items = self.items items[n] = '..' n = n+1 for i=1,#dirs do items[n],n=dirs[i],n+1 end for i=1,#imageFiles do items[n],n=imageFiles[i],n+1 end if (#items>n-1) then for i=n,#items do items[i] = nil end end self:DisableRealign() --// clear old self:ClearChildren() --// add ".." self:_AddFile('..',self.imageFolderUp) --// add dirs at top for i=1,#dirs do self:_AddFile(ExtractFileName(dirs[i]),self.imageFolder) end --// add files for i=1,#imageFiles do self:_AddFile(ExtractFileName(imageFiles[i]),imageFiles[i]) end self:EnableRealign() end function ImageListView:SetDir(directory) self:DeselectAll() self.dir = directory self:ScanDir() self:CallListeners(self.OnDirChange, directory) if (self.parent) then self.parent:RequestRealign() else self:UpdateLayout() self:Invalidate() end end function ImageListView:GoToParentDir() self:SetDir(GetParentDir(self.dir)) end function ImageListView:GotoFile(filepath) local dir = ExtractDir(filepath) local file = ExtractFileName(filepath) self.dir = dir self:ScanDir() self:Select(file) if (self.parent) then if (self.parent.classname == "scrollpanel") then local x,y,w,h = self:GetItemXY(next(self.selectedItems)) self.parent:SetScrollPos(x+w*0.5, y+h*0.5, true) end self.parent:RequestRealign() else self:UpdateLayout() self:Invalidate() end end --//============================================================================= function ImageListView:Select(item) if (type(item)=="number") then self:SelectItem(item) else local items = self.items for i=1,#items do if (ExtractFileName(items[i])==item) then self:SelectItem(i) return end end self:SelectItem(1) end end --//============================================================================= function ImageListView:DrawItemBkGnd(index) local cell = self._cells[index] local itemPadding = self.itemPadding if (self.selectedItems[index]) then self:DrawItemBackground(cell[1] - itemPadding[1],cell[2] - itemPadding[2],cell[3] + itemPadding[1] + itemPadding[3],cell[4] + itemPadding[2] + itemPadding[4],"selected") else self:DrawItemBackground(cell[1] - itemPadding[1],cell[2] - itemPadding[2],cell[3] + itemPadding[1] + itemPadding[3],cell[4] + itemPadding[2] + itemPadding[4],"normal") end end --//============================================================================= function ImageListView:HitTest(x,y) local cx,cy = self:LocalToClient(x,y) local obj = inherited.HitTest(self,cx,cy) if (obj) then return obj end local itemIdx = self:GetItemIndexAt(cx,cy) return (itemIdx>=0) and self end function ImageListView:MouseDblClick(x,y) local cx,cy = self:LocalToClient(x,y) local itemIdx = self:GetItemIndexAt(cx,cy) if (itemIdx<0) then return end if (itemIdx==1) then self:SetDir(GetParentDir(self.dir)) return self end if (itemIdx<=self._dirsNum+1) then self:SetDir(self._dirList[itemIdx-1]) return self else self:CallListeners(self.OnDblClickItem, self.items[itemIdx], itemIdx) return self end end --//=============================================================================
gpl-2.0
Taracque/epgp
libs/AceConfig-3.0/AceConfig-3.0.lua
12
2240
--- AceConfig-3.0 wrapper library. -- Provides an API to register an options table with the config registry, -- as well as associate it with a slash command. -- @class file -- @name AceConfig-3.0 -- @release $Id: AceConfig-3.0.lua 969 2010-10-07 02:11:48Z shefki $ --[[ AceConfig-3.0 Very light wrapper library that combines all the AceConfig subcomponents into one more easily used whole. ]] local MAJOR, MINOR = "AceConfig-3.0", 2 local AceConfig = LibStub:NewLibrary(MAJOR, MINOR) if not AceConfig then return end local cfgreg = LibStub("AceConfigRegistry-3.0") local cfgcmd = LibStub("AceConfigCmd-3.0") --TODO: local cfgdlg = LibStub("AceConfigDialog-3.0", true) --TODO: local cfgdrp = LibStub("AceConfigDropdown-3.0", true) -- Lua APIs local pcall, error, type, pairs = pcall, error, type, pairs -- ------------------------------------------------------------------- -- :RegisterOptionsTable(appName, options, slashcmd, persist) -- -- - appName - (string) application name -- - options - table or function ref, see AceConfigRegistry -- - slashcmd - slash command (string) or table with commands, or nil to NOT create a slash command --- Register a option table with the AceConfig registry. -- You can supply a slash command (or a table of slash commands) to register with AceConfigCmd directly. -- @paramsig appName, options [, slashcmd] -- @param appName The application name for the config table. -- @param options The option table (or a function to generate one on demand). http://www.wowace.com/addons/ace3/pages/ace-config-3-0-options-tables/ -- @param slashcmd A slash command to register for the option table, or a table of slash commands. -- @usage -- local AceConfig = LibStub("AceConfig-3.0") -- AceConfig:RegisterOptionsTable("MyAddon", myOptions, {"/myslash", "/my"}) function AceConfig:RegisterOptionsTable(appName, options, slashcmd) local ok,msg = pcall(cfgreg.RegisterOptionsTable, self, appName, options) if not ok then error(msg, 2) end if slashcmd then if type(slashcmd) == "table" then for _,cmd in pairs(slashcmd) do cfgcmd:CreateChatCommand(cmd, appName) end else cfgcmd:CreateChatCommand(slashcmd, appName) end end end
bsd-3-clause
Mechaniston/FibaroHC_mechHomeBcfg
BR_buttonWall (202, maxInst = 5).lua
1
8692
--[[ %% properties 323 sceneActivation %% globals --]] -- CONSTS -- local debugMode = true; local buttonID = 323; local lightBigRoomGenDevID = 40; local lightHall_KitchenGenDevID = 148; local lightBRLeftID = 41; local lightBRCenterID = 42; local lightBRRightID = 43; local lightBRBedID = 44; local lightKitchenID = 149; local lightHall_entID = 150; local lightHall_deepID = 151; local bedIsDownID = 205; local vdLightBRID = 195; local vdLightBRSwitchBtn = "6"; local vdLightKtnID = 196; local vdLightKtnSwitchBtn = "5"; local vdLightHllID = 207; local vdLightHllSwitchBtn = "5"; local lightValFullOn = "100"; -- set 100 val local lightValFOrNOn = "200"; -- turn on or night val local lightValHOrNOn = "150"; -- set half or night val - used for Hall -- button/BinSens scnActs codes local btnScnActOn = 10; -- toggle switch only local btnScnActOff = 11; -- toggle switch only local btnScnActClick = 16; -- momentary switch only local btnScnActDblClick = 14; local btnScnActTrplClick = 15; local btnScnActHold = 12; -- momentary switch only local btnScnActRelease = 13; -- momentary switch only local btnKind_OneTwo = 0; -- use 0 for 1st channel or 10 for 2nd channel -- GET ENVS -- local scrTrigger = fibaro:getSourceTrigger(); if ( scrTrigger["type"] ~= "property" ) then if ( debugMode ) then fibaro:debug("Incorrect call.. Abort!"); end fibaro:abort(); end fibaro:sleep(50); -- to prevent to kill all instances if ( fibaro:countScenes() > 1 ) then if ( debugMode ) then fibaro:debug("Double start" .. "(" .. tostring(fibaro:countScenes()) .. ").. Abort dup!"); end fibaro:abort(); end local sceneActID = tonumber(fibaro:getValue(buttonID, "sceneActivation")); if ( ((btnKind_OneTwo == 0) and (sceneActID >= 20)) or ((btnKind_OneTwo == 10) and (sceneActID < 20)) ) then if ( debugMode ) then fibaro:debug("Another button.. Abort!"); end fibaro:abort(); end local lightLeft = tonumber(fibaro:getValue(lightBRLeftID, "value")); local lightCenter = tonumber(fibaro:getValue(lightBRCenterID, "value")); local lightRight = tonumber(fibaro:getValue(lightBRRightID, "value")); local lightBed = tonumber(fibaro:getValue(lightBRBedID, "value")); local lightKitchen = tonumber(fibaro:getValue(lightKitchenID, "value")); local lightHallE = tonumber(fibaro:getValue(lightHall_entID, "value")); local lightHallD = tonumber(fibaro:getValue(lightHall_deepID, "value")); local bedIsDown = tonumber(fibaro:getValue(bedIsDownID, "value")); local btnMode, btnModeMT = fibaro:getGlobal("BRbtnWallMode"); if ( debugMode ) then fibaro:debug( "lL = " .. tostring(lightLeft) .. ", " .. "lC = " .. tostring(lightCenter) .. ", " .. "lR = " .. tostring(lightRight) .. ", " .. "lB = " .. tostring(lightBed) .. ", " .. "lK = " .. tostring(lightKitchen) .. ", " .. "lHe = " .. tostring(lightHallE) .. ", " .. "lHd = " .. tostring(lightHallD) ); fibaro:debug( "bedIsDown = " .. tostring(bedIsDown) .. ", " .. "btnMode = " .. btnMode .. ", " .. "btnModeMT = " .. btnModeMT .. ", " .. "curtime = " .. os.time() ); fibaro:debug( "sceneActID = " .. tostring(sceneActID) .. ", " .. "btnValue = " .. fibaro:getValue(buttonID, "value") ); end -- PROCESS -- local lightsActions = ""; if ( (sceneActID == btnScnActClick + btnKind_OneTwo) or (sceneActID == btnScnActOn + btnKind_OneTwo) or (sceneActID == btnScnActOff + btnKind_OneTwo) ) then --------------------- if ( (btnMode == "HK") and (os.time() - btnModeMT <= 10) ) then if ( (lightKitchen == 0) and (lightHallE == 0) and (lightHallD == 0) ) then fibaro:call(vdLightKtnID, "pressButton", vdLightKtnSwitchBtn); fibaro:call(vdLightHllID, "pressButton", vdLightHllSwitchBtn); else fibaro:call(vdLightKtnID, "pressButton", vdLightKtnOffBtn); fibaro:call(vdLightHllID, "pressButton", vdLightHllOffBtn); end else fibaro:call(vdLightBRID, "pressButton", vdLightBRSwitchBtn); end elseif ( sceneActID == btnScnActDblClick + btnKind_OneTwo ) then -------------- -- v.2 - with btnMode --TODO: change btnMode if ( (btnMode == "HK") and (os.time() - btnModeMT <= 10) ) then -- v.1 - with timeout changeing mode --[[local val1, DT1 = fibaro:get(lightBigRoomGenDevID, "value"); local val2, DT2 = fibaro:get(lightHall_KitchenGenDevID, "value"); if ( debugMode ) then fibaro:debug("val1 = ".. val1 .. ", val2 = " .. val2); end if ( (DT2 > DT1) and (os.time() - DT2 < 6) ) then -- Ê_Õ light was switched -- during last 5 sec --]] -- change Ê_Õ lights if ( lightKitchen > 0 ) then if ( (lightHallE > 0) or (lightHallD > 0) ) then lightsActions = lightHall_entID .. "," .. lightValHOrNOn .. ";" .. lightHall_deepID .. ",0" .. lightKitchenID .. ",0"; else lightsActions = lightHall_entID .. "," .. tostring(lightKitchen) .. ";" .. lightKitchenID .. ",0"; end else if ( lightHallD > 0 ) then lightsActions = lightKitchenID .. "," .. tostring(lightHallD) .. ";" .. lightHall_entID .. "," .. tostring(lightHallD) .. ";"; elseif ( lightHallE > 0 ) then lightsActions = lightKitchenID .. "," .. tostring(lightHallE) .. ";" .. lightHall_deepID .. "," .. tostring(lightHallE) .. ";"; else fibaro:call(vdLightKtnID, "pressButton", vdLightKtnSwitchBtn); fibaro:call(vdLightHllID, "pressButton", vdLightHllSwitchBtn); end end else -- change ÁÊ lights --[[ if ( (lightBed == 0) and bedIsDown ) then lightsActions = lightBRBedID .. "," .. lightValFOrNOn .. ";"; else if ( lightBed > 0 ) then lightsActions = lightBRBedID .. ",0;"; end if ( (lightLeft > 0) and (lightCenter > 0) and (lightRight > 0) ) then lightsActions = lightsActions .. tostring(lightBRCenterID).. ",0;"; elseif ( (lightLeft > 0) and (lightCenter == 0) and (lightRight > 0) ) then lightsActions = lightsActions .. lightBRCenterID .. "," .. tostring(lightLeft) .. ";" .. lightBRLeftID .. ",0;" .. lightBRRightID .. ",0;"; elseif ( (lightLeft == 0) and (lightCenter > 0) and (lightRight == 0) ) then lightsActions = lightsActions .. lightBRLeftID .. "," .. tostring(lightCenter) .. ";" .. lightBRLeftID .. ",0"; elseif ( (lightLeft > 0) and (lightCenter == 0) and (lightRight == 0) ) then lightsActions = lightsActions .. lightBRRightID .. "," .. tostring(lightLeft) .. ";" .. lightBRLeftID .. ",0"; elseif ( (lightLeft == 0) and (lightCenter == 0) and (lightRight > 0) ) then if ( lightBed == 0 ) then lightsActions = lightsActions .. lightBRBedID .. "," .. lightValFOrNOn .. ";" .. lightBRRightID .. ",0"; else lightsActions = lightsActions .. lightBRLeftID .. "," .. tostring(lightRight) .. ";" .. lightBRCenterID .. "," .. tostring(lightRight) .. ";"; end else lightsActions = lightsActions .. lightBRLeftID .. "," .. lightValFOrNOn .. ";" .. lightBRCenterID .. "," .. lightValFOrNOn .. ";" .. lightBRRightID .. "," .. lightValFOrNOn .. ";"; end end --]] end if ( debugMode ) then fibaro:debug("lightsActions = <" .. lightsActions .. ">"); end elseif ( sceneActID == btnScnActTrplClick + btnKind_OneTwo ) then ------------- --fibaro:setGlobal("BRbtnWallMode", "HK"); fibaro:call(vdLightHllID, "pressButton", vdLightHllSwitchBtn); --[[if ( lightKitchen == 0 ) then if ( lightHall == 0 ) then lightsActions = lightKitchenID .. "," .. lightValFOrNOn .. ";" .. lightHallID .. "," .. lightValHOrNOn .. ";"; else lightsActions = lightKitchenID .. "," .. lightValFOrNOn .. ";"; end else if ( lightHall == 0 ) then lightsActions = lightHallID .. "," .. lightValHOrNOn .. ";"; else lightsActions = lightKitchenID .. ",0;" .. lightHallID .. ",0;"; end end--]] end if ( lightsActions ~= "" ) then fibaro:setGlobal("lightsQueue", fibaro:getGlobalValue("lightsQueue") .. lightsActions); end
mit
tetoali605/THETETOO_A7A
plugins/admin.lua
7
10194
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY tetoo ▀▄ ▄▀ ▀▄ ▄▀ BY nmore (@l_l_lo) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY l_l_ll ▀▄ ▄▀ ▀▄ ▄▀ broadcast : الاوامـــر ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end --Function to add log supergroup local function logadd(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local GBan_log = 'GBan_log' if not data[tostring(GBan_log)] then data[tostring(GBan_log)] = {} save_data(_config.moderation.data, data) end data[tostring(GBan_log)][tostring(msg.to.id)] = msg.to.peer_id save_data(_config.moderation.data, data) local text = 'Log_SuperGroup has has been set!' reply_msg(msg.id,text,ok_cb,false) return end --Function to remove log supergroup local function logrem(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local GBan_log = 'GBan_log' if not data[tostring(GBan_log)] then data[tostring(GBan_log)] = nil save_data(_config.moderation.data, data) end data[tostring(GBan_log)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local text = 'Log_SuperGroup has has been removed!' reply_msg(msg.id,text,ok_cb,false) return end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairsByKeys(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function reload_plugins( ) plugins = {} return load_plugins() end local function run(msg,matches) local receiver = get_receiver(msg) local group = msg.to.id local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") if not is_admin1(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "Msg sent" end if matches[1] == "pmblock" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "pmunblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then if not is_sudo(msg) then-- Sudo only return end get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then if not is_sudo(msg) then-- Sudo only return end del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent a group dialog list with both json and text format to your private messages" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end if matches[1] == "sync_gbans" then if not is_sudo(msg) then-- Sudo only return end local url = "http://seedteam.org/Teleseed/Global_bans.json" local SEED_gbans = http.request(url) local jdat = json:decode(SEED_gbans) for k,v in pairs(jdat) do redis:hset('user:'..v, 'print_name', k) banall_user(v) print(k, v.." Globally banned") end end if matches[1] == 'reload' then receiver = get_receiver(msg) reload_plugins(true) post_msg(receiver, "Reloaded!", ok_cb, false) return "Reloaded!" end --[[*For Debug* if matches[1] == "vardumpmsg" and is_admin1(msg) then local text = serpent.block(msg, {comment=false}) send_large_msg("channel#id"..msg.to.id, text) end]] if matches[1] == 'updateid' then local data = load_data(_config.moderation.data) local long_id = data[tostring(msg.to.id)]['long_id'] if not long_id then data[tostring(msg.to.id)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) return "Updated ID" end end if matches[1] == 'addlog' and not matches[2] then if is_log_group(msg) then return "Already a Log_SuperGroup" end print("Log_SuperGroup "..msg.to.title.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log_SuperGroup") logadd(msg) end if matches[1] == 'remlog' and not matches[2] then if not is_log_group(msg) then return "Not a Log_SuperGroup" end print("Log_SuperGroup "..msg.to.title.."("..msg.to.id..") removed") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log_SuperGroup") logrem(msg) end return end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^[#!/](pm) (%d+) (.*)$", "^[#!/](import) (.*)$", "^[#!/](pmunblock) (%d+)$", "^[#!/](pmblock) (%d+)$", "^[#!/](markread) (on)$", "^[#!/](markread) (off)$", "^[#!/](setbotphoto)$", "^[#!/](contactlist)$", "^[#!/](dialoglist)$", "^[#!/](delcontact) (%d+)$", "^[#/!](reload)$", "^[#/!](updateid)$", "^[#/!](addlog)$", "^[#/!](remlog)$", "%[(photo)%]", }, run = run, pre_process = pre_process } --By @imandaneshi :) --https://github.com/SEEDTEAM/TeleSeed/blob/test/plugins/admin.lua ---Modified by @Rondoozle for supergroups
gpl-2.0
fastmailops/prosody
plugins/mod_http_errors.lua
4
2068
module:set_global(); local server = require "net.http.server"; local codes = require "net.http.codes"; local show_private = module:get_option_boolean("http_errors_detailed", false); local always_serve = module:get_option_boolean("http_errors_always_show", true); local default_message = { module:get_option_string("http_errors_default_message", "That's all I know.") }; local default_messages = { [400] = { "What kind of request do you call that??" }; [403] = { "You're not allowed to do that." }; [404] = { "Whatever you were looking for is not here. %"; "Where did you put it?", "It's behind you.", "Keep looking." }; [500] = { "% Check your error log for more info."; "Gremlins.", "It broke.", "Don't look at me." }; }; local messages = setmetatable(module:get_option("http_errors_messages", {}), { __index = default_messages }); local html = [[ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body{ margin-top:14%; text-align:center; background-color:#F8F8F8; font-family:sans-serif; } h1{ font-size:xx-large; } p{ font-size:x-large; } p+p { font-size: large; font-family: courier } </style> </head> <body> <h1>$title</h1> <p>$message</p> <p>$extra</p> </body> </html>]]; html = html:gsub("%s%s+", ""); local entities = { ["<"] = "&lt;", [">"] = "&gt;", ["&"] = "&amp;", ["'"] = "&apos;", ["\""] = "&quot;", ["\n"] = "<br/>", }; local function tohtml(plain) return (plain:gsub("[<>&'\"\n]", entities)); end local function get_page(code, extra) local message = messages[code]; if always_serve or message then message = message or default_message; return (html:gsub("$(%a+)", { title = rawget(codes, code) or ("Code "..tostring(code)); message = message[1]:gsub("%%", function () return message[math.random(2, math.max(#message,2))]; end); extra = tohtml(extra or ""); })); end end module:hook_object_event(server, "http-error", function (event) return get_page(event.code, (show_private and event.private_message) or event.message); end);
mit
kitala1/darkstar
scripts/zones/Bastok_Markets/npcs/Ulrike.lua
53
1816
----------------------------------- -- Area: Bastok Markets -- NPC: Ulrike -- Type: Goldsmithing Synthesis Image Support -- @pos -218.399 -7.824 -56.203 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,6); local SkillCap = getCraftSkillCap(player, SKILL_GOLDSMITHING); local SkillLevel = player:getSkillLevel(SKILL_GOLDSMITHING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_GOLDSMITHING_IMAGERY) == false) then player:startEvent(0x0130,SkillCap,SkillLevel,2,201,player:getGil(),0,9,0); else player:startEvent(0x0130,SkillCap,SkillLevel,2,201,player:getGil(),6975,9,0); end else player:startEvent(0x0130); 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 == 0x0130 and option == 1) then player:messageSpecial(GOLDSMITHING_SUPPORT,0,3,2); player:addStatusEffect(EFFECT_GOLDSMITHING_IMAGERY,1,0,120); end end;
gpl-3.0
fpkaliii/kdrugs
lua/kdrugs/sv_kdrugs.lua
1
1343
util.AddNetworkString("kdrugs") util.AddNetworkString("kdrugs.lab") AddCSLuaFile("cl_kdrugs.lua") AddCSLuaFile("sh_kdrugs.lua") AddCSLuaFile("kdrugs_config.lua") kdrugs = {} include("kdrugs_config.lua") include("sh_kdrugs.lua") function kdrugs.think() local curtime = CurTime() for k,v in next, player.GetAll() do if !v.kdrugs then continue end for id, tab in next, v.kdrugs do local drug = kdrugs.drugs[id] if tab.time + drug.time + drug.atime >= curtime and v:Alive() then if drug.Start and !tab.started and tab.time + drug.time >= curtime then drug:Start(v, tab.extra) tab.started = true elseif drug.End and tab.started and curtime >= tab.time + drug.time then drug:End(v, tab.extra + 1) tab.started = false end else v.kdrugs[id] = nil if drug.EndAfterEffects then drug:EndAfterEffects(v, tab.extra + 1) end end end end end function kdrugs.startcommand(ply, cmd) local curtime = CurTime() if ply.kdrugs then for id, tab in next, ply.kdrugs do local drug = kdrugs.drugs[id] if drug.AlterMovement and (tab.time + drug.time + drug.atime) >= curtime and ply:Alive() then drug:AlterMovement(ply, tab.extra) end end end end kdrugs.load() hook.Add("Think", "kdrugs.think", kdrugs.think) hook.Add("StartCommand", "kdrugs.startcommand", kdrugs.startcommand)
mit
kitala1/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Galzweesh.lua
34
1034
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Galzweesh -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0292); 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
kitala1/darkstar
scripts/zones/Boneyard_Gully/bcnms/head_wind.lua
13
1700
----------------------------------- -- Area: Boneyard_Gully -- Name: head_wind -- BCNM: 672 ----------------------------------- package.loaded["scripts/zones/Boneyard_Gully/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Boneyard_Gully/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 5) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); player:setVar("COP_Ulmia_s_Path",6); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); end elseif(leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if(csid == 0x7d01)then player:addExp(1000); end end;
gpl-3.0
nicodinh/cuberite
lib/tolua++/src/bin/lua/clean.lua
64
1336
-- mark up comments and strings STR1 = "\001" STR2 = "\002" STR3 = "\003" STR4 = "\004" REM = "\005" ANY = "([\001-\005])" ESC1 = "\006" ESC2 = "\007" MASK = { -- the substitution order is important {ESC1, "\\'"}, {ESC2, '\\"'}, {STR1, "'"}, {STR2, '"'}, {STR3, "%[%["}, {STR4, "%]%]"}, {REM , "%-%-"}, } function mask (s) for i = 1,getn(MASK) do s = gsub(s,MASK[i][2],MASK[i][1]) end return s end function unmask (s) for i = 1,getn(MASK) do s = gsub(s,MASK[i][1],MASK[i][2]) end return s end function clean (s) -- check for compilation error local code = "return function ()\n" .. s .. "\n end" if not dostring(code) then return nil end if flags['C'] then return s end local S = "" -- saved string s = mask(s) -- remove blanks and comments while 1 do local b,e,d = strfind(s,ANY) if b then S = S..strsub(s,1,b-1) s = strsub(s,b+1) if d==STR1 or d==STR2 then e = strfind(s,d) S = S ..d..strsub(s,1,e) s = strsub(s,e+1) elseif d==STR3 then e = strfind(s,STR4) S = S..d..strsub(s,1,e) s = strsub(s,e+1) elseif d==REM then s = gsub(s,"[^\n]*(\n?)","%1",1) end else S = S..s break end end -- eliminate unecessary spaces S = gsub(S,"[ \t]+"," ") S = gsub(S,"[ \t]*\n[ \t]*","\n") S = gsub(S,"\n+","\n") S = unmask(S) return S end
apache-2.0
rm-code/love-atom
generator/json-generator.lua
1
6732
local json = require 'dkjson' -- ------------------------------------------------ -- Constants -- ------------------------------------------------ local OUTPUT_FILE = 'love-completions.json' local WIKI_URL = 'https://love2d.org/wiki/' local LOVE_MODULE_STRING = 'love.' -- JSON Output control local DEBUG = false local KEY_ORDER = { 'luaVersion', 'packagePath', 'global', 'namedTypes', 'type', 'description', 'fields', 'args', 'returnTypes', 'link' } local NOARGS = {} -- ------------------------------------------------ -- Local Functions -- ------------------------------------------------ --- -- Generates a sequence containing subtables of all the arguments -- local function createArguments( args, isMethod ) local arguments = {} -- Include a "self" argument for methods, since autocomplete-lua and Lua itself -- omits the first argument of methods preceeded by the : operator if isMethod then arguments[#arguments + 1] = {} arguments[#arguments].name = 'self' end for _, v in ipairs( args or NOARGS ) do arguments[#arguments + 1] = {} arguments[#arguments].name = v.name -- Use [foo] notation as display name for optional arguments. if v.default then arguments[#arguments].displayName = string.format( '[%s]', v.name ) end end return arguments end local function getType( type ) if type == 'string' or type == 'number' or type == 'table' or type == 'boolean' or type == 'function' then return { type = type } end return { type = 'ref', name = type } end local function createReturnTypes( returns ) local returnTypes = {} for i, v in ipairs( returns ) do returnTypes[i] = getType( v.type ) end return returnTypes end -- TODO handle functions with neither args nor return variables. local function createVariant( vdef, isMethod ) local variant = {} variant.description = vdef.description variant.args = createArguments( vdef.arguments, isMethod ) return variant end local function createFunction( f, parent, moduleString, isMethod ) local name = f.name parent[name] = {} parent[name].type = 'function' parent[name].link = string.format( "%s%s%s", WIKI_URL, moduleString, name ) -- NOTE Currently atom-autocomplete-lua doesn't support return types which -- have been defined inside of variants. So for now we only use the -- return types of the first variant. -- @see https://github.com/dapetcu21/atom-autocomplete-lua/issues/15 if f.variants[1].returns then parent[name].returnTypes = createReturnTypes( f.variants[1].returns ) end -- Create normal function if there is just one variant. if #f.variants == 1 then local v = createVariant( f.variants[1], isMethod ) parent[name].description = f.description parent[name].args = v.args return end -- Generate multiple variants. parent[name].variants = {} for i, v in ipairs( f.variants ) do local variant = createVariant( v, isMethod ) -- Use default description if there is no specific variant description. if not variant.description then variant.description = f.description end parent[name].variants[i] = variant end end local function createLoveFunctions( functions, parent ) for _, f in pairs( functions ) do createFunction( f, parent, LOVE_MODULE_STRING ) end end local function createLoveModuleFunctions( modules, parent ) for _, m in pairs( modules ) do local name = m.name parent[name] = {} parent[name].type = 'table' parent[name].description = m.description parent[name].link = string.format( "%s%s%s", WIKI_URL, LOVE_MODULE_STRING, name ) parent[name].fields = {} for _, f in pairs( m.functions ) do createFunction( f, parent[name].fields, string.format( '%s%s.', LOVE_MODULE_STRING, name )) end end end local function createGlobals( api, global ) global.type = 'table' global.fields = {} global.fields.love = {} global.fields.love.type = 'table' global.fields.love.fields = {} createLoveFunctions( api.functions, global.fields.love.fields ) createLoveFunctions( api.callbacks, global.fields.love.fields ) createLoveModuleFunctions( api.modules, global.fields.love.fields ) end -- ------------------------------------------------ -- Creation methods for named types -- ------------------------------------------------ local function collectTypes( api ) local types = {} for _, type in pairs( api.types ) do assert( not types[type.name] ) types[type.name] = type end for _, module in pairs( api.modules ) do if module.types then -- Not all modules define types. for _, type in pairs( module.types ) do assert( not types[type.name] ) types[type.name] = type end end end return types end local function createTypes( types, namedTypes ) for name, type in pairs( types ) do print( ' ' .. name ) namedTypes[name] = {} namedTypes[name].type = 'table' namedTypes[name].fields = {} if type.functions then for _, f in pairs( type.functions ) do createFunction( f, namedTypes[name].fields, name .. ':', true ) end end if type.supertypes then namedTypes[name].metatable = {} namedTypes[name].metatable.type = 'table' namedTypes[name].metatable.fields = { __index = { type = 'ref', name = type.parenttype } } end end end local function createJSON() print( 'Generating LOVE snippets ... ' ) -- Load the LÖVE api files. local api = require( 'api.love_api' ) assert( api, 'No api file found!' ) print( 'Found API file for LÖVE version ' .. api.version ) -- Create main table. local output = { global = {}, namedTypes = {}, packagePath = "./?.lua,./?/init.lua" } print( 'Generating functions ...' ) createGlobals( api, output.global ) print( 'Generating types ...' ) local types = collectTypes( api ) createTypes( types, output.namedTypes ) local jsonString = json.encode( output, { indent = DEBUG, keyorder = KEY_ORDER }) local file = io.open( OUTPUT_FILE, 'w' ) assert( file, "ERROR: Can't write file: " .. OUTPUT_FILE ) file:write( jsonString ) print( 'DONE!' ) end createJSON()
mit
kitala1/darkstar
scripts/zones/Sacrificial_Chamber/npcs/_4j4.lua
12
1340
----------------------------------- -- Area: Sacrificial Chamber -- NPC: Mahogany Door -- @pos 300 30 -324 163 ------------------------------------- package.loaded["scripts/zones/Sacrificial_Chamber/TextIDs"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/missions"); require("scripts/zones/Sacrificial_Chamber/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(TradeBCNM(player,player:getZoneID(),trade,npc))then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(EventTriggerBCNM(player,npc))then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if(EventUpdateBCNM(player,csid,option))then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if(EventFinishBCNM(player,csid,option))then return; end end;
gpl-3.0
kitala1/darkstar
scripts/globals/abilities/pets/healing_breath_i.lua
2
1269
--------------------------------------------------- -- Healing Breath I --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill, master) -- TODO: Correct base value (45/256). See Healing Breath III for details. ---------- Deep Breathing ---------- -- 0 for none -- 1 for first merit -- 0.25 for each merit after the first -- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*) local deep = 0; if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then deep = 1+((master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25); pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST); end local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath local base = math.floor((45/256)*(1+(pet:getTP()/1024))*(pet:getHP())+42); if(target:getHP()+base > target:getMaxHP()) then base = target:getMaxHP() - target:getHP(); --cap it end skill:setMsg(MSG_SELF_HEAL); target:addHP(base); return base; end
gpl-3.0
kitala1/darkstar
scripts/zones/Dynamis-San_dOria/mobs/Overlord_s_Tombstone.lua
11
1409
----------------------------------- -- Area: Dynamis San d'Oria -- NPC: Overlord's Tombstone ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/dynamis"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) SpawnMob(17535350):updateEnmity(target); -- 110 SpawnMob(17535351):updateEnmity(target); -- 111 SpawnMob(17535352):updateEnmity(target); -- 112 SpawnMob(17535354):updateEnmity(target); -- 114 SpawnMob(17534978):updateEnmity(target); -- Battlechoir Gitchfotch SpawnMob(17534979):updateEnmity(target); -- Soulsender Fugbrag end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if(alreadyReceived(killer,8) == false) then addDynamisList(killer,128); killer:addTitle(DYNAMISSAN_DORIA_INTERLOPER); -- Add title local npc = GetNPCByID(17535224); -- Spawn ??? npc:setPos(mob:getXPos(),mob:getYPos(),mob:getZPos()); npc:setStatus(0); killer:launchDynamisSecondPart(); -- Spawn dynamis second part end for i = 17534978, 17534979 do if (GetMobAction(i) ~= 0) then DespawnMob(i); end end end;
gpl-3.0
NiFiLocal/nifi-minifi-cpp
thirdparty/civetweb-1.10/test/1000images.lua
11
8259
mg.write("HTTP/1.1 200 OK\r\n") mg.write("Connection: close\r\n") mg.write("Content-Type: text/html; charset=utf-8\r\n") mg.write("\r\n") t = os.time() if not mg.request_info.query_string then cnt = 1000 else cnt = tonumber(mg.get_var(mg.request_info.query_string, "cnt")) end cnt = 100*math.floor(cnt/100) mg.write([[ <html> <head> <title>]] .. cnt .. [[ images</title> <script type="text/javascript"> var startLoad = Date.now(); window.onload = function () { var loadTime = (Date.now()-startLoad) + " ms"; document.getElementById('timing').innerHTML = loadTime; } </script> </head> <body> <h1>A large gallery of small images:</h1> <p> ]]) for s=0,(cnt/100)-1 do local ts = (tostring(t) .. tostring(s)) mg.write([[ <h2>page ]]..s..[[</h2> <table> <tr> <td><img src="imagetest/00.png?ts=]]..ts..[["></td> <td><img src="imagetest/01.png?ts=]]..ts..[["></td> <td><img src="imagetest/02.png?ts=]]..ts..[["></td> <td><img src="imagetest/03.png?ts=]]..ts..[["></td> <td><img src="imagetest/04.png?ts=]]..ts..[["></td> <td><img src="imagetest/05.png?ts=]]..ts..[["></td> <td><img src="imagetest/06.png?ts=]]..ts..[["></td> <td><img src="imagetest/07.png?ts=]]..ts..[["></td> <td><img src="imagetest/08.png?ts=]]..ts..[["></td> <td><img src="imagetest/09.png?ts=]]..ts..[["></td> </tr> ]]) mg.write([[ <tr> <td><img src="imagetest/10.png?ts=]]..ts..[["></td> <td><img src="imagetest/11.png?ts=]]..ts..[["></td> <td><img src="imagetest/12.png?ts=]]..ts..[["></td> <td><img src="imagetest/13.png?ts=]]..ts..[["></td> <td><img src="imagetest/14.png?ts=]]..ts..[["></td> <td><img src="imagetest/15.png?ts=]]..ts..[["></td> <td><img src="imagetest/16.png?ts=]]..ts..[["></td> <td><img src="imagetest/17.png?ts=]]..ts..[["></td> <td><img src="imagetest/18.png?ts=]]..ts..[["></td> <td><img src="imagetest/19.png?ts=]]..ts..[["></td> </tr> ]]) mg.write([[ <tr> <td><img src="imagetest/20.png?ts=]]..ts..[["></td> <td><img src="imagetest/21.png?ts=]]..ts..[["></td> <td><img src="imagetest/22.png?ts=]]..ts..[["></td> <td><img src="imagetest/23.png?ts=]]..ts..[["></td> <td><img src="imagetest/24.png?ts=]]..ts..[["></td> <td><img src="imagetest/25.png?ts=]]..ts..[["></td> <td><img src="imagetest/26.png?ts=]]..ts..[["></td> <td><img src="imagetest/27.png?ts=]]..ts..[["></td> <td><img src="imagetest/28.png?ts=]]..ts..[["></td> <td><img src="imagetest/29.png?ts=]]..ts..[["></td> </tr> ]]) mg.write([[ <tr> <td><img src="imagetest/20.png?ts=]]..ts..[["></td> <td><img src="imagetest/21.png?ts=]]..ts..[["></td> <td><img src="imagetest/22.png?ts=]]..ts..[["></td> <td><img src="imagetest/23.png?ts=]]..ts..[["></td> <td><img src="imagetest/24.png?ts=]]..ts..[["></td> <td><img src="imagetest/25.png?ts=]]..ts..[["></td> <td><img src="imagetest/26.png?ts=]]..ts..[["></td> <td><img src="imagetest/27.png?ts=]]..ts..[["></td> <td><img src="imagetest/28.png?ts=]]..ts..[["></td> <td><img src="imagetest/29.png?ts=]]..ts..[["></td> </tr> ]]) mg.write([[ <tr> <td><img src="imagetest/30.png?ts=]]..ts..[["></td> <td><img src="imagetest/31.png?ts=]]..ts..[["></td> <td><img src="imagetest/32.png?ts=]]..ts..[["></td> <td><img src="imagetest/33.png?ts=]]..ts..[["></td> <td><img src="imagetest/34.png?ts=]]..ts..[["></td> <td><img src="imagetest/35.png?ts=]]..ts..[["></td> <td><img src="imagetest/36.png?ts=]]..ts..[["></td> <td><img src="imagetest/37.png?ts=]]..ts..[["></td> <td><img src="imagetest/38.png?ts=]]..ts..[["></td> <td><img src="imagetest/39.png?ts=]]..ts..[["></td> </tr> ]]) mg.write([[ <tr> <td><img src="imagetest/40.png?ts=]]..ts..[["></td> <td><img src="imagetest/41.png?ts=]]..ts..[["></td> <td><img src="imagetest/42.png?ts=]]..ts..[["></td> <td><img src="imagetest/43.png?ts=]]..ts..[["></td> <td><img src="imagetest/44.png?ts=]]..ts..[["></td> <td><img src="imagetest/45.png?ts=]]..ts..[["></td> <td><img src="imagetest/46.png?ts=]]..ts..[["></td> <td><img src="imagetest/47.png?ts=]]..ts..[["></td> <td><img src="imagetest/48.png?ts=]]..ts..[["></td> <td><img src="imagetest/49.png?ts=]]..ts..[["></td> </tr> ]]) mg.write([[ <tr> <td><img src="imagetest/50.png?ts=]]..ts..[["></td> <td><img src="imagetest/51.png?ts=]]..ts..[["></td> <td><img src="imagetest/52.png?ts=]]..ts..[["></td> <td><img src="imagetest/53.png?ts=]]..ts..[["></td> <td><img src="imagetest/54.png?ts=]]..ts..[["></td> <td><img src="imagetest/55.png?ts=]]..ts..[["></td> <td><img src="imagetest/56.png?ts=]]..ts..[["></td> <td><img src="imagetest/57.png?ts=]]..ts..[["></td> <td><img src="imagetest/58.png?ts=]]..ts..[["></td> <td><img src="imagetest/59.png?ts=]]..ts..[["></td> </tr> ]]) mg.write([[ <tr> <td><img src="imagetest/60.png?ts=]]..ts..[["></td> <td><img src="imagetest/61.png?ts=]]..ts..[["></td> <td><img src="imagetest/62.png?ts=]]..ts..[["></td> <td><img src="imagetest/63.png?ts=]]..ts..[["></td> <td><img src="imagetest/64.png?ts=]]..ts..[["></td> <td><img src="imagetest/65.png?ts=]]..ts..[["></td> <td><img src="imagetest/66.png?ts=]]..ts..[["></td> <td><img src="imagetest/67.png?ts=]]..ts..[["></td> <td><img src="imagetest/68.png?ts=]]..ts..[["></td> <td><img src="imagetest/69.png?ts=]]..ts..[["></td> </tr> ]]) mg.write([[ <tr> <td><img src="imagetest/70.png?ts=]]..ts..[["></td> <td><img src="imagetest/71.png?ts=]]..ts..[["></td> <td><img src="imagetest/72.png?ts=]]..ts..[["></td> <td><img src="imagetest/73.png?ts=]]..ts..[["></td> <td><img src="imagetest/74.png?ts=]]..ts..[["></td> <td><img src="imagetest/75.png?ts=]]..ts..[["></td> <td><img src="imagetest/76.png?ts=]]..ts..[["></td> <td><img src="imagetest/77.png?ts=]]..ts..[["></td> <td><img src="imagetest/78.png?ts=]]..ts..[["></td> <td><img src="imagetest/79.png?ts=]]..ts..[["></td> </tr> ]]) mg.write([[ <tr> <td><img src="imagetest/80.png?ts=]]..ts..[["></td> <td><img src="imagetest/81.png?ts=]]..ts..[["></td> <td><img src="imagetest/82.png?ts=]]..ts..[["></td> <td><img src="imagetest/83.png?ts=]]..ts..[["></td> <td><img src="imagetest/84.png?ts=]]..ts..[["></td> <td><img src="imagetest/85.png?ts=]]..ts..[["></td> <td><img src="imagetest/86.png?ts=]]..ts..[["></td> <td><img src="imagetest/87.png?ts=]]..ts..[["></td> <td><img src="imagetest/88.png?ts=]]..ts..[["></td> <td><img src="imagetest/89.png?ts=]]..ts..[["></td> </tr> ]]) mg.write([[ <tr> <td><img src="imagetest/90.png?ts=]]..ts..[["></td> <td><img src="imagetest/91.png?ts=]]..ts..[["></td> <td><img src="imagetest/92.png?ts=]]..ts..[["></td> <td><img src="imagetest/93.png?ts=]]..ts..[["></td> <td><img src="imagetest/94.png?ts=]]..ts..[["></td> <td><img src="imagetest/95.png?ts=]]..ts..[["></td> <td><img src="imagetest/96.png?ts=]]..ts..[["></td> <td><img src="imagetest/97.png?ts=]]..ts..[["></td> <td><img src="imagetest/98.png?ts=]]..ts..[["></td> <td><img src="imagetest/99.png?ts=]]..ts..[["></td> </tr> </table> ]]) end mg.write([[ </p> <p id="timing"> Test case: all images are displayed. </p> </body> </html> ]])
apache-2.0
kitala1/darkstar
scripts/zones/Mhaura/npcs/Kamilah.lua
17
1173
----------------------------------- -- Area: Mhaura -- NPC: Kamilah -- Guild Merchant NPC: Blacksmithing Guild -- @pos -64.302 -16.000 35.261 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:sendGuild(532,8,23,2)) then player:showText(npc,SMITHING_GUILD); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
fqrouter/luci
protocols/ppp/luasrc/model/cbi/admin_network/proto_ppp.lua
24
3761
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local device, username, password local ipv6, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand, mtu device = section:taboption("general", Value, "device", translate("Modem device")) device.rmempty = false local device_suggestions = nixio.fs.glob("/dev/tty*S*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do device:value(node) end end username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", Flag, "ipv6", translate("Enable IPv6 negotiation on the PPP link")) ipv6.default = ipv6.disabled end defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end function keepalive_failure.write() end function keepalive_failure.remove() end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(1500)"
apache-2.0
kitala1/darkstar
scripts/zones/Lower_Jeuno/npcs/Garnev.lua
17
2220
----------------------------------- -- Area: Lower Jeuno -- NPC: Garnev -- Starts and Finishes Quest: Deal with Tenshodo -- @zone 245 -- @pos 30 4 -36 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(JEUNO,DEAL_WITH_TENSHODO) == QUEST_ACCEPTED and trade:hasItemQty(554,1) == true and trade:getItemCount() == 1) then player:startEvent(0x00a6); -- Ending quest end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getQuestStatus(JEUNO,A_CLOCK_MOST_DELICATE) == QUEST_ACCEPTED and player:getQuestStatus(JEUNO,DEAL_WITH_TENSHODO) == QUEST_AVAILABLE) then if(player:getFameLevel(NORG) >= 2) then player:startEvent(0x00a7); -- Start quest else player:startEvent(0x00a8); -- dialog without correct tenshodo/norg fame end else player:startEvent(0x00CF); -- 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 == 0x00a7) then player:addQuest(JEUNO,DEAL_WITH_TENSHODO); elseif(csid == 0x00a6) then player:addTitle(TRADER_OF_RENOWN); player:addKeyItem(CLOCK_TOWER_OIL); player:messageSpecial(KEYITEM_OBTAINED,CLOCK_TOWER_OIL); player:addFame(JEUNO,30); player:tradeComplete(trade); player:completeQuest(JEUNO,DEAL_WITH_TENSHODO); end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Bastok_Markets/npcs/Svana.lua
59
1040
----------------------------------- -- Area: Bastok Markets -- NPC: Svana -- Type: Weather Reporter ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0004,0,0,0,0,0,0,0,VanadielTime()); 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
kitala1/darkstar
scripts/zones/Windurst_Woods/npcs/Zahsa_Syalmhaia.lua
38
1052
----------------------------------- -- Area: Windurst Woods -- NPC: Zahsa Syalmhaia -- Type: Great War Veteran NPC -- @zone: 241 -- @pos 13.710 1.422 -83.198 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x031d); 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
hanxi/cocos2d-x-v3.1
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/PhysicsJointRotarySpring.lua
6
1379
-------------------------------- -- @module PhysicsJointRotarySpring -- @extend PhysicsJoint -------------------------------- -- @function [parent=#PhysicsJointRotarySpring] getDamping -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsJointRotarySpring] setRestAngle -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsJointRotarySpring] getStiffness -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsJointRotarySpring] setStiffness -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsJointRotarySpring] setDamping -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsJointRotarySpring] getRestAngle -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsJointRotarySpring] construct -- @param self -- @param #cc.PhysicsBody physicsbody -- @param #cc.PhysicsBody physicsbody -- @param #float float -- @param #float float -- @return PhysicsJointRotarySpring#PhysicsJointRotarySpring ret (return value: cc.PhysicsJointRotarySpring) return nil
mit
kitala1/darkstar
scripts/globals/mobskills/Geotic_Breath.lua
7
1271
--------------------------------------------- -- Geotic Breath -- -- Description: Deals Earth damage to enemies within a fan-shaped area. -- Type: Breath -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown cone -- Notes: Used only by Ouryu --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/utils"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(EFFECT_INVINCIBLE)) then return 1; elseif(target:isBehind(mob, 48) == true) then return 1; elseif (mob:AnimationSub() ~= 0) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = MobBreathMove(mob, target, 0.2, 1.25, ELE_EARTH, 1400); local angle = mob:getAngle(target); angle = mob:getRotPos() - angle; dmgmod = dmgmod * ((128-math.abs(angle))/128); utils.clamp(dmgmod, 50, 1600); local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,MOBSKILL_BREATH,MOBPARAM_EARTH,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
kitala1/darkstar
scripts/globals/mobskills/Voiceless_Storm.lua
25
1175
--------------------------------------------- -- Voiceless Storm -- Description: AOE Damage, Silence, strips Utsusemi (MOBPARAM_WIPE_SHADOWS) --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- --------------------------------------------- -- onMobSkillCheck no animation check required --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; --------------------------------------------- -- onMobSkillCheck no animation check required --------------------------------------------- function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_SILENCE; local numhits = 1; local accmod = 1; local dmgmod = 1; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_NONE,MOBPARAM_WIPE_SHADOWS); MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 60); target:delHP(dmg); return dmg; end;
gpl-3.0
darrenatdesignory/CG
scripts/dmc_buttons.lua
1
21432
--====================================================================-- -- dmc_buttons.lua -- -- by David McCuskey -- Documentation: http://docs.davidmccuskey.com/display/docs/dmc_buttons.lua --====================================================================-- --[[ Copyright (C) 2011 David McCuskey. All Rights Reserved. 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. --]] -- ===================================================== -- Imports -- ===================================================== local Utils = require( "scripts.dmc_utils" ) local Objects = require( "scripts.dmc_objects" ) local inheritsFrom = Objects.inheritsFrom local CoronaBase = Objects.CoronaBase --====================================================================-- -- Buttons base class --====================================================================-- local ButtonBase = inheritsFrom( CoronaBase ) ButtonBase.NAME = "Button Base" ButtonBase._SUPPORTED_VIEWS = nil ButtonBase._PRINT_INCLUDE = Utils.extend( CoronaBase._PRINT_INCLUDE, { '_img_info', '_img_data', '_callback' } ) ButtonBase._PRINT_EXCLUDE = Utils.extend( CoronaBase._PRINT_EXCLUDE, {} ) ButtonBase.PHASE_PRESS = "press" ButtonBase.PHASE_RELEASE = "release" -- create a base image configuration -- copied into state-specific tables ButtonBase._BASE_IMAGE_CONFIG = { source = "", width = 0, height = 0, xOffset = 0, yOffset = 0, label = nil, } -- create a base label style configuration -- copied into state-specific tables ButtonBase._BASE_STYLE_CONFIG = { font = native.systemFontBold, size = 17, color = { 255, 255, 255, 255 }, xOffset = 0, yOffset = 0, } -- ============================= -- Constructor from CoronaBase -- ============================= function ButtonBase:_init( options ) --print( "in ButtonBase:_init()" ) self:superCall( "_init" ) if self._SUPPORTED_VIEWS == nil then return end local options = options or {} -- create properties self.id = "" self._img_info = {} self._img_data = {} self._callback = { onPress = nil, onRelease = nil, onEvent = nil, } -- setup our image info structure self:_setImageInfo() end -- _setImageInfo() -- -- setup the default parameters for each image state -- function ButtonBase:_setImageInfo() local img_list = self._SUPPORTED_VIEWS local img_info = self._img_info for i=1, #img_list do local t = img_list[ i ] -- image string, eg 'active' img_info[ t ] = Utils.extend( self._BASE_IMAGE_CONFIG, {} ) img_info[ t ].style = Utils.extend( self._BASE_STYLE_CONFIG, {} ) end end -- _createView() -- -- create all of the display items for each image state -- function ButtonBase:_createView() if self._SUPPORTED_VIEWS == nil then return end local img_info, img_data = self._img_info, self._img_data local group, grp_info, img, label local img_list = self._SUPPORTED_VIEWS for i=1, #img_list do local t = img_list[ i ] -- image string, eg 'active' -- do Corona stuff grp_info = img_info[ t ] group = display.newGroup() -- save to our object for reference img_data[ t ] = group self:insert( group, true ) group:addEventListener( "touch", self ) -- setup image img = display.newImageRect( grp_info.source, grp_info.width, grp_info.height ) if img == nil then print("\nERROR: image rect source '" .. tostring( grp_info.source ) .. "'\n\n" ) end group:insert( img ) -- setup label if ( grp_info.label ) then label = display.newText( grp_info.label, 0, 0, grp_info.style.font, grp_info.style.size ) label:setTextColor( unpack( grp_info.style.color ) ) group:insert( label ) label:setReferencePoint( display.CenterReferencePoint ) label.x, label.y = grp_info.style.xOffset, grp_info.style.yOffset end end end function ButtonBase:destroy() --print( "in ButtonBase:destroy()" ) local img_info, img_data = self._img_info, self._img_data local img_list = self._SUPPORTED_VIEWS for i=1, #img_list do local obj, group local t = img_list[ i ] -- image string, eg 'active' Utils.destroy( img_info[ t ] ) img_info[ t ] = nil -- get rid of image state groups ( display objects ) group = img_data[ t ] while group.numChildren > 0 do obj = group[1] group:remove( obj ) --obj:removeSelf() end group:removeEventListener( "touch", self ) self:remove( group ) img_data[ t ] = nil end self._img_info = nil self._img_data = nil self._callback = nil -- call after we do our cleanup CoronaBase.destroy( self ) end --== PUBLIC METHODS ============================================ -- x() -- -- overridden from super -- function ButtonBase.__setters:x( value ) local img_list = self._SUPPORTED_VIEWS local i for i=1, #img_list do local t = img_list[ i ] -- 'active' local img = self._img_data[ t ] img.x = value + self._img_info[ t ].xOffset end end -- y() -- -- overridden from super -- function ButtonBase.__setters:y( value ) local img_list = self._SUPPORTED_VIEWS local i for i=1, #img_list do local t = img_list[ i ] -- 'active' local img = self._img_data[ t ] img.y = value + self._img_info[ t ].yOffset end end --====================================================================-- -- Push Button class --====================================================================-- local PushButton = inheritsFrom( ButtonBase ) PushButton.NAME = "Push Button" PushButton._SUPPORTED_VIEWS = { "up", "down" } function PushButton:_init( options ) --print( "in PushButton:_init()'") self:superCall( "_init" ) local options = options or {} local img_info, img_data = self._img_info, self._img_data -- == define our properties ==================== -- these are display objects img_data.default = nil img_data.down = nil -- setup our image info structure self:_setImageInfo() -- == overlay incoming options ==================== -- do top-level options first if options.id then self.id = options.id end if options.height then img_info.up.height = options.height img_info.down.height = options.height end if options.width then img_info.up.width = options.width img_info.down.width = options.width end if options.label then img_info.up.label = options.label img_info.down.label = options.label end if options.defaultSrc then img_info.up.source = options.defaultSrc img_info.down.source = options.defaultSrc end if options.upSrc then img_info.up.source = options.upSrc end if options.downSrc then img_info.down.source = options.downSrc end if options.style then Utils.extend( options.style, img_info.up.style ) Utils.extend( options.style, img_info.down.style ) end -- now do second-level options if options.up then Utils.extend( options.up, img_info.up ) end if options.down then Utils.extend( options.down, img_info.down ) end if options.onPress and type( options.onPress ) == "function" then self._callback.onPress = options.onPress end if options.onRelease and type( options.onRelease ) == "function" then self._callback.onRelease = options.onRelease end if options.onEvent and type( options.onEvent ) == "function" then self._callback.onEvent = options.onEvent end end function PushButton:_initComplete() local img_data = self._img_data img_data.up.isVisible = true img_data.down.isVisible = false end function PushButton:touch( e ) local phase = e.phase local img_data = self._img_data local onEvent = self._callback.onEvent local onPress = self._callback.onPress local onRelease = self._callback.onRelease local result = true local buttonEvent = {} buttonEvent.target = self buttonEvent.id = self.id -- phase "BEGAN" if phase == "began" then buttonEvent.phase = ButtonBase.PHASE_PRESS buttonEvent.name = "touch" if onPress then result = onPress( e ) elseif ( onEvent ) then result = onEvent( buttonEvent ) end self:dispatchEvent( buttonEvent ) display.getCurrentStage():setFocus( e.target ) self.isFocus = true img_data.down.isVisible = true img_data.up.isVisible = false elseif self.isFocus then -- check if touch is over the button local bounds = self.contentBounds local x,y = e.x,e.y local isWithinBounds = bounds.xMin <= x and bounds.xMax >= x and bounds.yMin <= y and bounds.yMax >= y -- phase "MOVED" if phase == "moved" then -- show correct image state img_data.down.isVisible = isWithinBounds img_data.up.isVisible = not isWithinBounds -- phase "ENDED" elseif phase == "ended" or phase == "cancelled" then if phase == "ended" then buttonEvent.phase = ButtonBase.PHASE_RELEASE buttonEvent.name = "touch" if isWithinBounds then if onRelease then result = onRelease( e ) elseif onEvent then result = onEvent( buttonEvent ) end self:dispatchEvent( buttonEvent ) end end display.getCurrentStage():setFocus( nil ) self.isFocus = false img_data.down.isVisible = false img_data.up.isVisible = true end end return result end --====================================================================-- -- BinaryButton button class --====================================================================-- local BinaryButton = inheritsFrom( ButtonBase ) BinaryButton.NAME = "Binary Button" BinaryButton._SUPPORTED_VIEWS = { 'active', 'inactive' } BinaryButton.STATE_INACTIVE = "inactive" BinaryButton.STATE_ACTIVE = "active" function BinaryButton:new( options ) local o = self:_bless() o:_init( options ) if options then o:_createView() end return o end function BinaryButton:_init( options ) self:superCall( "_init" ) local options = options or {} local img_info, img_data = self._img_info, self._img_data -- == define our properties ==================== self.state = "" -- these are display objects img_data.active = nil img_data.inactive = nil -- setup our image info structure self:_setImageInfo() -- == overlay incoming options ==================== -- do top-level options first if options.id then self.id = options.id end if options.height then img_info.active.height = options.height img_info.inactive.height = options.height end if options.width then img_info.active.width = options.width img_info.inactive.width = options.width end if options.label then img_info.active.label = options.label img_info.inactive.label = options.label end if options.defaultSrc then img_info.active.source = options.defaultSrc img_info.inactive.source = options.defaultSrc end if options.inactiveSrc then img_info.inactive.source = options.inactiveSrc end if options.activeSrc then img_info.active.source = options.activeSrc end if options.style then Utils.extend( options.style, img_info.active.style ) Utils.extend( options.style, img_info.inactive.style ) end -- now do second-level options if options.active then Utils.extend( options.active, img_info.active ) end if options.inactive then Utils.extend( options.inactive, img_info.inactive ) end if options.onPress and type( options.onPress ) == "function" then self._callback.onPress = options.onPress end if options.onRelease and type( options.onRelease ) == "function" then self._callback.onRelease = options.onRelease end if options.onEvent and type( options.onEvent ) == "function" then self._callback.onEvent = options.onEvent end end function BinaryButton:_initComplete() local img_data = self._img_data img_data.active.isVisible = false img_data.inactive.isVisible = true self:_setButtonState( BinaryButton.STATE_INACTIVE ) end function BinaryButton:getNextState() -- override this end function BinaryButton:touch( e ) local phase = e.phase local onEvent = self._callback.onEvent local onPress = self._callback.onPress local onRelease = self._callback.onRelease local result = true local buttonEvent = {} buttonEvent.target = self buttonEvent.id = self.id buttonEvent.state = self.state local current_state = self.state local other_state = self:getNextState() -- phase "BEGAN" if phase == "began" then buttonEvent.phase = ButtonBase.PHASE_PRESS buttonEvent.name = "touch" if onPress then result = onPress( e ) elseif onEvent then result = onEvent( buttonEvent ) end self:dispatchEvent( buttonEvent ) self:_setButtonImage( other_state ) display.getCurrentStage():setFocus( e.target ) self.isFocus = true elseif self.isFocus then -- check if touch is over the button local bounds = self.contentBounds local x,y = e.x,e.y local isWithinBounds = bounds.xMin <= x and bounds.xMax >= x and bounds.yMin <= y and bounds.yMax >= y -- phase "MOVED" if phase == "moved" then --print ("moved") if isWithinBounds then self:_setButtonImage( other_state ) else self:_setButtonImage( current_state ) end -- phase "ENDED" elseif phase == "ended" or phase == "cancelled" then if phase == "ended" then buttonEvent.phase = ButtonBase.PHASE_RELEASE buttonEvent.name = "touch" if isWithinBounds then local state = BinaryButton.STATE_INACTIVE if self.state == state then state = BinaryButton.STATE_ACTIVE end self:_setButtonState( state ) buttonEvent.state = self.state if onRelease then result = onRelease( e ) elseif onEvent then result = onEvent( buttonEvent ) end self:dispatchEvent( buttonEvent ) end end display.getCurrentStage():setFocus( nil ) self.isFocus = false self:_setButtonImage() end end return result end function BinaryButton:_setButtonState( value ) -- no need to update if the same state if self.state == value then return end -- save the new state self.state = value self:_setButtonImage( value ) end function BinaryButton:_setButtonImage( value ) local value = value or self.state local img_data = self._img_data -- change button view to reflect the current state local showInactive = value == BinaryButton.STATE_INACTIVE img_data.inactive.isVisible = showInactive img_data.active.isVisible = not showInactive end --====================================================================-- -- Toggle Button class --====================================================================-- local ToggleButton = inheritsFrom( BinaryButton ) ToggleButton.NAME = "Toggle Button" -- for use with "down" image state function ToggleButton:getNextState() local state = BinaryButton.STATE_INACTIVE if self.state == state then state = BinaryButton.STATE_ACTIVE end return state end --====================================================================-- -- Radio Button class --====================================================================-- local RadioButton = inheritsFrom( BinaryButton ) RadioButton.NAME = "Radio Button" -- for use with "down" image state function RadioButton:getNextState() return BinaryButton.STATE_ACTIVE end --====================================================================-- -- Button Group base class --====================================================================-- local ButtonGroupBase = inheritsFrom( CoronaBase ) ButtonGroupBase.NAME = "Button Group Base" ButtonGroupBase._PRINT_INCLUDE = Utils.extend( CoronaBase._PRINT_INCLUDE, { '_group_buttons', '_selected_button' } ) ButtonGroupBase._PRINT_EXCLUDE = Utils.extend( CoronaBase._PRINT_EXCLUDE, {} ) function ButtonGroupBase:new( options ) local o = self:_bless() o:_init( options ) return o end function ButtonGroupBase:_init( options ) self:superCall( "_init" ) -- create properties self.setFirstActive = nil -- whether first load button is set to state active self._group_buttons = {} -- table of our buttons to control self._selected_button = nil -- this is handle to real object, not display -- overlay incoming options if options then Utils.extend( options, self ) end end function ButtonGroupBase:add( obj, params ) local params = params or {} -- these are options which can be passed in local opts = { setActive = false, } -- process incoming options Utils.extend( params, opts ) -- if this is the first button, make it active if ( self.setFirstActive and #self._group_buttons == 0 ) or opts.setActive then self:_setButtonGroupState( ToggleButton.STATE_INACTIVE, opts ) obj:_setButtonState( ToggleButton.STATE_ACTIVE ) self._selected_button = obj end -- do corona stuff self:insert( obj.display ) obj:addEventListener( "touch", self ) -- add to our button array table.insert( self._group_buttons, obj ) end function ButtonGroupBase:destroy() --print ( "in ButtonGroupBase:destroy()") self._selected_button = nil -- remove our buttons while #self._group_buttons > 0 do local button = table.remove( self._group_buttons, 1 ) button:removeEventListener( "touch", self ) button:destroy() end self._group_buttons = nil -- call after we do our cleanup CoronaBase.destroy( self ) end function ButtonGroupBase:_setButtonGroupState( value ) for i=1, table.getn( self._group_buttons ) do self._group_buttons[ i ]:_setButtonState( value ) end end --====================================================================-- -- Radio Group class --====================================================================-- local RadioGroup = inheritsFrom( ButtonGroupBase ) RadioGroup.NAME = "Radio Group" function RadioGroup:_init( options ) -- initialize with properties from super class self:superCall( "_init" ) -- add new properties specific to our class self.setFirstActive = true -- for first loaded button -- set our properties with incoming options if options then Utils.extend( options, self ) end end function RadioGroup:touch( e ) local btn = e.target local button_label = e.id if e.phase == ButtonBase.PHASE_RELEASE then local sendEvent = true if self._selected_button == btn then sendEvent = false end -- turn all buttons off self:_setButtonGroupState( ToggleButton.STATE_INACTIVE ) -- save selected button and set it to ON self._selected_button = btn btn:_setButtonState( ToggleButton.STATE_ACTIVE ) if sendEvent then self:dispatchEvent( { name="change", target=btn, label=button_label, state=btn.state } ) end return true end end --====================================================================-- -- Toggle Group class --====================================================================-- local ToggleGroup = inheritsFrom( ButtonGroupBase ) ToggleGroup.NAME = "Toggle Group" function ToggleGroup:_init( options ) -- initialize with properties from above self:superCall( "_init" ) -- add new properties specific to our class self.setFirstActive = false -- for first loaded button -- set our properties with incoming options if options then Utils.extend( options, self ) end end function ToggleGroup:touch( e ) local btn = e.target local btn_label = e.id if e.phase == ButtonBase.PHASE_RELEASE then -- if we have different button and the new state is STATE_ACTIVE if self._selected_button ~= btn and e.state == ToggleButton.STATE_ACTIVE then -- turn all buttons off self:_setButtonGroupState( ToggleButton.STATE_INACTIVE ) -- save button and set it to ON self._selected_button = btn btn:_setButtonState( ToggleButton.STATE_ACTIVE ) end self:dispatchEvent( { name="change", target=btn, label=btn_label, state=btn.state } ) return true end end -- ========================================================= -- Button Factory -- ========================================================= local Buttons = {} -- export class instantiations for direct access Buttons.ButtonBase = ButtonBase Buttons.PushButton = PushButton Buttons.BinaryButton = BinaryButton Buttons.ToggleButton = ToggleButton Buttons.RadioButton = RadioButton Buttons.ButtonGroupBase = ButtonGroupBase Buttons.RadioGroup = RadioGroup Buttons.ToggleGroup = ToggleGroup -- Button factory method function Buttons.create( class_type, options ) local o if class_type == "push" then o = PushButton:new( options ) elseif class_type == "radio" then o = RadioButton:new( options ) elseif class_type == "toggle" then o = ToggleButton:new( options ) elseif class_type == "radioGroup" then o = RadioGroup:new( options ) elseif class_type == "toggleGroup" then o = ToggleGroup:new( options ) else print ( "ERROR: Button Class Factory - unknown class type: " .. class_type ) end return o end return Buttons
mit
kitala1/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Zabahf.lua
19
1646
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Zabahf -- Type: Standard NPC -- @pos -90.070 -1 10.140 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local gotItAllProg = player:getVar("gotitallCS"); if(gotItAllProg == 1 or gotItAllProg == 3) then player:startEvent(0x0215); elseif(gotItAllProg == 2) then player:startEvent(0x020b); elseif(gotItAllProg == 5) then player:startEvent(0x021a); elseif(gotItAllProg == 6) then player:startEvent(0x021c); elseif(gotItAllProg == 7) then player:startEvent(0x0217); elseif(player:getQuestStatus(AHT_URHGAN,GOT_IT_ALL) == QUEST_COMPLETED) then player:startEvent(0x0212); 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 == 0x020b)then player:setVar("gotitallCS",3); end end;
gpl-3.0
NiFiLocal/nifi-minifi-cpp
thirdparty/civetweb-1.10/test/page_keep_alive_chunked.lua
11
2018
-- Set keep_alive. The return value specifies if this is possible at all. canKeepAlive = mg.keep_alive(true) now = os.date("!%a, %d %b %Y %H:%M:%S") -- First send the http headers mg.write("HTTP/1.1 200 OK\r\n") mg.write("Content-Type: text/html\r\n") mg.write("Date: " .. now .. " GMT\r\n") mg.write("Cache-Control: no-cache\r\n") mg.write("Last-Modified: " .. now .. " GMT\r\n") if not canKeepAlive then mg.write("Connection: close\r\n") mg.write("\r\n") mg.write("<html><body>Keep alive not possible!</body></html>") return end if mg.request_info.http_version ~= "1.1" then -- wget will use HTTP/1.0 and Connection: keep-alive, so chunked transfer is not possible mg.write("Connection: close\r\n") mg.write("\r\n") mg.write("<html><body>Chunked transfer is only possible for HTTP/1.1 requests!</body></html>") mg.keep_alive(false) return end -- use chunked encoding (http://www.jmarshall.com/easy/http/#http1.1c2) mg.write("Cache-Control: max-age=0, must-revalidate\r\n") --mg.write("Cache-Control: no-cache\r\n") --mg.write("Cache-Control: no-store\r\n") mg.write("Connection: keep-alive\r\n") mg.write("Transfer-Encoding: chunked\r\n") mg.write("\r\n") -- function to send a chunk function send(str) local len = string.len(str) mg.write(string.format("%x\r\n", len)) mg.write(str.."\r\n") end -- send the chunks send("<html>") send("<head><title>Civetweb Lua script chunked transfer test page</title></head>") send("<body>\n") fileCnt = 0 if lfs then send("Files in " .. lfs.currentdir()) send('\n<table border="1">\n') send('<tr><th>name</th><th>type</th><th>size</th></tr>\n') for f in lfs.dir(".") do local at = lfs.attributes(f); if at then send('<tr><td>' .. f .. '</td><td>' .. at.mode .. '</td><td>' .. at.size .. '</td></tr>\n') end fileCnt = fileCnt + 1 end send("</table>\n") end send(fileCnt .. " entries (" .. now .. " GMT)\n") send("</body>") send("</html>") -- end send("")
apache-2.0